licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
1339
module Constants using HTTP using RelocatableFolders export PACKAGE_DIR, DATA_PATH, GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS, CONNECT, TRACE, HTTP_METHODS, WEBSOCKET, STREAM, SPECIAL_METHODS, METHOD_ALIASES, TYPE_ALIASES, SWAGGER_VERSION, REDOC_VERSION # Generate a reliable path to our package directory const PACKAGE_DIR = @path @__DIR__ # Generate a reliable path to our internal data folder that works when the # package is used with PackageCompiler.jl const DATA_PATH = @path joinpath(@__DIR__, "..", "data") # HTTP Methods const GET = "GET" const POST = "POST" const PUT = "PUT" const DELETE = "DELETE" const PATCH = "PATCH" const HEAD = "HEAD" const OPTIONS = "OPTIONS" const CONNECT = "CONNECT" const TRACE = "TRACE" const HTTP_METHODS = Set{String}([GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS, CONNECT, TRACE]) # Special Methods const WEBSOCKET = "WEBSOCKET" const STREAM = "STREAM" const SPECIAL_METHODS = Set{String}([WEBSOCKET, STREAM]) # Sepcial Method Aliases const METHOD_ALIASES = Dict{String,String}( WEBSOCKET => GET, STREAM => GET ) const TYPE_ALIASES = Dict{String, Type}( WEBSOCKET => HTTP.WebSockets.WebSocket, STREAM => HTTP.Streams.Stream ) const SWAGGER_VERSION = "[email protected]" const REDOC_VERSION = "[email protected]" end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
3260
module AppContext import Base: @kwdef, wait, close, isopen import Base.Threads: ReentrantLock using HTTP using HTTP: Server, Router using ..Types export Context, CronContext, TasksContext, Documenation, Service, history, wait, close, isopen function defaultSchema() :: Dict Dict( "openapi" => "3.0.0", "info" => Dict( "title" => "API Overview", "version" => "1.0.0" ), "paths" => Dict() ) end @kwdef struct CronContext run :: Ref{Bool} = Ref{Bool}(false) # Flag used to stop all running jobs active_jobs :: Set{ActiveCron} = Set() # Set of all running tasks registered_jobs :: Set{RegisteredCron} = Set() # Set of cron expressions and functions (expression, name, function) job_definitions :: Set{CronDefinition} = Set() # Cron job definitions registered through the router() (path, httpmethod, cron_expression) end @kwdef struct TasksContext active_tasks :: Set{ActiveTask} = Set() # Set of all running tasks which contains (task_id, timer) registered_tasks :: Set{RegisteredTask} = Set() # Vector of repeat task definitions (path, httpmethod, interval) task_definitions :: Set{TaskDefinition} = Set() # Set of all registered task definitions () end @kwdef struct Documenation enabled :: Ref{Bool} = Ref{Bool}(true) router :: Ref{Nullable{Router}} = Ref{Nullable{Router}}(nothing) # used for docs & metrics internal endpoints docspath :: Ref{String} = Ref{String}("/docs") schemapath :: Ref{String} = Ref{String}("/schema") schema :: Dict = defaultSchema() taggedroutes :: Dict{String, TaggedRoute} = Dict{String, TaggedRoute}() # used to group routes by tag end @kwdef struct Service server :: Ref{Nullable{Server}} = Ref{Nullable{Server}}(nothing) router :: Router = Router() custommiddleware :: Dict{String, Tuple} = Dict{String, Tuple}() middleware_cache :: Dict{String, Function} = Dict{String, Function}() history :: History = History(1_000_000) history_lock :: ReentrantLock = ReentrantLock() end @kwdef struct Context service :: Service = Service() docs :: Documenation = Documenation() cron :: CronContext = CronContext() tasks :: TasksContext = TasksContext() end Base.isopen(service::Service) = !isnothing(service.server[]) && isopen(service.server[]) Base.close(service::Service) = !isnothing(service.server[]) && close(service.server[]) Base.wait(service::Service) = !isnothing(service.server[]) && wait(service.server[]) # @eval begin # """ # Context(ctx::Context; kwargs...) # Create a new `Context` object by copying an existing one and optionally overriding some of its fields with keyword arguments. # """ # function Context(ctx::Context; $([Expr(:kw ,k, :(ctx.$k)) for k in fieldnames(Context)]...)) # return Context($(fieldnames(Context)...)) # end # end end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
24865
module Core using Base: @kwdef using HTTP using HTTP: Router using Sockets using JSON3 using Base using Dates using Reexport using RelocatableFolders using DataStructures: CircularDeque import Base.Threads: lock include("util.jl"); @reexport using .Util include("types.jl"); @reexport using .Types include("constants.jl"); @reexport using .Constants include("handlers.jl"); @reexport using .Handlers include("context.jl"); @reexport using .AppContext include("middleware.jl"); @reexport using .Middleware include("routerhof.jl"); @reexport using .RouterHOF include("cron.jl"); @reexport using .Cron include("repeattasks.jl"); @reexport using .RepeatTasks include("metrics.jl"); @reexport using .Metrics include("reflection.jl"); @reexport using .Reflection include("extractors.jl"); @reexport using .Extractors include("autodoc.jl"); @reexport using .AutoDoc export start, serve, serveparallel, terminate, internalrequest, staticfiles, dynamicfiles kitten_title = raw""" , , /|_/ o _|_ _|_ _ |\ | | | |/ /|/| | \_/ |/ |_/ |_/ |_/ | |_/ """ function serverwelcome(host::String, port::Int, docs::Bool, metrics::Bool, parallel::Bool, docspath::String) printstyled(kitten_title, color=:blue, bold=true) @info "πŸ“¦ Version 0.1.0 (2024-06-18)" @info "βœ… Started server: http://$host:$port" if docs @info "πŸ“– Documentation: http://$host:$port$docspath" end if docs && metrics @info "πŸ“Š Metrics: http://$host:$port$docspath/metrics" end if parallel @info "πŸš€ Running in parallel mode with $(Threads.nthreads()) threads" end end """ serve(; middleware::Vector=[], handler=stream_handler, host="127.0.0.1", port=8080, async=false, parallel=false, serialize=true, catch_errors=true, docs=true, metrics=true, show_errors=true, show_banner=true, docs_path="/docs", schema_path="/schema", kwargs...) Start the webserver with your own custom request handler """ function serve(ctx::Context; middleware = [], handler = stream_handler, host = "127.0.0.1", port = 8080, async = false, parallel = false, serialize = true, catch_errors= true, docs = true, metrics = true, show_errors = true, show_banner = true, docs_path = "/docs", schema_path = "/schema", kwargs...) :: Server # overwrite docs & schema paths ctx.docs.enabled[] = docs ctx.docs.docspath[] = docs_path ctx.docs.schemapath[] = schema_path # intitialize documenation router (used by docs and metrics) ctx.docs.router[] = Router() # compose our middleware ahead of time (so it only has to be built up once) configured_middelware = setupmiddleware(ctx; middleware, serialize, catch_errors, docs, metrics, show_errors) # setup the primary stream handler function (can be customized by the caller) handle_stream = handler(configured_middelware) if parallel if Threads.nthreads() <= 1 @warn "serveparallel() only has 1 thread available to use, try launching julia like this: \"julia -t auto\" to leverage multiple threads" end if haskey(kwargs, :queuesize) @warn "Deprecated: The `queuesize` parameter is no longer used / supported in serveparallel()" end # wrap top level handler with parallel handler handle_stream = parallel_stream_handler(handle_stream) end # The cleanup of resources are put at the topmost level in `methods.jl` return startserver(ctx; host, port, show_banner, docs, metrics, parallel, async, kwargs, start=(kwargs) -> HTTP.serve!(handle_stream, host, port; kwargs...)) end """ terminate(ctx) stops the webserver immediately """ function terminate(context::Context) if isopen(context.service) # stop background cron jobs stopcronjobs(context.cron) clearcronjobs(context.cron) # stop repeating tasks stoptasks(context.tasks) cleartasks(context.tasks) # stop server close(context.service) end end """ Register all cron jobs defined through our router() HOF """ function registercronjobs(ctx::Context) for job in ctx.cron.job_definitions path, httpmethod, expression = job.path, job.httpmethod, job.expression cron(ctx.cron.registered_jobs, expression, path, () -> internalrequest(ctx, HTTP.Request(httpmethod, path))) end end """ Register all repeat tasks defined through our router() HOF """ function registertasks(ctx::Context) for task_def in ctx.tasks.task_definitions path, httpmethod, interval = task_def.path, task_def.httpmethod, task_def.interval task(ctx.tasks.registered_tasks, interval, path, () -> internalrequest(ctx, HTTP.Request(httpmethod, path))) end end """ decorate_request(ip::IPAddr) This function can be used to add additional usefull metadata to the incoming request context dictionary. At the moment, it just inserts the caller's ip address """ function decorate_request(ip::IPAddr, stream::HTTP.Stream) return function (handle) return function (req::HTTP.Request) req.context[:ip] = ip req.context[:stream] = stream handle(req) end end end """ This is our root stream handler used in both serve() and serveparallel(). This function determines how we handle all incoming requests """ function stream_handler(middleware::Function) return function (stream::HTTP.Stream) # extract the caller's ip address ip, _ = Sockets.getpeername(stream) # build up a streamhandler to handle our incoming requests handle_stream = HTTP.streamhandler(middleware |> decorate_request(ip, stream)) # handle the incoming request return handle_stream(stream) end end """ parallel_stream_handler(handle_stream::Function) This function uses `Threads.@spawn` to schedule a new task on any available thread. Inside this task, `@async` is used for cooperative multitasking, allowing the task to yield during I/O operations. """ function parallel_stream_handler(handle_stream::Function) function (stream::HTTP.Stream) task = Threads.@spawn begin handle = @async handle_stream(stream) wait(handle) end wait(task) end end """ Compose the user & internally defined middleware functions together. Practically, this allows users to 'chain' middleware functions like `serve(handler1, handler2, handler3)` when starting their application and have them execute in the order they were passed (left to right) for each incoming request """ function setupmiddleware(ctx::Context; middleware::Vector=[], docs::Bool=true, metrics::Bool=true, serialize::Bool=true, catch_errors::Bool=true, show_errors=true)::Function # determine if we have any special router or route-specific middleware custom_middleware = !isempty(ctx.service.custommiddleware) ? [compose(ctx.service.router, middleware, ctx.service.custommiddleware, ctx.service.middleware_cache)] : reverse(middleware) # Docs middleware should only be available at runtime when serve() or serveparallel is called docs_middleware = docs && !isnothing(ctx.docs.router[]) ? [DocsMiddleware(ctx.docs.router[], ctx.docs.docspath[])] : [] # check if we should use our default serialization middleware function serializer = serialize ? [DefaultSerializer(catch_errors; show_errors)] : [] # check if we need to track metrics collect_metrics = metrics ? [MetricsMiddleware(ctx.service, metrics)] : [] # combine all our middleware functions return reduce(|>, [ ctx.service.router, serializer..., custom_middleware..., collect_metrics..., docs_middleware..., ]) end """ Internal helper function to launch the server in a consistent way """ function startserver(ctx::Context; host, port, show_banner=false, docs=false, metrics=false, parallel=false, async=false, kwargs, start)::Server docs && setupdocs(ctx) metrics && setupmetrics(ctx) show_banner && serverwelcome(host, port, docs, metrics, parallel, ctx.docs.docspath[]) # start the HTTP server ctx.service.server[] = start(preprocesskwargs(kwargs)) # Register & Start all repeat tasks registertasks(ctx) starttasks(ctx.tasks) # Register & Start all cron jobs registercronjobs(ctx) startcronjobs(ctx.cron) if !async try wait(ctx.service) catch error !isa(error, InterruptException) && @error "ERROR: " exception = (error, catch_backtrace()) finally println() # this pushes the "[ Info: Server on 127.0.0.1:8080 closing" to the next line end end return ctx.service.server[] end """ Used to overwrite defaults to any incoming keyword arguments """ function preprocesskwargs(kwargs) kwargs_dict = Dict{Symbol,Any}(kwargs) # always set to streaming mode (regardless of what was passed) kwargs_dict[:stream] = true # user passed no loggin preferences - use defualt logging format if isempty(kwargs_dict) || !haskey(kwargs_dict, :access_log) kwargs_dict[:access_log] = logfmt"$time_iso8601 - $remote_addr:$remote_port - \"$request\" $status" end return kwargs_dict end """ internalrequest(req::HTTP.Request; middleware::Vector=[], serialize::Bool=true, catch_errors::Bool=true) Directly call one of our other endpoints registered with the router, using your own middleware and bypassing any globally defined middleware """ function internalrequest(ctx::Context, req::HTTP.Request; middleware::Vector=[], metrics::Bool=false, serialize::Bool=true, catch_errors=true)::HTTP.Response req.context[:ip] = "INTERNAL" # label internal requests return req |> setupmiddleware(ctx; middleware, metrics, serialize, catch_errors) end function DocsMiddleware(docsrouter::Router, docspath::String) return function (handle) return function (req::HTTP.Request) if startswith(req.target, docspath) response = docsrouter(req) else response = handle(req) end format_response!(req, response) return req.response end end end """ Create a default serializer function that handles HTTP requests and formats the responses. """ function DefaultSerializer(catch_errors::Bool; show_errors::Bool) return function (handle) return function (req::HTTP.Request) return handlerequest(catch_errors; show_errors) do response = handle(req) format_response!(req, response) return req.response end end end end function MetricsMiddleware(service::Service, catch_errors::Bool) return function (handler) return function (req::HTTP.Request) return handlerequest(catch_errors) do start_time = time() # Handle the request response = handler(req) # Log response time response_time = (time() - start_time) * 1000 # Make sure we update the History object in a thread-safe way lock(service.history_lock) do if response.status == 200 push_history(service.history, HTTPTransaction( string(req.context[:ip]), string(req.target), now(UTC), response_time, true, response.status, nothing )) else push_history(service.history, HTTPTransaction( string(req.context[:ip]), string(req.target), now(UTC), response_time, false, response.status, text(response) )) end end return response end end end end function parse_route(httpmethod::String, route::Union{String,Function})::String # check if path is a callable function (that means it's a router higher-order-function) if isa(route, Function) # This is true when the user passes the router() directly to the path. # We call the generated function without args so it uses the default args # from the parent function. if countargs(route) == 1 route = route() end # If it's still a function, then that means this is from the 3rd inner function # defined in the createrouter() function. if countargs(route) == 2 route = route(httpmethod) end end # if the route is still a function, then it's from the 3rd inner function # defined in the createrouter() function when the 'router()' function is passed directly. if isa(route, Function) route = route(httpmethod) end !isa(route, String) && throw("The `route` parameter is not a String, but is instead a: $(typeof(route))") return route end function parse_func_params(route::String, func::Function) """ Parsing Rules: 1. path parameters are detected by their presence in the route string 2. query parameters are not in the route string and can have default values 3. path extractors can be used instead of traditional path parameters 4. extrators can be used alongside traditional path & query params """ info = splitdef(func, start=2) # skip the indentifying first arg # collect path param definitions from the route string hasBraces = r"({)|(})" route_params = Vector{Symbol}() for value in HTTP.URIs.splitpath(route) if contains(value, hasBraces) variable = replace(value, hasBraces => "") |> strip push!(route_params, Symbol(variable)) end end # Identify all path & query params (can be declared as regular variables or extractors) pathnames = Vector{Symbol}() querynames = Vector{Symbol}() headernames = Vector{Symbol}() bodynames = Vector{Symbol}() path_params = [] query_params = [] header_params = [] body_params = [] for param in info.args # case 1: it's an extractor type if param.type <: Extractor innner_type = param.type |> extracttype # push the variables from the struct into the params array if param.type <: Path append!(pathnames, fieldnames(innner_type)) push!(path_params, param) elseif param.type <: Query append!(querynames, fieldnames(innner_type)) push!(query_params, param) elseif param.type <: Header append!(headernames, fieldnames(innner_type)) push!(header_params, param) else append!(bodynames, fieldnames(innner_type)) push!(body_params, param) end # case 2: It's a path parameter elseif param.name in route_params push!(pathnames, param.name) push!(path_params, param) # Case 3: It's a query parameter else push!(querynames, param.name) push!(query_params, param) end end # make sure all the path params are present in the route if !isempty(route_params) missing_params = [ route_param for route_param in route_params if !any(path_param -> path_param == route_param, pathnames) ] if !isempty(missing_params) throw(ArgumentError("Your request handler is missing path parameters: {$(join(missing_params, ", "))} defined in this route: $route")) end end return ( info=info, pathparams=path_params, pathnames=pathnames, queryparams=query_params, querynames=querynames, headers=header_params, headernames=headernames, bodyargs=body_params, bodynames=bodynames ) end """ register(ctx::Context, httpmethod::String, route::String, func::Function) Register a request handler function with a path to the ROUTER """ function register(ctx::Context, httpmethod::String, route::Union{String,Function}, func::Function) # Parse & validate path parameters route = parse_route(httpmethod, route) func_details = parse_func_params(route, func) # only generate the schema if the docs are enabled if ctx.docs.enabled[] # Pull out the request parameters queryparams = func_details.queryparams pathparams = func_details.pathparams headers = func_details.headers bodyparams = func_details.bodyargs # Register the route schema with out autodocs module registerschema(ctx.docs, route, httpmethod, pathparams, queryparams, headers, bodyparams, Base.return_types(func)) end # Register the route with the router registerhandler(ctx.service.router, httpmethod, route, func, func_details) end """ This alternaive registers a route wihout generating any documentation for it. Used primarily for internal routes like docs and metrics """ function register(router::Router, httpmethod::String, route::Union{String,Function}, func::Function) # Parse & validate path parameters route = parse_route(httpmethod, route) func_details = parse_func_params(route, func) # Register the route with the router registerhandler(router, httpmethod, route, func, func_details) end """ Given an incoming request, parse out each argument and prepare it to get passed to the corresponding handler. """ function extract_params(req::HTTP.Request, func_details)::Vector{Any} info = func_details.info pathparams = func_details.pathnames queryparams = func_details.querynames lazy_req = LazyRequest(request=req) parameters = Vector{Any}() for param in info.sig name = string(param.name) if param.type <: Extractor push!(parameters, extract(param, lazy_req)) elseif param.name in pathparams raw_pathparams = Types.pathparams(lazy_req) push!(parameters, parseparam(param.type, raw_pathparams[name])) elseif param.name in queryparams raw_queryparams = Types.queryvars(lazy_req) # if the query parameter is not present, use the default value if available if !haskey(raw_queryparams, name) && param.hasdefault push!(parameters, param.default) else push!(parameters, parseparam(param.type, raw_queryparams[name])) end end end return parameters end function registerhandler(router::Router, httpmethod::String, route::String, func::Function, func_details::NamedTuple) # Get information about the function's arguments method = first(methods(func)) no_args = method.nargs == 1 # check if handler has a :request kwarg info = func_details.info has_req_kwarg = :request in Base.kwarg_decl(method) has_path_params = !isempty(info.args) # Generate the function handler based on the input types arg_type = first_arg_type(method, httpmethod) func_handle = select_handler(arg_type, has_req_kwarg, has_path_params; no_args=no_args) # Figure out if we need to include parameter parsing logic for this route if isempty(info.sig) handle = function (req::HTTP.Request) func_handle(req, func) end else handle = function (req::HTTP.Request) path_parameters = extract_params(req, func_details) func_handle(req, func; pathParams=path_parameters) end end # Use method aliases for special methods resolved_httpmethod = get(METHOD_ALIASES, httpmethod, httpmethod) HTTP.register!(router, resolved_httpmethod, route, handle) end function setupdocs(ctx::Context) setupdocs(ctx.docs.router[], ctx.docs.schema, ctx.docs.docspath[], ctx.docs.schemapath[]) end # add the swagger and swagger/schema routes function setupdocs(router::Router, schema::Dict, docspath::String, schemapath::String) full_schema = "$docspath$schemapath" register(router, "GET", "$docspath", () -> swaggerhtml(full_schema, docspath)) register(router, "GET", "$docspath/swagger", () -> swaggerhtml(full_schema, docspath)) register(router, "GET", "$docspath/redoc", () -> redochtml(full_schema, docspath)) register(router, "GET", full_schema, () -> schema) end function setupmetrics(context::Context) setupmetrics(context.docs.router[], context.service.history, context.docs.docspath[], context.service.history_lock) end # add the swagger and swagger/schema routes function setupmetrics(router::Router, history::History, docspath::String, history_lock::ReentrantLock) # This allows us to customize the path to the metrics dashboard function loadfile(filepath)::String content = readfile(filepath) # only replace content if it's in a generated file ext = lowercase(last(splitext(filepath))) if ext in [".html", ".css", ".js"] return replace(content, "/123e4567-e89b-12d3-a456-426614174000/" => "$docspath/metrics/") else return content end end staticfiles(router, "$DATA_PATH/dashboard", "$docspath/metrics"; loadfile=loadfile) # Create a thread-safe copy of the history object and it's internal data function safe_get_transactions(history::History)::Vector{HTTPTransaction} transactions = [] lock(history_lock) do transactions = collect(history) end return transactions end function innermetrics(req::HTTP.Request, window::Nullable{Int}, latest::Nullable{DateTime}) # create a threadsafe copy of the current transactions in our history object transactions = safe_get_transactions(history) # Figure out how far back to read from the history object window_value = !isnothing(window) && window > 0 ? Minute(window) : nothing lower_bound = !isnothing(latest) ? latest : window_value return Dict( "server" => server_metrics(transactions, nothing), "endpoints" => all_endpoint_metrics(transactions, nothing), "errors" => error_distribution(transactions, nothing), "avg_latency_per_second" => avg_latency_per_unit(transactions, Second, lower_bound) |> prepare_timeseries_data(), "requests_per_second" => requests_per_unit(transactions, Second, lower_bound) |> prepare_timeseries_data(), "avg_latency_per_minute" => avg_latency_per_unit(transactions, Minute, lower_bound) |> prepare_timeseries_data(), "requests_per_minute" => requests_per_unit(transactions, Minute, lower_bound) |> prepare_timeseries_data() ) end register(router, GET, "$docspath/metrics/data/{window}/{latest}", innermetrics) end """ staticfiles(folder::String, mountdir::String; headers::Vector{Pair{String,String}}=[], loadfile::Union{Function,Nothing}=nothing) Mount all files inside the /static folder (or user defined mount point). The `headers` array will get applied to all mounted files """ function staticfiles(router::HTTP.Router, folder::String, mountdir::String="static"; headers::Vector=[], loadfile::Nullable{Function}=nothing ) # remove the leading slash if first(mountdir) == '/' mountdir = mountdir[2:end] end function addroute(currentroute, filepath) resp = file(filepath; loadfile=loadfile, headers=headers) register(router, GET, currentroute, () -> resp) end mountfolder(folder, mountdir, addroute) end """ dynamicfiles(folder::String, mountdir::String; headers::Vector{Pair{String,String}}=[], loadfile::Union{Function,Nothing}=nothing) Mount all files inside the /static folder (or user defined mount point), but files are re-read on each request. The `headers` array will get applied to all mounted files """ function dynamicfiles(router::Router, folder::String, mountdir::String="static"; headers::Vector=[], loadfile::Nullable{Function}=nothing ) # remove the leading slash if first(mountdir) == '/' mountdir = mountdir[2:end] end function addroute(currentroute, filepath) register(router, GET, currentroute, () -> file(filepath; loadfile=loadfile, headers=headers)) end mountfolder(folder, mountdir, addroute) end end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
19046
module Cron using Base: @kwdef using Dates using ..Types: ActiveCron, RegisteredCron, Nullable using ..AppContext: CronContext export cron, startcronjobs, stopcronjobs, clearcronjobs """ Builds a new CRON job definition and appends it to hte list of cron jobs """ function cron(cronjobs::Set{RegisteredCron}, expression::String, name::String, f::Function) job_id = hash((expression, name, f)) job = RegisteredCron(job_id, expression, name, f) push!(cronjobs, job) end """ stopcronjobs() Stop each background task by toggling a global reference that all cron jobs reference """ function stopcronjobs(cron::CronContext) cron.run[] = false # clear the set of all running job ids empty!(cron.active_jobs) end """ Clears all cron job defintions """ function clearcronjobs(cron::CronContext) # clear all job definitions empty!(cron.registered_jobs) end """ startcronjobs() Start all the cron cronjobs within their own async task. Each individual task will loop conintually and sleep untill the next time it's suppost to """ function startcronjobs(cron::CronContext) if isempty(cron.registered_jobs) return end # set the global run flag to true cron.run[] = true # pull out all ids for the current running tasks running_tasks = Set{UInt}(job.id for job in cron.active_jobs) # filter out any jobs that are already running filtered_jobs = filter(cron.registered_jobs) do cronjob # (job_id, expression, name, func) = cronjob if cronjob.id in running_tasks printstyled("[ Cron: $(cronjob.name) is already running\n", color = :yellow) return false else return true end end # exit function early if no jobs to start if isempty(filtered_jobs) return end println() printstyled("[ Starting $(length(filtered_jobs)) Cron Job(s)\n", color = :green, bold = true) for job in filtered_jobs job_id, expression, name, func = job.id, job.expression, job.name, job.action # add job it to set of running jobs push!(cron.active_jobs, ActiveCron(job_id, job)) printstyled("[ Cron: ", color = :green, bold = true) println("{ expr: $expression, name: $name }") # Assuming name and expression are your variables Threads.@spawn begin try while cron.run[] # get the current datetime object current_time::DateTime = now() # get the next datetime object that matches this cron expression next_date = next(expression, current_time) # figure out how long we need to wait ms_to_wait = sleep_until(current_time, next_date) # breaking the sleep into 1-second intervals while ms_to_wait > 0 && cron.run[] sleep_time = min(1000, ms_to_wait) # Sleep for 1 second or the remaining time sleep(Millisecond(sleep_time)) ms_to_wait -= sleep_time # Reduce the wait time end # Execute the function if it's time and if we are still running if ms_to_wait <= 0 && cron.run[] try @async func() # for ordinary functions catch error @error "ERROR in CRON job { id: $job_id, expr: $expression, name: $name }: " exception=(error, catch_backtrace()) end end end finally # remove job id if the job fails delete!(cron.active_jobs, job_id) end end end end weeknames = Dict( "SUN" => 7, "MON" => 1, "TUE" => 2, "WED" => 3, "THU" => 4, "FRI" => 5, "SAT" => 6, ) monthnames = Dict( "JAN" => 1, "FEB" => 2, "MAR" => 3, "APR" => 4, "MAY" => 5, "JUN" => 6, "JUL" => 7, "AUG" => 8, "SEP" => 9, "OCT" => 10, "NOV" => 11, "DEC" => 12 ) function translate(input::AbstractString) if haskey(weeknames, input) return weeknames[input] elseif haskey(monthnames, input) return monthnames[input] else return input end end function customparse(type, input) if isa(input, type) return input end return parse(type, input) end # https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/support/CronExpression.html # https://crontab.cronhub.io/ """ return the date for the last weekday (Friday) of the month """ function lastweekdayofmonth(time::DateTime) current = lastdayofmonth(time) while dayofweek(current) > 5 current -= Day(1) end return current end function isweekday(time::DateTime) daynumber = dayofweek(time) return daynumber >= 1 && daynumber <= 5 end """ Return the date of the weekday that's nearest to the nth day of the month """ function nthweekdayofmonth(time::DateTime, n::Int64) if n < 1 || n > Dates.daysinmonth(time) error("n must be between 1 and $(Dates.daysinmonth(time))") end target = DateTime(year(time), month(time), day(n)) if isweekday(target) return target end current_month = month(time) before = DateTime(year(time), month(time), day(max(1, n-1))) after = DateTime(year(time), month(time), day(min(n+1, Dates.daysinmonth(time)))) while true if isweekday(before) && month(before) == current_month return before elseif isweekday(after) && month(after) == current_month return after end if day(after) < Dates.daysinmonth(time) after += Day(1) else break end end end """ return the date for the last weekday (Friday) of the week """ function lastweekday(time::DateTime) current = lastdayofweek(time) while dayofweek(current) > 5 current -= Day(1) end return current end function lasttargetdayofmonth(time::DateTime, daynumber::Int64) last_day = lastdayofmonth(time) current = DateTime(year(last_day), month(last_day), day(Dates.daysinmonth(time))) while dayofweek(current) != daynumber current -= Day(1) end return current end function getoccurance(time::DateTime, daynumber::Int64, occurance::Int64) baseline = firstdayofmonth(time) # increment untill we hit the daytype we want while dayofweek(baseline) !== daynumber baseline += Day(1) end # keep jumping by 7 days untill we the the target occurance while dayofweekofmonth(baseline) !== occurance baseline += Day(7) end return baseline end function matchexpression(input::Nullable{AbstractString}, time::DateTime, converter, maxvalue, adjustedmax=nothing) :: Bool try # base case: return true if if isnothing(input) return true end # Handle sole week or month expressions if haskey(weeknames, input) || haskey(monthnames, input) input = translate(input) end numericvalue = isa(input, Int64) ? input : tryparse(Int64, input) current = converter(time) # need to convert zero based max values to their "real world" equivalent if !isnothing(adjustedmax) && current == 0 current = adjustedmax end # Every Second if input == "*" return true # At X seconds past the minute elseif numericvalue !== nothing # If this field is zero indexed and set to 0 if !isnothing(adjustedmax) && current == adjustedmax return numericvalue == (current - adjustedmax) else return numericvalue == current end elseif contains(input, ",") lowerbound, upperbound = split(input, ",") lowerbound, upperbound = translate(lowerbound), translate(upperbound) return current == customparse(Int64, lowerbound) || current === customparse(Int64, upperbound) elseif contains(input, "-") lowerbound, upperbound = split(input, "-") lowerbound, upperbound = translate(lowerbound), translate(upperbound) if lowerbound == "*" return current <= customparse(Int64, upperbound) elseif upperbound == "*" return current >= customparse(Int64, lowerbound) else return current >= customparse(Int64, lowerbound) && current <= customparse(Int64, upperbound) end elseif contains(input, "/") numerator, denominator = split(input, "/") numerator, denominator = translate(numerator), translate(denominator) # Every second, starting at Y seconds past the minute if denominator == "*" numerator = customparse(Int64, numerator) return current >= numerator elseif numerator == "*" # Every X seconds denominator = customparse(Int64, denominator) return current % denominator == 0 else # Every X seconds, starting at Y seconds past the minute numerator = customparse(Int64, numerator) denominator = customparse(Int64, denominator) return current % denominator == 0 && current >= numerator end end return false catch return false end end function match_special(input::Nullable{AbstractString}, time::DateTime, converter, maxvalue, adjustedmax=nothing) :: Bool # base case: return true if if isnothing(input) return true end # Handle sole week or month expressions if haskey(weeknames, input) || haskey(monthnames, input) input = translate(input) end numericvalue = isa(input, Int64) ? input : tryparse(Int64, input) current = converter(time) # if given a datetime as a max value, means this is a special case expression if maxvalue isa Function maxvalue = converter(maxvalue(time)) end current = converter(time) # need to convert zero based max values to their "real world" equivalent if !isnothing(adjustedmax) && current == 0 current = adjustedmax end # At X seconds past the minute if numericvalue !== nothing # If this field is zero indexed and set to 0 if !isnothing(adjustedmax) && current == adjustedmax return numericvalue == (current - adjustedmax) else return numericvalue == current end elseif input == "?" || input == "*" return true # comamnd: Return the last valid value for this field elseif input == "L" return current == maxvalue # command: the last weekday of the month elseif input == "LW" return current == converter(lastweekdayofmonth(time)) # command negative offset (i.e. L-n), it means "nth-to-last day of the month". elseif contains(input, "L-") return current == maxvalue - customparse(Int64, replace(input, "L-" => "")) # ex.) "11W" = on the weekday nearest day 11th of the month elseif match(r"[0-9]+W", input) !== nothing daynumber = parse(Int64, replace(input, "W" => "")) return current == dayofmonth(nthweekdayofmonth(time, daynumber)) # ex.) "4L" = last Thursday of the month elseif match(r"[0-9]+L", input) !== nothing daynumber = parse(Int64, replace(input, "L" => "")) return dayofmonth(time) == dayofmonth(lasttargetdayofmonth(time, daynumber)) # ex.) "THUL" = last Thursday of the month elseif match(r"([A-Z]+)L", input) !== nothing dayabbreviation = match(r"([A-Z]+)L", input)[1] daynumber = weeknames[dayabbreviation] return dayofmonth(time) == dayofmonth(lasttargetdayofmonth(time, daynumber)) # ex.) 5#2" = the second Friday in the month elseif match(r"([0-9])#([0-9])", input) !== nothing daynumber, position = match(r"([0-9])#([0-9])", input).captures target = getoccurance(time, parse(Int64, daynumber), parse(Int64, position)) return dayofmonth(time) == dayofmonth(target) # ex.) "MON#1" => the first Monday in the month elseif match(r"([A-Z]+)#([0-9])", input) !== nothing daynumber, position = match(r"([A-Z]+)#([0-9])", input).captures target = getoccurance(time, weeknames[daynumber], parse(Int64, position)) return dayofmonth(time) == dayofmonth(target) else return false end end function iscronmatch(expression::String, time::DateTime) :: Bool parsed_expression::Vector{Nullable{AbstractString}} = split(strip(expression), " ") # fill in any missing arguments with nothing, so the array is always fill_length = 6 - length(parsed_expression) if fill_length > 0 parsed_expression = vcat(parsed_expression, fill(nothing, fill_length)) end # extract individual expressions seconds_expression, minute_expression, hour_expression, dayofmonth_expression, month_expression, dayofweek_expression = parsed_expression if !match_month(month_expression, time) return false end if !match_dayofmonth(dayofmonth_expression, time) return false end if !match_dayofweek(dayofweek_expression, time) return false end if !match_hour(hour_expression, time) return false end if !match_minutes(minute_expression, time) return false end if !match_seconds(seconds_expression, time) return false end return true end function match_seconds(seconds_expression, time::DateTime) return matchexpression(seconds_expression, time, second, 59, 60) end function match_minutes(minute_expression, time::DateTime) return matchexpression(minute_expression, time, minute, 59, 60) end function match_hour(hour_expression, time::DateTime) return matchexpression(hour_expression, time, hour, 23, 24) end function match_dayofmonth(dayofmonth_expression, time::DateTime) return match_special(dayofmonth_expression, time, dayofmonth, lastdayofmonth) || matchexpression(dayofmonth_expression, time, dayofmonth, lastdayofmonth) end function match_month(month_expression, time::DateTime) return match_special(month_expression, time, month, 12) || matchexpression(month_expression, time, month, 12) end function match_dayofweek(dayofweek_expression, time::DateTime) return match_special(dayofweek_expression, time, dayofweek, lastdayofweek) || matchexpression(dayofweek_expression, time, dayofweek, lastdayofweek) end """ This function takes a cron expression and a start_time and returns the next datetime object that matches this expression """ function next(cron_expr::String, start_time::DateTime)::DateTime parsed_expression::Vector{Nullable{AbstractString}} = split(strip(cron_expr), " ") # fill in any missing arguments with nothing, so the array is always fill_length = 6 - length(parsed_expression) if fill_length > 0 parsed_expression = vcat(parsed_expression, fill(nothing, fill_length)) end # extract individual expressions seconds_expression, minute_expression, hour_expression, dayofmonth_expression, month_expression, dayofweek_expression = parsed_expression # initialize a candidate time with start_time plus one second candidate_time = start_time + Second(1) # loop until candidate time matches all fields of cron expression while true # check if candidate time matches second field if !match_seconds(seconds_expression, candidate_time) # increment candidate time by one second candidate_time += Second(1) continue end # check if candidate time matches minute field if !match_minutes(minute_expression, candidate_time) # increment candidate time by one minute and reset second # to minimum value candidate_time += Minute(1) - Second(second(candidate_time)) continue end # check if candidate time matches hour field if !match_hour(hour_expression, candidate_time) # increment candidate time by one hour and reset minute # and second to minimum values candidate_time += Hour(1) - Minute(minute(candidate_time)) - Second(second(candidate_time)) continue end # check if candidate time matches day of week field if !match_dayofweek(dayofweek_expression, candidate_time) # increment candidate time by one day and reset hour, # minute and second to minimum values candidate_time += Day(1) - Hour(hour(candidate_time)) - Minute(minute(candidate_time)) - Second(second(candidate_time)) continue end # check if candidate time matches day of month field if !match_dayofmonth(dayofmonth_expression, candidate_time) # increment candidate time by one day and reset hour, # minute and second to minimum values candidate_time += Day(1) - Hour(hour(candidate_time)) - Minute(minute(candidate_time)) - Second(second(candidate_time)) continue end # check if candidate time matches month field if !match_month(month_expression, candidate_time) # increment candidate time by one month and reset day, hour, # minute and second to minimum values candidate_time += Month(1) - Day(day(candidate_time)) + Day(1) - Hour(hour(candidate_time)) - Minute(minute(candidate_time)) - Second(second(candidate_time)) continue end break # exit the loop as all fields match end return remove_milliseconds(candidate_time) # return the next matching tme end # remove the milliseconds from a datetime by rounding down at the seconds function remove_milliseconds(dt::DateTime) return floor(dt, Dates.Second) end function sleep_until(now::DateTime, future::DateTime) # Check if the future datetime is later than the current datetime if future > now # Convert the difference between future and now to milliseconds ms = Dates.value(future - now) # Return the milliseconds to sleep return ms else # Return zero if the future datetime is not later than the current datetime return 0 end end end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
829
# Some deprecated stuff function enabledocs() @warn "This function is deprecated in favour of keyword argument `docs` in serve" end function disabledocs() throw("This function is deprecated in favour of keyword argument `docs` in serve") end function isdocsenabled() @warn "This function is deprecated in favour of keyword argument `docs` in serve" return true # as set in serve end """ configdocs(docspath::String = "/docs", schemapath::String = "/schema") Configure the default docs and schema endpoints """ function configdocs(docspath::String = "/docs", schemapath::String = "/schema") @warn "This function is deprecated in favour of keyword argument `docs_path` and `schema_path` in serve" CONTEXT[].docs.docspath[] = docspath CONTEXT[].docs.schemapath[] = schemapath return end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
5360
module Extractors using JSON3 using Base: @kwdef using HTTP using Dates using StructTypes using ..Util: text, json, formdata, parseparam using ..Reflection: struct_builder, extract_struct_info using ..Types export Extractor, extract, validate, extracttype, isextractor, isreqparam, isbodyparam, Path, Query, Header, Json, JsonFragment, Form, Body abstract type Extractor{T} end """ Given a classname, build a new Extractor class """ macro extractor(class_name) quote struct $(Symbol(class_name)){T} <: Extractor{T} payload::Union{T, Nothing} validate::Union{Function, Nothing} type::Type{T} # Only pass a validator $(Symbol(class_name)){T}(f::Function) where T = new{T}(nothing, f, T) # Pass Type for payload $(Symbol(class_name))(::Type{T}) where T = new{T}(nothing, nothing, T) # Pass Type for payload & validator $(Symbol(class_name))(::Type{T}, f::Function) where T = new{T}(nothing, f, T) # Pass object directly $(Symbol(class_name))(payload::T) where T = new{T}(payload, nothing, T) # Pass object directly & validator $(Symbol(class_name))(payload::T, f::Function) where T = new{T}(payload, f, T) end end |> esc end ## RequestParts Extractors @extractor Path @extractor Query @extractor Header ## RequestContent Extractors @extractor Json @extractor JsonFragment @extractor Form @extractor Body function extracttype(::Type{U}) where {T, U <: Extractor{T}} return T end function isextractor(::Param{T}) where {T} return T <: Extractor end function isreqparam(::Param{U}) where {T, U <: Extractor{T}} return U <: Union{Path{T}, Query{T}, Header{T}} end function isbodyparam(::Param{U}) where {T, U <: Extractor{T}} return U <: Union{Json{T}, JsonFragment{T}, Form{T}, Body{T}} end # Generic validation function - if no validate function is defined for a type, return true validate(type::T) where {T} = true """ This function will try to validate an instance of a type using both global and local validators. If both validators pass, the instance is returned. If either fails, an ArgumentError is thrown. """ function try_validate(param::Param{U}, instance::T) :: T where {T, U <: Extractor{T}} # Case 1: Use global validate function - returns true if one isn't defined for this type if !validate(instance) impl = Base.which(validate, (T,)) throw(ArgumentError("Validation failed for $(param.name): $T \n|> $instance \n|> $impl")) end # Case 2: Use custom validate function from an Extractor (if defined) if param.hasdefault && param.default isa U && !isnothing(param.default.validate) if !param.default.validate(instance) impl = Base.which(param.default.validate, (T,)) throw(ArgumentError("Validation failed for $(param.name): $T \n|> $instance \n|> $impl")) end end return instance end """ Extracts a JSON object from a request and converts it into a custom struct """ function extract(param::Param{Json{T}}, request::LazyRequest) :: Json{T} where {T} instance = JSON3.read(textbody(request), T) valid_instance = try_validate(param, instance) return Json(valid_instance) end """ Extracts a part of a json object from the body of a request and converts it into a custom struct """ function extract(param::Param{JsonFragment{T}}, request::LazyRequest) :: JsonFragment{T} where {T} body = Types.jsonbody(request)[param.name] instance = struct_builder(T, body) valid_instance = try_validate(param, instance) return JsonFragment(valid_instance) end """ Extracts the body from a request and convert it into a custom type """ function extract(param::Param{Body{T}}, request::LazyRequest) :: Body{T} where {T} instance = parseparam(T, textbody(request); escape=false) valid_instance = try_validate(param, instance) return Body(valid_instance) end """ Extracts a Form from a request and converts it into a custom struct """ function extract(param::Param{Form{T}}, request::LazyRequest) :: Form{T} where {T} form = Types.formbody(request) instance = struct_builder(T, form) valid_instance = try_validate(param, instance) return Form(valid_instance) end """ Extracts path parameters from a request and convert it into a custom struct """ function extract(param::Param{Path{T}}, request::LazyRequest) :: Path{T} where {T} params = Types.pathparams(request) instance = struct_builder(T, params) valid_instance = try_validate(param, instance) return Path(valid_instance) end """ Extracts query parameters from a request and convert it into a custom struct """ function extract(param::Param{Query{T}}, request::LazyRequest) :: Query{T} where {T} params = Types.queryvars(request) instance = struct_builder(T, params) valid_instance = try_validate(param, instance) return Query(valid_instance) end """ Extracts Headers from a request and convert it into a custom struct """ function extract(param::Param{Header{T}}, request::LazyRequest) :: Header{T} where {T} headers = Types.headers(request) instance = struct_builder(T, headers) valid_instance = try_validate(param, instance) return Header(valid_instance) end end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
3813
module Handlers using HTTP using ..Types: Nullable using ..Core: SPECIAL_METHODS, TYPE_ALIASES export select_handler, first_arg_type # Union type of supported Handlers HandlerArgType = Union{HTTP.Messages.Request, HTTP.WebSockets.WebSocket, HTTP.Streams.Stream} """ Determine how to call each handler based on the arguments it takes. """ function get_invoker_stategy(has_req_kwarg::Bool, has_path_params::Bool, no_args::Bool) if has_req_kwarg if no_args return function (func::Function, _::HandlerArgType, req::HTTP.Messages.Request, _::Nullable{Vector}) func(; request=req) end elseif has_path_params return function (func::Function, arg::HandlerArgType, req::HTTP.Messages.Request, pathParams::Nullable{Vector}) func(arg, pathParams...; request=req) end else return function (func::Function, arg::HandlerArgType, req::HTTP.Messages.Request, _::Nullable{Vector}) func(arg; request=req) end end else if no_args return function (func::Function, _::HandlerArgType, _::HTTP.Messages.Request, _::Nullable{Vector}) func() end elseif has_path_params return function (func::Function, arg::HandlerArgType, _::HTTP.Messages.Request, pathParams::Nullable{Vector}) func(arg, pathParams...) end else return function (func::Function, arg::HandlerArgType, _::HTTP.Messages.Request, _::Nullable{Vector}) func(arg) end end end end """ select_handler(::Type{T}) This base case, returns a handler for `HTTP.Request` objects. """ function select_handler(::Type{T}, has_req_kwarg::Bool, has_path_params::Bool; no_args=false) where {T} invoker = get_invoker_stategy(has_req_kwarg, has_path_params, no_args) function (req::HTTP.Request, func::Function; pathParams::Nullable{Vector}=nothing) invoker(func, req, req, pathParams) end end """ select_handler(::Type{HTTP.Streams.Stream}) Returns a handler for `HTTP.Streams.Stream` types """ function select_handler(::Type{HTTP.Streams.Stream}, has_req_kwarg::Bool, has_path_params::Bool; no_args=false) invoker = get_invoker_stategy(has_req_kwarg, has_path_params, no_args) function (req::HTTP.Request, func::Function; pathParams::Nullable{Vector}=nothing) invoker(func, req.context[:stream], req, pathParams) end end """ select_handler(::Type{HTTP.WebSockets.WebSocket}) Returns a handler for `HTTP.WebSockets.WebSocket`types """ function select_handler(::Type{HTTP.WebSockets.WebSocket}, has_req_kwarg::Bool, has_path_params::Bool; no_args=false) invoker = get_invoker_stategy(has_req_kwarg, has_path_params, no_args) function (req::HTTP.Request, func::Function; pathParams::Nullable{Vector}=nothing) HTTP.WebSockets.isupgrade(req) && HTTP.WebSockets.upgrade(ws -> invoker(func, ws, req, pathParams), req.context[:stream]) end end """ first_arg_type(method::Method, httpmethod::String) Determine the type of the first argument of a given method. If the `httpmethod` is in `Constants.SPECIAL_METHODS`, the function will return the corresponding type from `TYPE_ALIASES` if it exists, or `Type{HTTP.Request}` as a default. Otherwise, it will return the type of the second field of the method's signature. """ function first_arg_type(method::Method, httpmethod::String) :: Type if httpmethod in SPECIAL_METHODS return get(TYPE_ALIASES, httpmethod, HTTP.Request) else # either grab the first argument type or default to HTTP.Request field_types = fieldtypes(method.sig) return length(field_types) < 2 ? HTTP.Request : field_types[2] end end end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
2447
module Instances using RelocatableFolders export instance function escape_path_if_windows(path::String) return Sys.iswindows() ? replace(path, "\\" => "\\\\") : path end function fullpath(path::AbstractString) :: String absolute_path = @path abspath(joinpath(@__DIR__, path)) return absolute_path |> String |> escape_path_if_windows end function extract_filename(include_str::String, include_regex::Regex) # Regular expression to match the pattern include("filename") match_result = match(include_regex, include_str) if match_result !== nothing return match_result.captures[1] # Return the captured filename end end function preprocess_includes(content::String, include_regex::Regex = r"include\(\"(.*)\"\)") # Function to replace include calls with absolute paths function replace_include(match) # Extract the path from the match path = extract_filename(String(match), include_regex) absolute_path = fullpath(path) # Return the updated include call return "include(\"$absolute_path\")" end # Replace all include calls in the content return replace(content, include_regex => replace_include) end """ load(path::String) Load a module from a file specified by `path`. The file should define a module. The module is loaded into the current scope under the name `custom_module`. """ function load(path::String) absolute_path = fullpath(path) !isfile(absolute_path) && throw("not a valid file") # Read the file content content = read(absolute_path, String) # Preprocess includes to adjust paths processed_content = preprocess_includes(content) quote # Execute the preprocessed content custom_module = include_string(@__MODULE__, $(processed_content)) using .custom_module end end """ instance() Create a new self-containedinstance of the Kitten module. This done by creating a new unique module at runtime and loading the Kitten module into it. This results in a unique instance of the Kernel module that can be used independently. """ function instance() # Create the module definition with the macro call for the function definition mod_def = Expr(:module, false, gensym(), Expr(:block, :(using Base), load("Kitten.jl") ) ) # Evaluate the module definition to actually create it return eval(mod_def) end end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
10413
# This is where methods are coupled to a global state """ resetstate() Reset all the internal state variables """ function resetstate() # prevent context reset when created at compile-time if (@__MODULE__) == Kitten CONTEXT[] = Kitten.Core.Context() end end function serve(; kwargs...) async = Base.get(kwargs, :async, false) try # return the resulting HTTP.Server object return Kitten.Core.serve(CONTEXT[]; kwargs...) finally # close server on exit if we aren't running asynchronously if !async terminate() # only reset state on exit if we aren't running asynchronously & are running it interactively isinteractive() && resetstate() end end end """ serveparallel(; middleware::Vector=[], handler=stream_handler, host="127.0.0.1", port=8080, serialize=true, async=false, catch_errors=true, docs=true, metrics=true, kwargs...) """ function serveparallel(; kwargs...) serve(; parallel=true, kwargs...) end ### Routing Macros ### """ @get(path::String, func::Function) Used to register a function to a specific endpoint to handle GET requests """ macro get(path, func) path, func = adjustparams(path, func) :(@route [GET] $(esc(path)) $(esc(func))) end """ @post(path::String, func::Function) Used to register a function to a specific endpoint to handle POST requests """ macro post(path, func) path, func = adjustparams(path, func) :(@route [POST] $(esc(path)) $(esc(func))) end """ @put(path::String, func::Function) Used to register a function to a specific endpoint to handle PUT requests """ macro put(path, func) path, func = adjustparams(path, func) :(@route [PUT] $(esc(path)) $(esc(func))) end """ @patch(path::String, func::Function) Used to register a function to a specific endpoint to handle PATCH requests """ macro patch(path, func) path, func = adjustparams(path, func) :(@route [PATCH] $(esc(path)) $(esc(func))) end """ @delete(path::String, func::Function) Used to register a function to a specific endpoint to handle DELETE requests """ macro delete(path, func) path, func = adjustparams(path, func) :(@route [DELETE] $(esc(path)) $(esc(func))) end """ @stream(path::String, func::Function) Used to register a function to a specific endpoint to handle Streaming requests """ macro stream(path, func) path, func = adjustparams(path, func) :(@route [STREAM] $(esc(path)) $(esc(func))) end """ @websocket(path::String, func::Function) Used to register a function to a specific endpoint to handle WebSocket connections """ macro websocket(path, func) path, func = adjustparams(path, func) :(@route [WEBSOCKET] $(esc(path)) $(esc(func))) end """ @route(methods::Array{String}, path::String, func::Function) Used to register a function to a specific endpoint to handle mulitiple request types """ macro route(methods, path, func) :(route($(esc(methods)), $(esc(path)), $(esc(func)))) end """ adjustparams(path, func) Adjust the order of `path` and `func` based on their types. This is used to support the `do ... end` syntax for the routing macros. """ function adjustparams(path, func) # case 1: do ... end block syntax was used if isa(path, Expr) && path.head == :-> func, path # case 2: regular syntax was used else path, func end end ### Core Routing Functions ### function route(methods::Vector{String}, path::Union{String,Function}, func::Function) for method in methods Kitten.Core.register(CONTEXT[], method, path, func) end end # This variation supports the do..block syntax route(func::Function, methods::Vector{String}, path::Union{String,Function}) = route(methods, path, func) ### Special Routing Functions Support for do..end Syntax ### stream(func::Function, path::String) = route([STREAM], path, func) stream(func::Function, path::Function) = route([STREAM], path, func) websocket(func::Function, path::String) = route([WEBSOCKET], path, func) websocket(func::Function, path::Function) = route([WEBSOCKET], path, func) ### Core Routing Functions Support for do..end Syntax ### get(func::Function, path::String) = route([GET], path, func) get(func::Function, path::Function) = route([GET], path, func) post(func::Function, path::String) = route([POST], path, func) post(func::Function, path::Function) = route([POST], path, func) put(func::Function, path::String) = route([PUT], path, func) put(func::Function, path::Function) = route([PUT], path, func) patch(func::Function, path::String) = route([PATCH], path, func) patch(func::Function, path::Function) = route([PATCH], path, func) delete(func::Function, path::String) = route([DELETE], path, func) delete(func::Function, path::Function) = route([DELETE], path, func) """ @staticfiles(folder::String, mountdir::String, headers::Vector{Pair{String,String}}=[]) Mount all files inside the /static folder (or user defined mount point) """ macro staticfiles(folder, mountdir="static", headers=[]) printstyled("@staticfiles macro is deprecated, please use the staticfiles() function instead\n", color=:red, bold=true) quote staticfiles($(esc(folder)), $(esc(mountdir)); headers=$(esc(headers))) end end """ @dynamicfiles(folder::String, mountdir::String, headers::Vector{Pair{String,String}}=[]) Mount all files inside the /static folder (or user defined mount point), but files are re-read on each request """ macro dynamicfiles(folder, mountdir="static", headers=[]) printstyled("@dynamicfiles macro is deprecated, please use the dynamicfiles() function instead\n", color=:red, bold=true) quote dynamicfiles($(esc(folder)), $(esc(mountdir)); headers=$(esc(headers))) end end staticfiles( folder::String, mountdir::String="static"; headers::Vector=[], loadfile::Nullable{Function}=nothing ) = Kitten.Core.staticfiles(CONTEXT[].service.router, folder, mountdir; headers, loadfile) dynamicfiles( folder::String, mountdir::String="static"; headers::Vector=[], loadfile::Nullable{Function}=nothing ) = Kitten.Core.dynamicfiles(CONTEXT[].service.router, folder, mountdir; headers, loadfile) internalrequest(req::Kitten.Request; middleware::Vector=[], metrics::Bool=false, serialize::Bool=true, catch_errors=true) = Kitten.Core.internalrequest(CONTEXT[], req; middleware, metrics, serialize, catch_errors) function router(prefix::String=""; tags::Vector{String}=Vector{String}(), middleware::Nullable{Vector}=nothing, interval::Nullable{Real}=nothing, cron::Nullable{String}=nothing) return Kitten.Core.router(CONTEXT[], prefix; tags, middleware, interval, cron) end mergeschema(route::String, customschema::Dict) = Kitten.Core.mergeschema(CONTEXT[].docs.schema, route, customschema) mergeschema(customschema::Dict) = Kitten.Core.mergeschema(CONTEXT[].docs.schema, customschema) """ getschema() Return the current internal schema for this app """ function getschema() return CONTEXT[].docs.schema end """ setschema(customschema::Dict) Overwrites the entire internal schema """ function setschema(customschema::Dict) empty!(CONTEXT[].docs.schema) merge!(CONTEXT[].docs.schema, customschema) return end """ @repeat(interval::Real, func::Function) Registers a repeat task. This will extract either the function name or the random Id julia assigns to each lambda function. """ macro repeat(interval, func) quote Kitten.Core.task($(CONTEXT[].tasks.registered_tasks), $(esc(interval)), string($(esc(func))), $(esc(func))) end end """ @repeat(interval::Real, name::String, func::Function) This variation provides way manually "name" a registered repeat task. This information is used by the server on startup to log out all cron jobs. """ macro repeat(interval, name, func) quote Kitten.Core.task($(CONTEXT[].tasks.registered_tasks), $(esc(interval)), string($(esc(name))), $(esc(func))) end end """ @cron(expression::String, func::Function) Registers a function with a cron expression. This will extract either the function name or the random Id julia assigns to each lambda function. """ macro cron(expression, func) quote Kitten.Core.cron($(CONTEXT[].cron.registered_jobs), $(esc(expression)), string($(esc(func))), $(esc(func))) end end """ @cron(expression::String, name::String, func::Function) This variation provides way manually "name" a registered function. This information is used by the server on startup to log out all cron jobs. """ macro cron(expression, name, func) quote Kitten.Core.cron($(CONTEXT[].cron.registered_jobs), $(esc(expression)), string($(esc(name))), $(esc(func))) end end ## Cron Job Functions ## function startcronjobs(ctx::Context) Kitten.Core.registercronjobs(ctx) Kitten.Core.startcronjobs(ctx.cron) end startcronjobs() = startcronjobs(CONTEXT[]) stopcronjobs(ctx::Context) = Kitten.Core.stopcronjobs(ctx.cron) stopcronjobs() = stopcronjobs(CONTEXT[]) clearcronjobs(ctx::Context) = Kitten.Core.clearcronjobs(ctx.cron) clearcronjobs() = clearcronjobs(CONTEXT[]) ### Repeat Task Functions ### function starttasks(context::Context) Kitten.Core.registertasks(context) Kitten.Core.starttasks(context.tasks) end starttasks() = starttasks(CONTEXT[]) stoptasks(context::Context) = Kitten.Core.stoptasks(context.tasks) stoptasks() = stoptasks(CONTEXT[]) cleartasks(context::Context) = Kitten.Core.cleartasks(context.tasks) cleartasks() = cleartasks(CONTEXT[]) ### Terminate Function ### terminate(context::Context) = Kitten.Core.terminate(context) terminate() = terminate(CONTEXT[]) ### Setup Docs Strings ### for method in [:serve, :terminate, :staticfiles, :dynamicfiles, :internalrequest] eval(quote @doc (@doc(Kitten.Core.$method)) $method end) end # Docs Methods for method in [:router, :mergeschema] eval(quote @doc (@doc(Kitten.Core.AutoDoc.$method)) $method end) end # Repeat Task methods for method in [:starttasks, :stoptasks, :cleartasks] eval(quote @doc (@doc(Kitten.Core.RepeatTasks.$method)) $method end) end # Cron methods for method in [:startcronjobs, :stopcronjobs, :clearcronjobs] eval(quote @doc (@doc(Kitten.Core.Cron.$method)) $method end) end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
9654
module Metrics using HTTP using JSON3 using Dates using DataStructures using Statistics using RelocatableFolders using ..Util using ..Types export MetricsMiddleware, get_history, push_history, server_metrics, all_endpoint_metrics, capture_metrics, bin_and_count_transactions, bin_transactions, requests_per_unit, avg_latency_per_unit, timeseries, series_format, error_distribution, prepare_timeseries_data struct TimeseriesRecord timestamp::DateTime value::Number end function push_history(history::History, transaction::HTTPTransaction) pushfirst!(history, transaction) end function get_history(history::History) :: Vector{HTTPTransaction} return collect(history) end # Helper function to calculate percentile function percentile(values, p) index = ceil(Int, p / 100 * length(values)) return sort(values)[index] end # Function to group HTTPTransaction objects by URI prefix with a maximum depth limit function group_transactions(transactions::Vector{HTTPTransaction}, max_depth::Int) # Create a dictionary to store the grouped transactions grouped_transactions = Dict{String, Vector{HTTPTransaction}}() for transaction in transactions # Split the URI by '/' to get the segments uri_parts = split(transaction.uri, '/') # Determine the depth and create the prefix depth = min(length(uri_parts), max_depth + 1) prefix = join(uri_parts[1:depth], '/') # Check if the prefix exists in the dictionary, if not, create an empty vector if !haskey(grouped_transactions, prefix) grouped_transactions[prefix] = [] end # Append the transaction to the corresponding prefix push!(grouped_transactions[prefix], transaction) end return grouped_transactions end ### Helper function to calculate metrics for a set of transactions function get_transaction_metrics(transactions::Vector{HTTPTransaction}) if isempty(transactions) return Dict( "total_requests" => 0, "avg_latency" => 0, "min_latency" => 0, "max_latency" => 0, "percentile_latency_95th" => 0, "error_rate" => 0 ) end total_requests = length(transactions) latencies = [t.duration for t in transactions if t.duration != 0.0] successes = [t.success for t in transactions] has_records = !isempty(latencies) has_successes = !isempty(successes) avg_latency = has_records ? mean(latencies) : 0 min_latency = has_records ? minimum(latencies) : 0 max_latency = has_records ? maximum(latencies) : 0 percentile_95_latency = has_records ? percentile(latencies, 95) : 0 total_errors = has_successes ? count(!, successes) : 0 error_rate = total_requests > 0 ? total_errors / total_requests : 0 return Dict( "total_requests" => total_requests, "total_errors" => total_errors, "avg_latency" => avg_latency, "min_latency" => min_latency, "max_latency" => max_latency, "percentile_latency_95th" => percentile_95_latency, "error_rate" => error_rate ) end ### Helper function to group transactions by endpoint function recent_transactions(history::Vector{HTTPTransaction}, ::Nothing) :: Vector{HTTPTransaction} return history end function recent_transactions(history::Vector{HTTPTransaction}, lower_bound::Dates.Period) :: Vector{HTTPTransaction} current_time = now(UTC) adjusted = lower_bound + Second(1) return filter(t -> current_time - t.timestamp <= adjusted, history) end # Needs coverage function recent_transactions(history::Vector{HTTPTransaction}, lower_bound::Dates.DateTime) :: Vector{HTTPTransaction} adjusted = lower_bound + Second(1) return filter(t -> t.timestamp >= adjusted, history) end """ Group transactions by URI depth with a maximum depth limit using the function """ function all_endpoint_metrics(history::Vector{HTTPTransaction}, lower_bound=Minute(15); max_depth=4) transactions = recent_transactions(history, lower_bound) groups = group_transactions(transactions, max_depth) return Dict(k => get_transaction_metrics(v) for (k,v) in groups) end function server_metrics(history::Vector{HTTPTransaction}, lower_bound=Minute(15)) transactions = recent_transactions(history, lower_bound) get_transaction_metrics(transactions) end # Needs coverage function endpoint_metrics(history::Vector{HTTPTransaction}, endpoint_uri::String) endpoint_transactions = filter(t -> t.uri == endpoint_uri, history) return get_transaction_metrics(endpoint_transactions) end function error_distribution(history::Vector{HTTPTransaction}, lower_bound=Minute(15)) metrics = all_endpoint_metrics(history, lower_bound) failed_counts = Dict{String, Int}() for (group_prefix, transaction_metrics) in metrics failures = transaction_metrics["total_errors"] if failures > 0 failed_counts[group_prefix] = get(failed_counts, group_prefix, 0) + failures end end return failed_counts end # """ # Helper function used to convert internal data so that it can be viewd by a graph more easily # """ # function prepare_timeseries_data(unit::Dates.TimePeriod=Second(1)) # function(binned_records::Dict) # binned_records |> timeseries |> fill_missing_data(unit, fill_to_current=true, sort=false) |> series_format # end # end function prepare_timeseries_data() function(binned_records::Dict) binned_records |> timeseries |> series_format end end # function fill_missing_data(unit::Dates.TimePeriod=Second(1); fill_to_current::Bool=false, sort::Bool=true) # return function(records::Vector{TimeseriesRecord}) # return fill_missing_data(records, unit, fill_to_current=fill_to_current, sort=sort) # end # end # function fill_missing_data(records::Vector{TimeseriesRecord}, unit::Dates.TimePeriod=Second(1); fill_to_current::Bool=false, sort::Bool=true) # # Ensure the input is sorted by timestamp # if sort # sort!(records, by = x -> x.timestamp) # end # filled_records = Vector{TimeseriesRecord}() # last_record_time = nothing # Initialize variable to store the time of the last record # for i in 1:length(records) # # Add the current record to the filled_records # push!(filled_records, records[i]) # last_record_time = records[i].timestamp # Update the time of the last record # # If this is not the last record, check the gap to the next record # if i < length(records) # next_time = records[i+1].timestamp # while last_record_time + unit < next_time # last_record_time += unit # push!(filled_records, TimeseriesRecord(last_record_time, 0)) # end # end # end # # If fill_to_current is true, fill in the gap between the last record and the current time # if fill_to_current && !isnothing(last_record_time) # current_time = now(UTC) # while last_record_time + unit < current_time # last_record_time += unit # push!(filled_records, TimeseriesRecord(last_record_time, 0)) # end # end # return filled_records # end """ Convert a dictionary of timeseries data into an array of sorted records """ function timeseries(data) :: Vector{TimeseriesRecord} # Convert the dictionary into an array of [timestamp, value] pairs timestamp_value_pairs = [TimeseriesRecord(k, v) for (k, v) in data] # Sort the array based on the timestamps (the first element in each pair) return sort(timestamp_value_pairs, by=x->x.timestamp) end """ Convert a TimeseriesRecord into a matrix format that works better with apex charts """ function series_format(data::Vector{TimeseriesRecord}) :: Vector{Vector{Union{DateTime,Number}}} return [[item.timestamp, item.value] for item in data] end """ Helper function to group transactions within a given timeframe """ function bin_transactions(history::Vector{HTTPTransaction}, lower_bound=Minute(15), unit=Minute, strategy=nothing) :: Dict{DateTime,Vector{HTTPTransaction}} transactions = recent_transactions(history, lower_bound) binned = Dict{DateTime, Vector{HTTPTransaction}}() for t in transactions # create bin's based on the given unit bin_value = floor(t.timestamp, unit) if !haskey(binned, bin_value) binned[bin_value] = [t] else push!(binned[bin_value], t) end if !isnothing(strategy) strategy(bin_value, t) end end return binned end function requests_per_unit(history::Vector{HTTPTransaction}, unit, lower_bound=Minute(15)) bin_counts = Dict{DateTime, Int}() function count_transactions(bin, transaction) bin_counts[bin] = get(bin_counts, bin, 0) + 1 end bin_transactions(history, lower_bound, unit, count_transactions) return bin_counts end """ Return the average latency per minute for the server """ function avg_latency_per_unit(history::Vector{HTTPTransaction}, unit, lower_bound=Minute(15)) bin_counts = Dict{DateTime, Vector{Number}}() function strategy(bin, transaction) if haskey(bin_counts, bin) push!(bin_counts[bin], transaction.duration) else bin_counts[bin] = [transaction.duration] end end bin_transactions(history, lower_bound, unit, strategy) averages = Dict{DateTime, Number}() for (k,v) in bin_counts averages[k] = mean(v) end return averages end end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
2379
module Middleware using HTTP export compose, genkey """ This function is used to generate dictionary keys which lookup middleware for routes """ function genkey(httpmethod::String, path::String)::String return "$httpmethod|$path" end """ This function is used to build up the middleware chain for all our endpoints """ function buildmiddleware(key::String, handler::Function, globalmiddleware::Vector, custommiddleware::Dict) :: Function # lookup the middleware for this path routermiddleware, routemiddleware = get(custommiddleware, key, (nothing, nothing)) # sanitize outputs (either value can be nothing) routermiddleware = isnothing(routermiddleware) ? [] : routermiddleware routemiddleware = isnothing(routemiddleware) ? [] : routemiddleware # initialize our middleware layers layers::Vector{Function} = [handler] # append the middleware in reverse order (so when we reduce over it, it's in the correct order) append!(layers, routemiddleware) append!(layers, routermiddleware) append!(layers, globalmiddleware) # combine all the middleware functions together return reduce(|>, layers) end """ This function dynamically determines which middleware functions to apply to a request at runtime. If router or route specific middleware is defined, then it's used instead of the globally defined middleware. """ function compose(router::HTTP.Router, globalmiddleware::Vector, custommiddleware::Dict, middleware_cache::Dict) return function (handler) return function (req::HTTP.Request) innerhandler, path, _ = HTTP.Handlers.gethandler(router, req) # Check if the current request matches one of our predefined routes if innerhandler !== nothing # Check if we already have a cached middleware function for this specific route key = genkey(req.method, path) func = get(middleware_cache, key, nothing) if !isnothing(func) return func(req) end # Combine all the middleware functions together strategy = buildmiddleware(key, handler, globalmiddleware, custommiddleware) middleware_cache[key] = strategy return strategy(req) end return handler(req) end end end end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
14380
module Reflection using StructTypes using Base: @kwdef using ..Types export splitdef, struct_builder, extract_struct_info """ Helper function to access the underlying value of any global references """ function getargvalue(arg) return isa(arg, GlobalRef) ? getfield(arg.mod, arg.name) : arg end """ Return all parameter name & types and keyword argument names from a function """ function getsignames(f::Function; start=2) return getsignames(methods(f), start=start) end """ Return parameter name & types and keyword argument names from a list of methods """ function getsignames(func_methods::Base.MethodList; start=2) arg_names = Vector{Symbol}() arg_types = Vector{Type}() kwarg_names = Vector{Symbol}() # track position & types of parameters in the function signature positions = Dict{Symbol, Int}() for m in func_methods argnames = Base.method_argnames(m)[start:end] argtypes = fieldtypes(m.sig)[start:end] for (i, (argname, type)) in enumerate(zip(argnames, argtypes)) if argname βˆ‰ arg_names push!(arg_names, argname) push!(arg_types, type) positions[argname] = i end end for kwarg in Base.kwarg_decl(m) if kwarg βˆ‰ kwarg_names && kwarg != :... push!(kwarg_names, kwarg) end end end return arg_names, arg_types, kwarg_names end function walkargs(predicate::Function, expr) if isdefined(expr, :args) for arg in expr.args if predicate(arg) return true end walkargs(predicate, arg) end end return false end function reconstruct(info::Core.CodeInfo, func_name::Symbol) # Track which index the function signature can be found on sig_index = nothing # create a dictionary of statements statements = Dict{Core.SSAValue, Any}() assignments = Dict{Core.SlotNumber, Any}() # create a unique flag for each call to mark missing values NO_VALUES = gensym() function rebuild!(values::AbstractVector) return rebuild!.(values) end function rebuild!(expr::Expr) expr.args = rebuild!.(expr.args) return expr end function rebuild!(ssa::Core.SSAValue) return rebuild!(statements[ssa]) end function rebuild!(slot::Core.SlotNumber) value = get(assignments, slot, NO_VALUES) return value == NO_VALUES ? slot : rebuild!(value) end function rebuild!(value::Any) return value end for (index, expr) in enumerate(info.code) ssa_index = Core.SSAValue(index) statements[ssa_index] = expr if expr isa Expr if expr.head == :(=) (lhs, rhs) = expr.args try assignments[lhs] = eval(rebuild!(rhs)) catch end # identify the function signature elseif isdefined(expr, :args) && expr.head == :call for arg in expr.args if arg isa Core.SlotNumber && arg.id == 1 sig_index = ssa_index end end end end end # Recursively build an expression of the actual type of each argument in the function signature evaled_sig = rebuild!(statements[sig_index]) default_values = [] for arg in evaled_sig.args contains_func_name = walkargs(arg) do x # Super generic check to see if the function name is in the expression return contains("$x", "$func_name") end if contains_func_name || arg == NO_VALUES || arg isa GlobalRef && contains("$(arg.name)", "$func_name") continue end if arg isa Expr push!(default_values, eval(arg)) else push!(default_values, arg) end end return default_values end """ Returns true if the CodeInfo object has a function signature Most funtion signatures follow this general pattern - The second to last expression is used as the function signature - The last argument is a Return node Below are a couple different examples of this in pattern in action: # Standard function signature CodeInfo( 1 ─ %1 = (#self#)(req, a, path, qparams, 23) └── return %1 ) # Extractor example (as a default value) CodeInfo( 1 ─ #22 = %new(Main.RunTests.ExtractorTests.:(var"#22#37")) β”‚ %2 = #22 β”‚ %3 = Main.RunTests.ExtractorTests.Header(Main.RunTests.ExtractorTests.Sample, %2) β”‚ %4 = (#self#)(req, %3) └── return %4 ) # This kind of function signature happens when a keyword argument is defined without at default value CodeInfo( 1 ─ %1 = "default" β”‚ c = %1 β”‚ %3 = true β”‚ d = %3 β”‚ %5 = Core.UndefKeywordError(:request) β”‚ %6 = Core.throw(%5) β”‚ request = %6 β”‚ %8 = Core.getfield(#self#, Symbol("#8#9")) β”‚ %9 = c β”‚ %10 = d β”‚ %11 = request β”‚ %12 = (%8)(%9, %10, %11, #self#, a, b) └── return %12 ) """ function has_sig_expr(c::Core.CodeInfo) :: Bool statements_length = length(c.code) # prevent index out of bounds if statements_length < 2 return false end # check for our pattern of a function signature followed by a return statement last_expr = c.code[statements_length] second_to_last_expr = c.code[statements_length - 1] if last_expr isa Core.ReturnNode && second_to_last_expr isa Expr && second_to_last_expr.head == :call # recursivley search expression to see if we have a SlotNumber(1) in the args return walkargs(second_to_last_expr) do arg return isa(arg, Core.SlotNumber) && arg.id == 1 end end return false end """ Given a list of CodeInfo objects, extract any default values assigned to parameters & keyword arguments """ function extract_defaults(info::Vector{Core.CodeInfo}, func_name::Symbol, param_names::Vector{Symbol}, kwarg_names::Vector{Symbol}) # These store the mapping between parameter names and their default values param_defaults = Dict() kwarg_defaults = Dict() # Given the params, we can take an educated guess and map the slot number to the parameter name slot_mapping = Dict(i + 1 => p for (i, p) in enumerate(vcat(param_names, kwarg_names))) # skip parsing if no parameters or keyword arguments are found if isempty(param_names) && isempty(kwarg_names) return param_defaults, kwarg_defaults end for c in info # skip code info objects that don't have a function signature if !has_sig_expr(c) continue end # rebuild the function signature with the default values included sig_args = reconstruct(c, func_name) sig_length = length(sig_args) self_index = findfirst([isa(x, Core.SlotNumber) && x.id == 1 for x in sig_args]) for (index, arg) in enumerate(sig_args) # for keyword arguments if index < self_index # derive the current slot name slot_number = sig_length - abs(self_index - index) + 1 slot_name = slot_mapping[slot_number] # don't store slot numbers when no default is given value = getargvalue(arg) if !isa(value, Core.SlotNumber) kwarg_defaults[slot_name] = value end # for regular arguments elseif index > self_index # derive the current slot name slot_number = abs(self_index - index) + 1 slot_name = slot_mapping[slot_number] # don't store slot numbers when no default is given value = getargvalue(arg) if !isa(value, Core.SlotNumber) param_defaults[slot_name] = value end end end end return param_defaults, kwarg_defaults end # Return the more specific type function select_type(t1::Type, t2::Type) # case 1: only t1 is any if t1 == Any && t2 != Any return t2 # case 2: only t2 is any elseif t2 == Any && t1 != Any return t1 # case 3: Niether / Both types are Any, chose the more specific type else if t1 <: t2 return t1 elseif t2 <: t1 return t2 else # if the types are the same, return the first type return t1 end end end # Merge two parameter objects, defaultint to the original params value function mergeparams(p1::Param, p2::Param) :: Param return Param( name = p1.name, type = select_type(p1.type, p2.type), default = coalesce(p1.default, p2.default), hasdefault = p1.hasdefault || p2.hasdefault ) end """ Used to extract the function signature from regular Julia functions. """ function splitdef(f::Function; start=1) method_defs = methods(f) func_name = first(method_defs).name return splitdef(Base.code_lowered(f), methods(f), func_name, start=start) end """ Used to extract the function signature from regular Julia Structs. This function merges the signature map at the end, because it's common for structs to have multiple constructors with the same parameter names as both keyword args and regular args. """ function splitdef(t::DataType; start=1) results = splitdef(Base.code_lowered(t), methods(t), nameof(t), start=start) sig_map = Dict{Symbol,Param}() for param in results.sig # merge parameters with the same name if haskey(sig_map, param.name) sig_map[param.name] = mergeparams(sig_map[param.name], param) # add unique parameter to the map else sig_map[param.name] = param end end merge!(results.sig_map, sig_map) return results end function splitdef(info::Vector{Core.CodeInfo}, method_defs::Base.MethodList, func_name::Symbol; start=1) # Extract parameter names and types param_names, param_types, kwarg_names = getsignames(method_defs) # Extract default values param_defaults, kwarg_defaults = extract_defaults(info, func_name, param_names, kwarg_names) # Create a list of Param objects from parameters params = Vector{Param}() for (name, type) in zip(param_names, param_types) if haskey(param_defaults, name) # inferr the type of the parameter based on the default value param_default = param_defaults[name] inferred_type = type == Any ? typeof(param_default) : type push!(params, Param(name=name, type=inferred_type, default=param_default, hasdefault=true)) else push!(params, Param(name=name, type=type)) end end # Create a list of Param objects from keyword arguments keyword_args = Vector{Param}() for name in kwarg_names # Don't infer the type of the keyword argument, since julia doesn't support types on kwargs if haskey(kwarg_defaults, name) push!(keyword_args, Param(name=name, type=Any, default=kwarg_defaults[name], hasdefault=true)) else push!(keyword_args, Param(name=name, type=Any)) end end sig_params = vcat(params, keyword_args)[start:end] return ( name = func_name, args = params[start:end], kwargs = keyword_args[start:end], sig = sig_params, sig_map = Dict{Symbol,Param}(param.name => param for param in sig_params) ) end """ has_kwdef_constructor(T::Type) :: Bool Returns true if type `T` has a constructor that takes only keyword arguments and matches the order and field names of `T`. Otherwise, it returns `false`. Practically, this check is used to check if `@kwdef` was used to define the struct. """ function has_kwdef_constructor(T::Type) :: Bool fieldnames = Base.fieldnames(T) for constructor in methods(T) if length(Base.method_argnames(constructor)) == 1 && Tuple(Base.kwarg_decl(constructor)) == fieldnames return true end end return false end # Function to extract field names, types, and default values function extract_struct_info(T::Type) field_names = fieldnames(T) type_map = Dict(name => fieldtype(T, name) for name in field_names) return (names=field_names, map=type_map) end function parsetype(target_type::Type{T}, value::Any) :: T where {T} if value isa T return value elseif value isa AbstractString return parse(target_type, value) else return convert(target_type, value) end end """ struct_builder(::Type{T}, parameters::Dict{String,String}) where {T} Constructs an object of type `T` using the parameters in the dictionary `parameters`. """ function struct_builder(::Type{T}, params::AbstractDict) :: T where {T} has_kwdef = has_kwdef_constructor(T) params_with_symbols = Dict(Symbol(k) => v for (k, v) in params) if has_kwdef # case 1: Use slower converter to handle structs with default values return kwarg_struct_builder(T, params_with_symbols) else # case 2: Use faster converter to handle structs with no defaults return StructTypes.constructfrom(T, params_with_symbols) end end """ kwarg_struct_builder(TargetType::Type{T}, params::AbstractDict) where {T} """ function kwarg_struct_builder(TargetType::Type{T}, params::AbstractDict) where {T} info = extract_struct_info(TargetType) param_dict = Dict{Symbol, Any}() for param_name in info.names # ignore unkown parameters if haskey(params, param_name) param_value = params[param_name] target_type = info.map[param_name] # Figure out how to parse the current param if target_type == Any || target_type == String parsed_value = param_value elseif isstructtype(target_type) parsed_value = struct_builder(target_type, param_value) else parsed_value = parsetype(target_type, param_value) end param_dict[param_name] = parsed_value end end return TargetType(;param_dict...) end end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
2155
module RepeatTasks using HTTP using ..Types: RegisteredTask, TaskDefinition, ActiveTask using ..AppContext: TasksContext export starttasks, stoptasks, cleartasks, task """ Create a repeat task and register it with the tasks context """ function task(repeattasks::Set{RegisteredTask}, interval::Real, name::String, f::Function) task_id = hash((name, interval, f)) task = RegisteredTask(task_id, name, interval, f) push!(repeattasks, task) end """ starttasks() Start all background repeat tasks """ function starttasks(tasks::TasksContext) # exit function early if no tasks are register if isempty(tasks.registered_tasks) return end # pull out all ids for the current running tasks running_tasks = Set{UInt}(task.id for task in tasks.active_tasks) # filter out any tasks that are already running filtered_tasks = filter(tasks.registered_tasks) do repeattask if repeattask.id in running_tasks printstyled("[ Task: $(repeattask.name) is already running\n", color = :yellow) return false else return true end end # exit function early if no tasks to start if isempty(filtered_tasks) return end # Start any remaining tasks println() printstyled("[ Starting $(length(filtered_tasks)) Repeat Task(s)\n", color = :magenta, bold = true) for task in filtered_tasks printstyled("[ Task: ", color = :magenta, bold = true) println("{ interval: $(task.interval) seconds, name: $(task.name) }") action = (timer) -> task.action() timer = Timer(action, 0, interval=task.interval) push!(tasks.active_tasks, ActiveTask(task.id, timer)) end end """ stoptasks() Stop all background repeat tasks """ function stoptasks(tasks::TasksContext) for task in tasks.active_tasks if isopen(task.timer) close(task.timer) end end empty!(tasks.active_tasks) end """ cleartasks(ct::Context) Clear any stored repeat task definitions """ function cleartasks(tasks::TasksContext) empty!(tasks.registered_tasks) end end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
4326
module RouterHOF using HTTP using ..Middleware: genkey using ..AppContext: Context, Documenation using ..Types: TaggedRoute, TaskDefinition, CronDefinition, Nullable export router """ This functions assists registering routes with a specific prefix. You can optionally assign tags either at the prefix and/or route level which are used to group and organize the autogenerated documentation """ function router(ctx::Context, prefix::String=""; tags::Vector{String}=Vector{String}(), middleware::Nullable{Vector}=nothing, interval::Nullable{Real}=nothing, cron::Nullable{String}=nothing) return createrouter(ctx, prefix, tags, middleware, interval, cron) end function createrouter(ctx::Context, prefix::String, routertags::Vector{String}, routermiddleware::Nullable{Vector}, routerinterval::Nullable{Real}, routercron::Nullable{String}=nothing) # appends a "/" character to the given string if doesn't have one. function fixpath(path::String) path = String(strip(path)) if !isnothing(path) && !isempty(path) && path !== "/" return startswith(path, "/") ? path : "/$path" end return "" end # This function takes input from the user next to the request handler return function (path=nothing; tags::Vector{String}=Vector{String}(), middleware::Nullable{Vector}=nothing, interval::Nullable{Real}=routerinterval, cron::Nullable{String}=routercron) # this is called inside the @register macro (only it knows the exact httpmethod associated with each path) return function (httpmethod::String) """ This scenario can happen when the user passes a router object directly like so: @get router("/math/power/{a}/{b}") function (req::HTTP.Request, a::Float64, b::Float64) return a ^ b end Under normal circumstances, the function returned by the router call is used when registering routes. However, in this specific case, the call to router returns a higher-order function (HOF) that's nested one layer deeper than expected. Due to the way we call these functions to derive the path for the currently registered route, the path argument can sometimes be mistakenly set to the HTTP method (e.g., "GET", "POST"). This can lead to the path getting concatenated with the HTTP method string. To account for this specific use case, we've added a check in the inner function to verify whether path matches the current passed in httpmethod. If it does, we assume that path has been incorrectly set to the HTTP method, and we update path to use the router prefix instead. """ if path === httpmethod path = prefix else # combine the current routers prefix with this specfic path path = !isnothing(path) ? "$(fixpath(prefix))$(fixpath(path))" : fixpath(prefix) end if !(isnothing(routermiddleware) && isnothing(middleware)) # add both router & route-sepecific middleware ctx.service.custommiddleware[genkey(httpmethod, path)] = (routermiddleware, middleware) end # register interval for this route if !isnothing(interval) && interval >= 0.0 task = TaskDefinition(path, httpmethod, interval) push!(ctx.tasks.task_definitions, task) end # register cron expression for this route if !isnothing(cron) && !isempty(cron) job = CronDefinition(path, httpmethod, cron) push!(ctx.cron.job_definitions, job) end combinedtags = [tags..., routertags...] # register tags if !haskey(ctx.docs.taggedroutes, path) ctx.docs.taggedroutes[path] = TaggedRoute([httpmethod], combinedtags) else combinedmethods = vcat(httpmethod, ctx.docs.taggedroutes[path].httpmethods) ctx.docs.taggedroutes[path] = TaggedRoute(combinedmethods, combinedtags) end #return path return path end end end end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
3633
module Types """ This module holds Structs that are used throughout the application """ using HTTP using Sockets using JSON3 using Dates using Base: @kwdef using DataStructures: CircularDeque using ..Util export Server, History, HTTPTransaction, TaggedRoute, Nullable, ActiveTask, RegisteredTask, TaskDefinition, ActiveCron, RegisteredCron, CronDefinition, Param, isrequired, LazyRequest, headers, pathparams, queryvars, jsonbody, formbody, textbody const Nullable{T} = Union{T, Nothing} # Represents a running task struct ActiveTask id :: UInt timer :: Timer end struct RegisteredTask id :: UInt name :: String interval:: Real action :: Function end # A task defined through the router() HOF struct TaskDefinition path :: String httpmethod :: String interval :: Real end # A cron job defined through the router() HOF struct CronDefinition path :: String httpmethod :: String expression :: String end struct RegisteredCron id :: UInt expression :: String name :: String action :: Function end # Represents a running cron job struct ActiveCron id :: UInt job :: RegisteredCron end struct TaggedRoute httpmethods :: Vector{String} tags :: Vector{String} end struct HTTPTransaction # Intristic Properties ip :: String uri :: String timestamp :: DateTime # derived properties duration :: Float64 success :: Bool status :: Int16 error_message :: Nullable{String} end const Server = HTTP.Server const History = CircularDeque{HTTPTransaction} @kwdef struct Param{T} name::Symbol type::Type{T} default::Union{T, Missing} = missing hasdefault::Bool = false end function isrequired(p::Param{T}) where T return !p.hasdefault || (ismissing(p.default) && !(T <: Missing)) end # Lazily init frequently used components of a request to be used between parameters when parsing @kwdef struct LazyRequest request :: HTTP.Request headers = Ref{Nullable{Dict{String,String}}}(nothing) pathparams = Ref{Nullable{Dict{String,String}}}(nothing) queryparams = Ref{Nullable{Dict{String,String}}}(nothing) formbody = Ref{Nullable{Dict{String,String}}}(nothing) jsonbody = Ref{Nullable{JSON3.Object}}(nothing) textbody = Ref{Nullable{String}}(nothing) end function headers(req::LazyRequest) :: Nullable{Dict{String,String}} if isnothing(req.headers[]) req.headers[] = Dict(String(k) => String(v) for (k,v) in HTTP.headers(req.request)) end return req.headers[] end function pathparams(req::LazyRequest) :: Nullable{Dict{String,String}} if isnothing(req.pathparams[]) req.pathparams[] = HTTP.getparams(req.request) end return req.pathparams[] end function queryvars(req::LazyRequest) :: Nullable{Dict{String,String}} if isnothing(req.queryparams[]) req.queryparams[] = Util.queryparams(req.request) end return req.queryparams[] end function jsonbody(req::LazyRequest) :: Nullable{JSON3.Object} if isnothing(req.jsonbody[]) req.jsonbody[] = json(req.request) end return req.jsonbody[] end function formbody(req::LazyRequest) :: Nullable{Dict{String,String}} if isnothing(req.formbody[]) req.formbody[] = formdata(req.request) end return req.formbody[] end function textbody(req::LazyRequest) :: Nullable{String} if isnothing(req.textbody[]) req.textbody[] = text(req.request) end return req.textbody[] end end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
194
module Util # Bring all our utilities under one module include("utilities/bodyparsers.jl"); include("utilities/render.jl"); include("utilities/misc.jl"); include("utilities/fileutil.jl"); end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
2331
using Requires const PNG = MIME"image/png"() const SVG = MIME"image/svg+xml"() const PDF = MIME"application/pdf"() const HTML = MIME"text/html"() """ response(content::String, status=200, headers=[]) :: HTTP.Response Convert a template string `content` into a valid HTTP Response object. The content type header is automatically generated based on the content's mimetype - `content`: The string content to be included in the HTTP response body. - `status`: The HTTP status code (default is 200). - `headers`: Additional HTTP headers to include (default is an empty array). Returns an `HTTP.Response` object with the specified content, status, and headers. """ function response(content::String, status=200, headers=[]; detect=true) :: HTTP.Response response = HTTP.Response(status, headers, content) detect && HTTP.setheader(response, "Content-Type" => HTTP.sniff(content)) HTTP.setheader(response, "Content-Length" => string(sizeof(content))) return response end function __init__() ################################################################ # Serialization Extensions # ################################################################ @require ProtoBuf = "3349acd9-ac6a-5e09-bcdb-63829b23a429" include("serialization/protobuf.jl") ################################################################ # Templating Extensions # ################################################################ @require Mustache="ffc61752-8dc7-55ee-8c37-f3e9cdd09e70" include("templating/mustache.jl") @require OteraEngine="b2d7f28f-acd6-4007-8b26-bc27716e5513" include("templating/oteraengine.jl") ################################################################ # Plotting Extensions # ################################################################ @require CairoMakie="13f3f980-e62b-5c42-98c6-ff1f3baf88f0" include("plotting/cairomakie.jl") @require Bonito="824d6782-a2ef-11e9-3a09-e5662e0c26f8" include("plotting/bonito.jl") @require WGLMakie="276b4fcb-3e11-5398-bf8b-a0c2d153d008" begin @require Bonito="824d6782-a2ef-11e9-3a09-e5662e0c26f8" begin include("plotting/wglmakie.jl") end end end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
968
import HTTP import .Core.Util: html # import the html function from util so we can override it import .Bonito: Page, App export html """ Converts a Figure object to the designated MIME type and wraps it inside an HTTP response. """ function response(content::App, mime_type::MIME, status::Int, headers::Vector) # Force inlining all data & js dependencies Page(exportable=true, offline=true) # Convert & load the figure into an IOBuffer io = IOBuffer() show(io, mime_type, content) body = take!(io) # format the response resp = HTTP.Response(status, headers, body) HTTP.setheader(resp, "Content-Type" => string(mime_type)) HTTP.setheader(resp, "Content-Length" => string(sizeof(body))) return resp end """ html(app::Bonito.App) :: HTTP.Response Convert a Bonito.App to HTML and wrap it inside an HTTP response. """ html(app::App, status=200, headers=[]) :: HTTP.Response = response(app, HTML, status, headers)
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
1524
import HTTP import .CairoMakie: Figure import .Core.Util: html # import the html function from util so we can override it export png, svg, pdf, html """ Converts a Figure object to the designated MIME type and wraps it inside an HTTP response. """ function response(fig::Figure, mime_type::MIME, status::Int, headers::Vector) :: HTTP.Response # Convert & load the figure into an IOBuffer io = IOBuffer() show(io, mime_type, fig) body = take!(io) # format the response resp = HTTP.Response(status, headers, body) HTTP.setheader(resp, "Content-Type" => string(mime_type)) HTTP.setheader(resp, "Content-Length" => string(sizeof(body))) return resp end """ svg(fig::Figure) :: HTTP.Response Convert a figure to an PNG and wrap it inside an HTTP response. """ png(fig::Figure, status=200, headers=[]) :: HTTP.Response = response(fig, PNG, status, headers) """ svg(fig::Figure) :: HTTP.Response Convert a figure to an SVG and wrap it inside an HTTP response. """ svg(fig::Figure, status=200, headers=[]) :: HTTP.Response = response(fig, SVG, status, headers) """ pdf(fig::Figure) :: HTTP.Response Convert a figure to a PDF and wrap it inside an HTTP response. """ pdf(fig::Figure, status=200, headers=[]) :: HTTP.Response = response(fig, PDF, status, headers) """ html(fig::Figure) :: HTTP.Response Convert a figure to HTML and wrap it inside an HTTP response. """ html(fig::Figure, status=200, headers=[]) :: HTTP.Response = response(fig, HTML, status, headers)
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
1026
import HTTP import .Core.Util: html # import the html function from util so we can override it import .WGLMakie.Makie: FigureLike import .Bonito: Page, App export html """ Converts a Figure object to the designated MIME type and wraps it inside an HTTP response. """ function response(content::FigureLike, mime_type::MIME, status::Int, headers::Vector) # Force inlining all data & js dependencies Page(exportable=true, offline=true) # Convert & load the figure into an IOBuffer io = IOBuffer() show(io, mime_type, content) body = take!(io) # format the response resp = HTTP.Response(status, headers, body) HTTP.setheader(resp, "Content-Type" => string(mime_type)) HTTP.setheader(resp, "Content-Length" => string(sizeof(body))) return resp end """ html(fig::Makie.FigureLike) :: HTTP.Response Convert a Makie figure to HTML and wrap it inside an HTTP response. """ html(fig::FigureLike, status=200, headers=[]) :: HTTP.Response = response(fig, HTML, status, headers)
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
2993
import HTTP import .ProtoBuf: encode, decode, ProtoDecoder, ProtoEncoder import .Core.Extractors: Extractor, extract, try_validate export protobuf, ProtoBuffer, extract """ protobuf(request::HTTP.Request, type::Type{T}) :: T where {T} Decode a protobuf message from the body of an HTTP request. # Arguments - `request`: An HTTP request object containing the protobuf message in its body. - `type`: The type of the protobuf message to decode. # Returns - The decoded protobuf message of the specified type. """ function protobuf(request::HTTP.Request, type::Type{T}) :: T where {T} io = IOBuffer(request.body) return decode(ProtoDecoder(io), type) end function protobuf(response::HTTP.Response, type::Type{T}) :: T where {T} io = IOBuffer(response.body) return decode(ProtoDecoder(io), type) end """ protobuf(content::T, url::String, method::String = "POST") :: HTTP.Request where {T} Encode a protobuf message into the body of an HTTP.Request # Arguments - `content`: The protobuf message to encode. - `target`: The target (URL) to which the request will be sent. - `method`: The HTTP method for the request (default is "POST"). - `headers`: The HTTP headers for the request (default is an empty list). # Returns - An HTTP request object with the encoded protobuf message in its body. """ function protobuf(content::T, target::String; method = "POST", headers = []) :: HTTP.Request where {T} io = IOBuffer() encode(ProtoEncoder(io), content) body = take!(io) # Format the request request = HTTP.Request(method, target, headers, body) HTTP.setheader(request, "Content-Type" => "application/octet-stream") HTTP.setheader(request, "Content-Length" => string(sizeof(body))) return request end """ protobuf(content::T; status = 200, headers = []) :: HTTP.Response where {T} Encode a protobuf message into the body of an HTTP.Response # Arguments - `content`: The protobuf message to encode. - `status`: The HTTP status code for the response (default is 200). - `headers`: The HTTP headers for the response (default is an empty list). # Returns - An HTTP response object with the encoded protobuf message in its body. """ function protobuf(content::T; status = 200, headers = []) :: HTTP.Response where {T} io = IOBuffer() encode(ProtoEncoder(io), content) body = take!(io) # Format the response response = HTTP.Response(status, headers, body = body) HTTP.setheader(response, "Content-Type" => "application/octet-stream") HTTP.setheader(response, "Content-Length" => string(sizeof(body))) return response end struct ProtoBuffer{T} <: Extractor{T} payload::T end """ Extracts a Protobuf message from a request and converts it into a custom struct """ function extract(param::Param{ProtoBuffer{T}}, request::LazyRequest) :: ProtoBuffer{T} where {T} instance = protobuf(request.request, T) valid_instance = try_validate(param, instance) return ProtoBuffer(valid_instance) end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
3088
using HTTP using MIMEs using .Mustache export mustache """ mustache(template::String; kwargs...) Create a function that renders a Mustache `template` string with the provided `kwargs`. If `template` is a file path, it reads the file content as the template string. Returns a function that takes a dictionary `data`, optional `status`, and `headers`, and returns an HTTP Response object with the rendered content. To get more info read the docs here: https://github.com/jverzani/Mustache.jl """ function mustache(template::String; mime_type=nothing, from_file=false, kwargs...) mime_is_known = !isnothing(mime_type) # Case 1: a path to a file was passed if from_file if mime_is_known return open(io -> mustache(io; mime_type=mime_type, kwargs...), template) else # deterime the mime type based on the extension type content_type = mime_from_path(template, MIME"application/octet-stream"()) |> contenttype_from_mime return open(io -> mustache(io; mime_type=content_type, kwargs...), template) end end # Case 2: A string template was passed directly function(data::AbstractDict = Dict(); status=200, headers=[]) content = Mustache.render(template, data; kwargs...) resp_headers = mime_is_known ? [["Content-Type" => mime_type]; headers] : headers response(content, status, resp_headers; detect=!mime_is_known) end end """ mustache(tokens::Mustache.MustacheTokens; kwargs...) Create a function that renders a Mustache template defined by `tokens` with the provided `kwargs`. Returns a function that takes a dictionary `data`, optional `status`, and `headers`, and returns an HTTP Response object with the rendered content. To get more info read the docs here: https://github.com/jverzani/Mustache.jl """ function mustache(tokens::Mustache.MustacheTokens; mime_type=nothing, kwargs...) mime_is_known = !isnothing(mime_type) return function(data::AbstractDict = Dict(); status=200, headers=[]) content = Mustache.render(tokens, data; kwargs...) resp_headers = mime_is_known ? [["Content-Type" => mime_type]; headers] : headers response(content, status, resp_headers; detect=!mime_is_known) end end """ mustache(file::IO; kwargs...) Create a function that renders a Mustache template from a file `file` with the provided `kwargs`. Returns a function that takes a dictionary `data`, optional `status`, and `headers`, and returns an HTTP Response object with the rendered content. To get more info read the docs here: https://github.com/jverzani/Mustache.jl """ function mustache(file::IO; mime_type=nothing, kwargs...) template = read(file, String) mime_is_known = !isnothing(mime_type) return function(data::AbstractDict = Dict(); status=200, headers=[]) content = Mustache.render(template, data; kwargs...) resp_headers = mime_is_known ? [["Content-Type" => mime_type]; headers] : headers response(content, status, resp_headers; detect=!mime_is_known) end end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
2707
using HTTP using MIMEs using .OteraEngine export otera """ otera(template::String; kwargs...) Create a function that renders an Otera `template` string with the provided `kwargs`. If `template` is a file path, it reads the file content as the template string. Returns a function that takes a dictionary `data` (default is an empty dictionary), optional `status`, `headers`, and `template_kwargs`, and returns an HTTP Response object with the rendered content. To get more info read the docs here: https://github.com/MommaWatasu/OteraEngine.jl """ function otera(template::String; mime_type=nothing, from_file=false, kwargs...) mime_is_known = !isnothing(mime_type) # Case 1: a path to a file was passed if from_file if mime_is_known return open(io -> otera(io; mime_type=mime_type, kwargs...), template) else # deterime the mime type based on the extension type content_type = mime_from_path(template, MIME"application/octet-stream"()) |> contenttype_from_mime return open(io -> otera(io; mime_type=content_type, kwargs...), template) end end # Case 2: A string template was passed directly tmp = Template(template, path=from_file; kwargs...) return function(data = nothing; status=200, headers=[], template_kwargs...) combined_kwargs = Dict{Symbol, Any}(template_kwargs) if data !== nothing combined_kwargs[:init] = data end content = tmp(; combined_kwargs...) resp_headers = mime_is_known ? [["Content-Type" => mime_type]; headers] : headers response(content, status, resp_headers; detect=!mime_is_known) end end """ otera(file::IO; kwargs...) Create a function that renders an Otera template from a file `file` with the provided `kwargs`. Returns a function that takes a dictionary `data`, optional `status`, `headers`, and `template_kwargs`, and returns an HTTP Response object with the rendered content. To get more info read the docs here: https://github.com/MommaWatasu/OteraEngine.jl """ function otera(file::IO; mime_type=nothing, kwargs...) template = read(file, String) mime_is_known = !isnothing(mime_type) tmp = Template(template, path=false; kwargs...) return function(data = nothing; status=200, headers=[], template_kwargs...) combined_kwargs = Dict{Symbol, Any}(template_kwargs) if data !== nothing combined_kwargs[:init] = data end content = tmp(; combined_kwargs...) resp_headers = mime_is_known ? [["Content-Type" => mime_type]; headers] : headers response(content, status, resp_headers; detect=!mime_is_known) end end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
2570
using HTTP using JSON3 using StructTypes export text, binary, json, formdata ### Helper functions used to parse the body of a HTTP.Request object """ text(request::HTTP.Request) Read the body of a HTTP.Request as a String """ function text(req::HTTP.Request) :: String body = IOBuffer(HTTP.payload(req)) return eof(body) ? nothing : read(seekstart(body), String) end """ formdata(request::HTTP.Request) Read the html form data from the body of a HTTP.Request """ function formdata(req::HTTP.Request) :: Dict return HTTP.URIs.queryparams(text(req)) end """ binary(request::HTTP.Request) Read the body of a HTTP.Request as a Vector{UInt8} """ function binary(req::HTTP.Request) :: Vector{UInt8} body = IOBuffer(HTTP.payload(req)) return eof(body) ? nothing : readavailable(body) end """ json(request::HTTP.Request; keyword_arguments...) Read the body of a HTTP.Request as JSON with additional arguments for the read/serializer. """ function json(req::HTTP.Request; kwargs...) body = IOBuffer(HTTP.payload(req)) return eof(body) ? nothing : JSON3.read(body; kwargs...) end """ json(request::HTTP.Request, classtype; keyword_arguments...) Read the body of a HTTP.Request as JSON with additional arguments for the read/serializer into a custom struct. """ function json(req::HTTP.Request, classtype::Type{T}; kwargs...) :: T where {T} body = IOBuffer(HTTP.payload(req)) return eof(body) ? nothing : JSON3.read(body, classtype; kwargs...) end ### Helper functions used to parse the body of an HTTP.Response object """ text(response::HTTP.Response) Read the body of a HTTP.Response as a String """ function text(response::HTTP.Response) :: String return String(response.body) end """ formdata(request::HTTP.Response) Read the html form data from the body of a HTTP.Response """ function formdata(response::HTTP.Response) :: Dict return HTTP.URIs.queryparams(text(response)) end """ json(response::HTTP.Response; keyword_arguments) Read the body of a HTTP.Response as JSON with additional keyword arguments """ function json(response::HTTP.Response; kwargs...) :: JSON3.Object return JSON3.read(response.body; kwargs...) end """ json(response::HTTP.Response, classtype; keyword_arguments) Read the body of a HTTP.Response as JSON with additional keyword arguments and serialize it into a custom struct """ function json(response::HTTP.Response, classtype::Type{T}; kwargs...) :: T where {T} return JSON3.read(response.body, classtype; kwargs...) end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
2784
using HTTP export readfile, mountfolder """ readfile(filepath::String) Reads a file as a String """ function readfile(filepath::String) return read(filepath, String) end """ getfiles(folder::String) Return all files inside a folder (searches nested folders) """ function getfiles(folder::String) target_files::Array{String} = [] for (root, _, files) in walkdir(folder) for file in files push!(target_files, joinpath(root, file)) end end return target_files end """ iteratefiles(func::Function, folder::String) Walk through all files in a directory and apply a function to each file """ function iteratefiles(func::Function, folder::String) for filepath in getfiles(folder) func(filepath) end end """ Helper function that returns everything before a designated substring """ function getbefore(input::String, target) :: String result = findfirst(target, input) index = first(result) - 1 return input[begin:index] end """ mountfolder(folder::String, mountdir::String, addroute::Function) This function is used to discover files & register them to the router while leaving the `addroute` function to determine how to register the files """ function mountfolder(folder::String, mountdir::String, addroute) separator = Base.Filesystem.path_separator # track all registered paths paths = Dict{String, Bool}() iteratefiles(folder) do filepath # remove the first occurrence of the root folder from the filepath before "mounting" cleanedmountpath = replace(filepath, "$(folder)$(separator)" => "", count=1) # make sure to replace any system path separator with "/" cleanedmountpath = replace(cleanedmountpath, separator => "/") # generate the path to mount the file to mountpath = mountdir == "/" || isnothing(mountdir) || isempty(mountdir) || all(isspace, mountdir) ? "/$cleanedmountpath" : "/$mountdir/$cleanedmountpath" paths[mountpath] = true # register the file route addroute(mountpath, filepath) # also register file to the root of each subpath if this file is an index.html if endswith(mountpath, "/index.html") # /docs/metrics and /docs/metrics/ are the same path # when HTTP is considered. # # add the route with the trailing "/" character # trimmedpath = getbefore(mountpath, "index.html") # paths[trimmedpath] = true # addroute(trimmedpath, filepath) # add the route without the trailing "/" character bare_path = getbefore(mountpath, "/index.html") paths[bare_path] = true addroute(bare_path, filepath) end end end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
9889
using HTTP using JSON3 using Dates export countargs, recursive_merge, parseparam, queryparams, redirect, handlerequest, format_response!, set_content_size!, format_sse_message ### Request helper functions ### """ queryparams(request::HTTP.Request) Parse's the query parameters from the Requests URL and return them as a Dict """ function queryparams(req::HTTP.Request) :: Dict local uri = HTTP.URI(req.target) return HTTP.queryparams(uri.query) end """ redirect(path::String; code = 308) return a redirect response """ function redirect(path::String; code = 307) :: HTTP.Response return HTTP.Response(code, ["Location" => path]) end function handlerequest(getresponse::Function, catch_errors::Bool; show_errors::Bool = true) if !catch_errors return getresponse() else try return getresponse() catch error if show_errors && !isa(error, InterruptException) @error "ERROR: " exception=(error, catch_backtrace()) end return json(("message" => "The Server encountered a problem"), status = 500) end end end """ countargs(func) Return the number of arguments of the first method of the function `f`. # Arguments - `f`: The function to get the number of arguments for. """ function countargs(f::Function) return methods(f) |> first |> x -> x.nargs end # https://discourse.julialang.org/t/multi-layer-dict-merge/27261/7 recursive_merge(x::AbstractDict...) = merge(recursive_merge, x...) recursive_merge(x...) = x[end] function recursive_merge(x::AbstractVector...) elements = Dict() parameters = [] flattened = cat(x...; dims=1) for item in flattened if !(item isa Dict) || !haskey(item, "name") continue end if haskey(elements, item["name"]) elements[item["name"]] = recursive_merge(elements[item["name"]], item) else elements[item["name"]] = item if !(item["name"] in parameters) push!(parameters, item["name"]) end end end if !isempty(parameters) return [ elements[name] for name in parameters ] else return flattened end end """ Path Parameter Parsing functions """ function parseparam(::Type{Any}, rawvalue::String; escape=true) return escape ? HTTP.unescapeuri(rawvalue) : rawvalue end function parseparam(::Type{String}, rawvalue::String; escape=true) return escape ? HTTP.unescapeuri(rawvalue) : rawvalue end function parseparam(::Type{T}, rawvalue::String; escape=true) where {T <: Enum} return T(parse(Int, escape ? HTTP.unescapeuri(rawvalue) : rawvalue)) end function parseparam(::Type{T}, rawvalue::String; escape=true) where {T <: Union{Date, DateTime}} return parse(T, escape ? HTTP.unescapeuri(rawvalue) : rawvalue) end function parseparam(::Type{T}, rawvalue::String; escape=true) where {T <: Union{Number, Char, Bool, Symbol}} return parse(T, escape ? HTTP.unescapeuri(rawvalue) : rawvalue) end function parseparam(::Type{T}, rawvalue::String; escape=true) where {T} return JSON3.read(escape ? HTTP.unescapeuri(rawvalue) : rawvalue, T) end """ Iterate over the union type and parse the value with the first type that doesn't throw an erorr """ function parseparam(type::Union, rawvalue::String; escape=true) value::String = escape ? HTTP.unescapeuri(rawvalue) : rawvalue result = value for current_type in Base.uniontypes(type) try result = parseparam(current_type, value) break catch continue end end return result end """ Response Formatter functions """ function format_response!(req::HTTP.Request, resp::HTTP.Response) # Return Response's as is without any modifications req.response = resp end function format_response!(req::HTTP.Request, content::AbstractString) # Dynamically determine the content type when given a string body = string(content) HTTP.setheader(req.response, "Content-Type" => HTTP.sniff(body)) HTTP.setheader(req.response, "Content-Length" => string(sizeof(body))) req.response.status = 200 req.response.body = content end function format_response!(req::HTTP.Request, content::Union{Number, Bool, Char, Symbol}) # Convert all primitvies to a string and set the content type to text/plain body = string(content) HTTP.setheader(req.response, "Content-Type" => "text/plain; charset=utf-8") HTTP.setheader(req.response, "Content-Length" => string(sizeof(body))) req.response.status = 200 req.response.body = body end function format_response!(req::HTTP.Request, content::Any) # Convert anthything else to a JSON string body = JSON3.write(content) HTTP.setheader(req.response, "Content-Type" => "application/json; charset=utf-8") HTTP.setheader(req.response, "Content-Length" => string(sizeof(body))) req.response.status = 200 req.response.body = body end """ format_sse_message(data::String; event::Union{String, Nothing} = nothing, id::Union{String, Nothing} = nothing) Create a properly formatted Server-Sent Event (SSE) string. # Arguments - `data`: The data to send. This should be a string. Newline characters in the data will be replaced with separate "data:" lines. - `event`: (optional) The type of event to send. If not provided, no event type will be sent. Should not contain newline characters. - `retry`: (optional) The reconnection time for the event in milliseconds. If not provided, no retry time will be sent. Should be an integer. - `id`: (optional) The ID of the event. If not provided, no ID will be sent. Should not contain newline characters. # Notes This function follows the Server-Sent Events (SSE) specification for sending events to the client. """ function format_sse_message( data :: String; event :: Union{String, Nothing} = nothing, retry :: Union{Int, Nothing} = nothing, id :: Union{String, Nothing} = nothing) :: String has_id = !isnothing(id) has_retry = !isnothing(retry) has_event = !isnothing(event) # check if event or id contain newline characters if has_id && contains(id, '\n') throw(ArgumentError("ID property cannot contain newline characters: $id")) end if has_event && contains(event, '\n') throw(ArgumentError("Event property cannot contain newline characters: $event")) end if has_retry && retry <= 0 throw(ArgumentError("Retry property must be a positive integer: $retry")) end io = IOBuffer() # Make sure we don't send any newlines in the data proptery for line in split(data, '\n') write(io, "data: $line\n") end # Optional properties has_id && write(io, "id: $id\n") has_retry && write(io, "retry: $retry\n") has_event && write(io, "event: $event\n") # Terminate the event, by marking it with a doubule newline write(io, "\n") # return the content of the buffer as a string return String(take!(io)) end """ set_content_size!(body::Base.CodeUnits{UInt8, String}, headers::Vector; add::Bool, replace::Bool) Set the "Content-Length" header in the `headers` vector based on the length of the `body`. # Arguments - `body`: The body of the HTTP response. This should be a `Base.CodeUnits{UInt8, String}`. - `headers`: A vector of headers for the HTTP response. - `add`: A boolean flag indicating whether to add the "Content-Length" header if it doesn't exist. Default is `false`. - `replace`: A boolean flag indicating whether to replace the "Content-Length" header if it exists. Default is `false`. """ function set_content_size!(body::Union{Base.CodeUnits{UInt8, String}, Vector{UInt8}}, headers::Vector; add::Bool, replace::Bool) content_length_found = false for i in 1:length(headers) if headers[i].first == "Content-Length" if replace headers[i] = "Content-Length" => string(sizeof(body)) end content_length_found = true break end end if add && !content_length_found push!(headers, "Content-Length" => string(sizeof(body))) end end # """ # generate_parser(func::Function, pathparams::Vector{Tuple{String,Type}}) # This function generates a parsing function specifically tailored to a given path. # It generates parsing expressions for each parameter and then passes them to the given function. # ```julia # # Here's an exmaple endpoint # @get "/" function(req::HTTP.Request, a::Float64, b::Float64) # return a + b # end # # Here's the function that's generated by the macro # function(func::Function, req::HTTP.Request) # # Extract the path parameters # params = HTTP.getparams(req) # # Generate the parsing expressions # a = parseparam(Float64, params["a"]) # b = parseparam(Float64, params["b"]) # # Call the original function with the parsed parameters in the order they appear # func(req, a, b) # end # ``` # """ # function generate_parser(pathparams) # # Extract the parameter names # func_args = [Symbol(param[1]) for param in pathparams] # # Create the parsing expressions for each path parameter # parsing_exprs = [ # :( $(Symbol(param_name)) = parseparam($(param_type), params[$("$param_name")]) ) # for (param_name, param_type) in pathparams # ] # quote # function(func::Function, req::HTTP.Request) # # Extract the path parameters # params = HTTP.getparams(req) # # Generate the parsing expressions # $(parsing_exprs...) # # Pass the func at runtime, so that revise can work with this # func(req, $(func_args...)) # end # end |> eval # end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
5394
using HTTP using JSON3 using MIMEs export html, text, json, xml, js, css, binary, file """ html(content::String; status::Int, headers::Vector{Pair}) :: HTTP.Response A convenience function to return a String that should be interpreted as HTML """ function html(content::String; status = 200, headers = []) :: HTTP.Response response = HTTP.Response(status, headers, body = content) HTTP.setheader(response, "Content-Type" => "text/html; charset=utf-8") HTTP.setheader(response, "Content-Length" => string(sizeof(content))) return response end """ text(content::String; status::Int, headers::Vector{Pair}) :: HTTP.Response A convenience function to return a String that should be interpreted as plain text """ function text(content::String; status = 200, headers = []) :: HTTP.Response response = HTTP.Response(status, headers, body = content) HTTP.setheader(response, "Content-Type" => "text/plain; charset=utf-8") HTTP.setheader(response, "Content-Length" => string(sizeof(content))) return response end """ json(content::Any; status::Int, headers::Vector{Pair}) :: HTTP.Response A convenience function to return a String that should be interpreted as JSON """ function json(content::Any; status = 200, headers = []) :: HTTP.Response body = JSON3.write(content) response = HTTP.Response(status, headers, body = body) HTTP.setheader(response, "Content-Type" => "application/json; charset=utf-8") HTTP.setheader(response, "Content-Length" => string(sizeof(body))) return response end """ json(content::Vector{UInt8}; status::Int, headers::Vector{Pair}) :: HTTP.Response A helper function that can be passed binary data that should be interpreted as JSON. No conversion is done on the content since it's already in binary format. """ function json(content::Vector{UInt8}; status = 200, headers = []) :: HTTP.Response response = HTTP.Response(status, headers, body = content) HTTP.setheader(response, "Content-Type" => "application/json; charset=utf-8") HTTP.setheader(response, "Content-Length" => string(sizeof(content))) return response end """ xml(content::String; status::Int, headers::Vector{Pair}) :: HTTP.Response A convenience function to return a String that should be interpreted as XML """ function xml(content::String; status = 200, headers = []) :: HTTP.Response response = HTTP.Response(status, headers, body = content) HTTP.setheader(response, "Content-Type" => "application/xml; charset=utf-8") HTTP.setheader(response, "Content-Length" => string(sizeof(content))) return response end """ js(content::String; status::Int, headers::Vector{Pair}) :: HTTP.Response A convenience function to return a String that should be interpreted as JavaScript """ function js(content::String; status = 200, headers = []) :: HTTP.Response response = HTTP.Response(status, headers, body = content) HTTP.setheader(response, "Content-Type" => "application/javascript; charset=utf-8") HTTP.setheader(response, "Content-Length" => string(sizeof(content))) return response end """ css(content::String; status::Int, headers::Vector{Pair}) :: HTTP.Response A convenience function to return a String that should be interpreted as CSS """ function css(content::String; status = 200, headers = []) :: HTTP.Response response = HTTP.Response(status, headers, body = content) HTTP.setheader(response, "Content-Type" => "text/css; charset=utf-8") HTTP.setheader(response, "Content-Length" => string(sizeof(content))) return response end """ binary(content::Vector{UInt8}; status::Int, headers::Vector{Pair}) :: HTTP.Response A convenience function to return a Vector of UInt8 that should be interpreted as binary data """ function binary(content::Vector{UInt8}; status = 200, headers = []) :: HTTP.Response response = HTTP.Response(status, headers, body = content) HTTP.setheader(response, "Content-Type" => "application/octet-stream") HTTP.setheader(response, "Content-Length" => string(sizeof(content))) return response end """ file(filepath::String; loadfile=nothing, status = 200, headers = []) :: HTTP.Response Reads a file and returns a HTTP.Response. The file is read as binary. If the file does not exist, an ArgumentError is thrown. The MIME type and the size of the file are added to the headers. # Arguments - `filepath`: The path to the file to be read. - `loadfile`: An optional function to load the file. If not provided, the file is read using the `open` function. - `status`: The HTTP status code to be used in the response. Defaults to 200. - `headers`: Any additional headers to be included in the response. Defaults to an empty array. # Returns - A HTTP response. """ function file(filepath::String; loadfile = nothing, status = 200, headers = []) :: HTTP.Response has_loadfile = !isnothing(loadfile) content = has_loadfile ? loadfile(filepath) : read(filepath, String) content_length = has_loadfile ? string(sizeof(content)) : string(filesize(filepath)) content_type = mime_from_path(filepath, MIME"application/octet-stream"()) |> contenttype_from_mime response = HTTP.Response(status, headers, body = content) HTTP.setheader(response, "Content-Type" => content_type) HTTP.setheader(response, "Content-Length" => content_length) return response end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
7310
module BodyParserTests using Test using HTTP using StructTypes using Kitten using Kitten: set_content_size! struct rank title :: String power :: Float64 end # added supporting structype StructTypes.StructType(::Type{rank}) = StructTypes.Struct() req = HTTP.Request("GET", "/json", [], """{"message":["hello",1.0]}""") json(req) @testset "formdata() Request struct keyword tests" begin req = HTTP.Request("POST", "/", [], "message=hello world&value=3") data = formdata(req) @test data["message"] == "hello world" @test data["value"] == "3" end @testset "formdata() Response struct keyword tests" begin req = HTTP.Response("message=hello world&value=3") data = formdata(req) @test data["message"] == "hello world" @test data["value"] == "3" end @testset "set_content_size!" begin headers = ["Content-Type" => "text/plain"] body = Vector{UInt8}("Hello, World!") @testset "when add is false and replace is false" begin set_content_size!(body, headers, add=false, replace=false) @test length(headers) == 1 @test headers[1].first == "Content-Type" @test headers[1].second == "text/plain" end @testset "when add is true and replace is false" begin set_content_size!(body, headers, add=true, replace=false) @test length(headers) == 2 @test headers[1].first == "Content-Type" @test headers[1].second == "text/plain" @test headers[2].first == "Content-Length" @test headers[2].second == "13" end @testset "when add is false and replace is true" begin headers = ["Content-Length" => "0", "Content-Type" => "text/plain"] set_content_size!(body, headers, add=false, replace=true) @test length(headers) == 2 @test headers[1].first == "Content-Length" @test headers[1].second == "13" @test headers[2].first == "Content-Type" @test headers[2].second == "text/plain" end @testset "when add is true and replace is true" begin headers = ["Content-Type" => "text/plain"] set_content_size!(body, headers, add=true, replace=true) @test length(headers) == 2 @test headers[1].first == "Content-Type" @test headers[1].second == "text/plain" @test headers[2].first == "Content-Length" @test headers[2].second == "13" end end @testset "json() Request struct keyword tests" begin @testset "json() Request struct keyword tests" begin req = HTTP.Request("GET", "/json", [], "{\"message\":[NaN,1.0]}") @test isnan(json(req, allow_inf = true)["message"][1]) @test !isnan(json(req, allow_inf = true)["message"][2]) req = HTTP.Request("GET", "/json", [], "{\"message\":[Inf,1.0]}") @test isinf(json(req, allow_inf = true)["message"][1]) req = HTTP.Request("GET", "/json", [], "{\"message\":[null,1.0]}") @test isnothing(json(req, allow_inf = false)["message"][1]) end @testset "json() Request stuct keyword with classtype" begin req = HTTP.Request("GET","/", [],"""{"title": "viscount", "power": NaN}""") myjson = json(req, rank, allow_inf = true) @test isnan(myjson.power) req = HTTP.Request("GET","/", [],"""{"title": "viscount", "power": 9000.1}""") myjson = json(req, rank, allow_inf = false) @test myjson.power == 9000.1 end @testset "regular Request json() tests" begin req = HTTP.Request("GET", "/json", [], "{\"message\":[null,1.0]}") @test isnothing(json(req)["message"][1]) @test json(req)["message"][2] == 1 req = HTTP.Request("GET", "/json", [], """{"message":["hello",1.0]}""") @test json(req)["message"][1] == "hello" @test json(req)["message"][2] == 1 req = HTTP.Request("GET", "/json", [], "{\"message\":[3.4,4.0]}") @test json(req)["message"][1] == 3.4 @test json(req)["message"][2] == 4 req = HTTP.Request("GET", "/json", [], "{\"message\":[null,1.0]}") @test isnothing(json(req)["message"][1]) end @testset "json() Request with classtype" begin req = HTTP.Request("GET","/", [],"""{"title": "viscount", "power": NaN}""") myjson = json(req, rank) @test isnan(myjson.power) req = HTTP.Request("GET","/", [],"""{"title": "viscount", "power": 9000.1}""") myjson = json(req, rank) @test myjson.power == 9000.1 # test invalid json req = HTTP.Request("GET","/", [],"""{}""") @test_throws MethodError json(req, rank) # test extra key req = HTTP.Request("GET","/", [],"""{"title": "viscount", "power": 9000.1, "extra": "hi"}""") myjson = json(req, rank) @test myjson.power == 9000.1 end @testset "json() Response" begin res = HTTP.Response("""{"title": "viscount", "power": 9000.1}""") myjson = json(res) @test myjson["power"] == 9000.1 res = HTTP.Response("""{"title": "viscount", "power": 9000.1}""") myjson = json(res, rank) @test myjson.power == 9000.1 end @testset "json() Response struct keyword tests" begin req = HTTP.Response("{\"message\":[NaN,1.0]}") @test isnan(json(req, allow_inf = true)["message"][1]) @test !isnan(json(req, allow_inf = true)["message"][2]) req = HTTP.Response("{\"message\":[Inf,1.0]}") @test isinf(json(req, allow_inf = true)["message"][1]) req = HTTP.Response("{\"message\":[null,1.0]}") @test isnothing(json(req, allow_inf = false)["message"][1]) end @testset "json() Response stuct keyword with classtype" begin req = HTTP.Response("""{"title": "viscount", "power": NaN}""") myjson = json(req, rank, allow_inf = true) @test isnan(myjson.power) req = HTTP.Response("""{"title": "viscount", "power": 9000.1}""") myjson = json(req, rank, allow_inf = false) @test myjson.power == 9000.1 end @testset "regular json() Response tests" begin req = HTTP.Response("{\"message\":[null,1.0]}") @test isnothing(json(req)["message"][1]) @test json(req)["message"][2] == 1 req = HTTP.Response("""{"message":["hello",1.0]}""") @test json(req)["message"][1] == "hello" @test json(req)["message"][2] == 1 req = HTTP.Response("{\"message\":[3.4,4.0]}") @test json(req)["message"][1] == 3.4 @test json(req)["message"][2] == 4 req = HTTP.Response("{\"message\":[null,1.0]}") @test isnothing(json(req)["message"][1]) end @testset "json() Response with classtype" begin req = HTTP.Response("""{"title": "viscount", "power": NaN}""") myjson = json(req, rank) @test isnan(myjson.power) req = HTTP.Response("""{"title": "viscount", "power": 9000.1}""") myjson = json(req, rank) @test myjson.power == 9000.1 # test invalid json req = HTTP.Response("""{}""") @test_throws MethodError json(req, rank) # test extra key req = HTTP.Response("""{"title": "viscount", "power": 9000.1, "extra": "hi"}""") myjson = json(req, rank) @test myjson.power == 9000.1 end end end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
165
module Constants export HOST, PORT, localhost const HOST = "127.0.0.1" const PORT = 6060 # 8080 port is frequently used const localhost = "http://$HOST:$PORT" end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
567
module CronManagementTests using Test using Kitten; @oxidise const iterations = Ref{Int}(0) get(router("/three", cron="*/3")) do iterations[] += 1 end @cron "*/2" function() iterations[] += 1 end @cron "*/5" function() iterations[] += 1 end startcronjobs() startcronjobs() # all active cron jobs should be filtered out and not started again # register a new cron job after the others have already began @cron "*/4" function() iterations[] += 1 end startcronjobs() while iterations[] < 15 sleep(1) end stopcronjobs() clearcronjobs() end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
24449
module CronTests using Test using HTTP using JSON3 using StructTypes using Sockets using Dates using Kitten using Kitten.Cron: iscronmatch, isweekday, lastweekdayofmonth, next, sleep_until, lastweekday, nthweekdayofmonth, matchexpression, translate using ..Constants @testset "Cron Module Tests" begin @testset "translate function tests" begin # Day translations @test translate("SUN") == 7 @test translate("MON") == 1 @test translate("TUE") == 2 @test translate("WED") == 3 @test translate("THU") == 4 @test translate("FRI") == 5 @test translate("SAT") == 6 # Month translations @test translate("JAN") == 1 @test translate("FEB") == 2 @test translate("MAR") == 3 @test translate("APR") == 4 @test translate("MAY") == 5 @test translate("JUN") == 6 @test translate("JUL") == 7 @test translate("AUG") == 8 @test translate("SEP") == 9 @test translate("OCT") == 10 @test translate("NOV") == 11 @test translate("DEC") == 12 # Unmatched Translations @test translate("XYZ") == "XYZ" @test translate("WOW") == "WOW" @test translate("") == "" end @testset "methods" begin @test lastweekday(DateTime(2022,1,1,0,0,0)) == DateTime(2021,12,31,0,0,0) @test lastweekday(DateTime(2022,1,3,0,0,0)) != DateTime(2022,1,8,0,0,0) @test lastweekday(DateTime(2022,1,3,0,0,0)) == DateTime(2022,1,7,0,0,0) @test lastweekday(DateTime(2022,1,3,0,0,0)) != DateTime(2022,1,6,0,0,0) end @testset "lastweekdayofmonth" begin @test lastweekdayofmonth(DateTime(2022,1,1,0,0,0)) == DateTime(2022,1,31,0,0,0) end @testset "nthweekdayofmonth" begin @test_throws ErrorException nthweekdayofmonth(DateTime(2022,1,1,0,0,0), -1) @test_throws ErrorException nthweekdayofmonth(DateTime(2022,1,1,0,0,0), 50) @test nthweekdayofmonth(DateTime(2024, 4, 27), 27) == DateTime(2024, 4, 26) @test nthweekdayofmonth(DateTime(2024, 5, 5), 5) == DateTime(2024, 5, 6) @test nthweekdayofmonth(DateTime(2022, 5, 1), 1) == DateTime(2022, 5, 2) @test nthweekdayofmonth(DateTime(2024, 6, 1), 1) == DateTime(2024, 6, 3) # Test with n as the first day of the month and the first day is a weekday @test nthweekdayofmonth(DateTime(2022, 3, 1), 1) == DateTime(2022, 3, 1) # Test with n as the last day of the month and the last day is a weekday @test nthweekdayofmonth(DateTime(2022, 4, 30), 30) == DateTime(2022, 4, 29) # Test with n as a day in the middle of the month and the day is a weekend @test nthweekdayofmonth(DateTime(2022, 5, 15), 15) == DateTime(2022, 5, 16) # Test with n as a day in the middle of the month and the day is a weekend @test nthweekdayofmonth(DateTime(2022, 6, 18), 18) == DateTime(2022, 6, 17) # Test with n as a day in the middle of the month and the day and the day before are weekends @test nthweekdayofmonth(DateTime(2022, 7, 17), 17) == DateTime(2022, 7, 18) # Test with n as a day in the middle of the month and the day, the day before and the day after are weekends @test nthweekdayofmonth(DateTime(2022, 12, 25), 25) == DateTime(2022, 12, 26) end @testset "sleep_until" begin @test sleep_until(now(), DateTime(2020,1,1,0,0,0)) == 0 end @testset "lastweekdayofmonth function tests" begin # Test when last day of the month is a Friday time = DateTime(2023, 9, 20) @test lastweekdayofmonth(time) == DateTime(2023, 9, 29) # Test when last day of the month is a Saturday time = DateTime(2023, 4, 15) @test lastweekdayofmonth(time) == DateTime(2023, 4, 28) # Test when last day of the month is a Sunday time = DateTime(2023, 10, 10) @test lastweekdayofmonth(time) == DateTime(2023, 10, 31) # Corrected date # Test when last day of the month is a weekday (Monday-Thursday) time = DateTime(2023, 11, 15) @test lastweekdayofmonth(time) == DateTime(2023, 11, 30) # Test with a leap year (February) time = DateTime(2024, 2, 20) @test lastweekdayofmonth(time) == DateTime(2024, 2, 29) # Test with a non-leap year (February) time = DateTime(2023, 2, 20) @test lastweekdayofmonth(time) == DateTime(2023, 2, 28) # Corrected date end @testset "next function tests" begin # Test all fields with asterisk (wildcard) start_time = DateTime(2023, 4, 3, 12, 30, 45) @test next("* * * * * *", start_time) == start_time + Second(1) # Test matching specific fields start_time = DateTime(2023, 1, 1, 0, 0, 0) @test next("30 15 10 5 2 *", start_time) == DateTime(2023, 2, 5, 10, 15, 30) # Test edge case: leap year start_time = DateTime(2020, 1, 1, 0, 0, 0) @test next("0 0 0 29 2 *", start_time) == DateTime(2020, 2, 29, 0, 0, 0) # Test edge case: end of the month start_time = DateTime(2023, 12, 30, 23, 59, 59) @test next("0 0 0 31 12 *", start_time) == DateTime(2023, 12, 31, 0, 0, 0) # Test edge case: end of the year start_time = DateTime(2022, 12, 31, 23, 59, 59) @test next("0 0 0 1 1 *", start_time) == DateTime(2023, 1, 1, 0, 0, 0) # Test day of the week start_time = DateTime(2023, 4, 3, 11, 59, 59) @test next("0 0 12 * * 1", start_time) == DateTime(2023, 4, 3, 12, 0, 0) # Test ranges and increments start_time = DateTime(2023, 4, 3, 10, 35, 0) @test next("0 */10 8-18 * * *", start_time) == DateTime(2023, 4, 3, 10, 40, 0) # Test wrapping around years start_time = DateTime(2023, 12, 31, 23, 59, 59) @test next("0 0 0 1 1 *", start_time) == DateTime(2024, 1, 1, 0, 0, 0) # Test wrapping around months start_time = DateTime(2023, 12, 31, 23, 59, 59) @test next("0 0 0 1 * *", start_time) == DateTime(2024, 1, 1, 0, 0, 0) # Test wrapping around days start_time = DateTime(2023, 4, 3, 23, 59, 59) @test next("0 0 * * * *", start_time) == DateTime(2023, 4, 4, 0, 0, 0) # Test wrapping around hours start_time = DateTime(2023, 4, 3, 23, 59, 59) @test next("0 * * * * *", start_time) == DateTime(2023, 4, 4, 0, 0, 0) # Test wrapping around minutes start_time = DateTime(2023, 4, 3, 23, 59, 59) @test next("* * * * * *", start_time) == DateTime(2023, 4, 4, 0, 0, 0) # Test case with only seconds field start_time = DateTime(2023, 4, 3, 12, 30, 29) @test next("30 * * * * *", start_time) == DateTime(2023, 4, 3, 12, 30, 30) end @testset "next() whole hour normalization tests" begin # these would work fine @test next("1 0 13", DateTime("2024-05-01T10:00:00")) == DateTime("2024-05-01T13:00:01") @test next("0 1 13", DateTime("2024-05-01T10:00:00")) == DateTime("2024-05-01T13:01:00") # these wouldn't previously be normalized with zero values @test next("0 0 13", DateTime("2024-05-01T10:00:00")) == DateTime("2024-05-01T13:00:00") @test next("0 0 13", DateTime("2024-05-01T14:00:00")) == DateTime("2024-05-02T13:00:00") # Test cases where the current time is exactly on the hour @test next("0 0 14", DateTime("2024-05-01T14:00:00")) == DateTime("2024-05-02T14:00:00") @test next("0 0 0", DateTime("2024-05-01T00:00:00")) == DateTime("2024-05-02T00:00:00") # Test cases where the current time is exactly one second before the hour @test next("0 0 15", DateTime("2024-05-01T14:59:59")) == DateTime("2024-05-01T15:00:00") @test next("0 0 1", DateTime("2024-05-01T00:59:59")) == DateTime("2024-05-01T01:00:00") # Test cases where the current time is exactly one second after the hour @test next("0 0 16", DateTime("2024-05-01T16:00:01")) == DateTime("2024-05-02T16:00:00") @test next("0 0 2", DateTime("2024-05-01T02:00:01")) == DateTime("2024-05-02T02:00:00") # Test cases where the current time is exactly on the half hour @test next("0 30 17", DateTime("2024-05-01T17:30:00")) == DateTime("2024-05-02T17:30:00") @test next("0 30 3", DateTime("2024-05-01T03:30:00")) == DateTime("2024-05-02T03:30:00") # Test cases where the current time is exactly one second before the half hour @test next("0 30 18", DateTime("2024-05-01T18:29:59")) == DateTime("2024-05-01T18:30:00") @test next("0 30 4", DateTime("2024-05-01T04:29:59")) == DateTime("2024-05-01T04:30:00") # Test cases where the current time is exactly one second after the half hour @test next("0 30 19", DateTime("2024-05-01T19:30:01")) == DateTime("2024-05-02T19:30:00") @test next("0 30 5", DateTime("2024-05-01T05:30:01")) == DateTime("2024-05-02T05:30:00") # Test case for second @test next("* * * * *", DateTime(2022, 5, 15, 14, 30, 0)) == DateTime(2022, 5, 15, 14, 30, 1) # Test case for minute @test next("0 * * * *", DateTime(2022, 5, 15, 14, 30)) == DateTime(2022, 5, 15, 14, 31) # Test case for hour @test next("0 0 * *", DateTime(2022, 5, 15, 14, 30)) == DateTime(2022, 5, 15, 15, 0) # Test case for day of month @test next("0 0 0 * *", DateTime(2022, 5, 15)) == DateTime(2022, 5, 16) # # Test case for month @test next("0 0 0 1 *", DateTime(2022, 5, 15)) == DateTime(2022, 6, 1) # Test case for day of week @test next("0 0 * * * MON", DateTime(2022, 5, 15)) == DateTime(2022, 5, 16) # invalid valude for day of month # @test next("0 0 0 0 *", DateTime(2022, 5, 15)) == DateTime(2022, 5, 16) end @testset "matchexpression function tests" begin time = DateTime(2023, 4, 3, 23, 59, 59) minute = Dates.minute second = Dates.second @test matchexpression(SubString("*"), time, minute, 59) == true @test matchexpression(SubString("59"), time, minute, 59) == true @test matchexpression(SubString("15"), time, minute, 59) == false @test matchexpression(SubString("45,59"), time, second, 59) == true @test matchexpression(SubString("15,30"), time, second, 59) == false @test matchexpression(SubString("50-59"), time, second, 59) == true @test matchexpression(SubString("10-40"), time, second, 59) == false @test matchexpression(SubString("59-*"), time, minute, 59) == true @test matchexpression(SubString("*-58"), time, minute, 59) == false @test matchexpression(SubString("*/10"), time, minute, 59) == false @test matchexpression(SubString("25/5"), time, minute, 59) == false end @testset "seconds tests" begin # check exact second @test iscronmatch("5/*", DateTime(2022,1,1,1,0,5)) == true @test iscronmatch("7/*", DateTime(2022,1,1,1,0,7)) == true # check between ranges @test iscronmatch("5-*", DateTime(2022,1,1,1,0,7)) == true @test iscronmatch("*-10", DateTime(2022,1,1,1,0,7)) == true end @testset "static matches" begin # Exact second match @test iscronmatch("0", DateTime(2022,1,1,1,0,0)) == true @test iscronmatch("1", DateTime(2022,1,1,1,0,1)) == true @test iscronmatch("5", DateTime(2022,1,1,1,0,5)) == true @test iscronmatch("7", DateTime(2022,1,1,1,0,7)) == true @test iscronmatch("39", DateTime(2022,1,1,1,0,39)) == true @test iscronmatch("59", DateTime(2022,1,1,1,0,59)) == true # Exact minute match @test iscronmatch("* 0", DateTime(2022,1,1,1,0,0)) == true @test iscronmatch("* 1", DateTime(2022,1,1,1,1,0)) == true @test iscronmatch("* 5", DateTime(2022,1,1,1,5,0)) == true @test iscronmatch("* 7", DateTime(2022,1,1,1,7,0)) == true @test iscronmatch("* 39", DateTime(2022,1,1,1,39,0)) == true @test iscronmatch("* 59", DateTime(2022,1,1,1,59,0)) == true # Exact hour match @test iscronmatch("* * 0", DateTime(2022,1,1,0,0,0)) == true @test iscronmatch("* * 1", DateTime(2022,1,1,1,0,0)) == true @test iscronmatch("* * 5", DateTime(2022,1,1,5,0,0)) == true @test iscronmatch("* * 12", DateTime(2022,1,1,12,0,0)) == true @test iscronmatch("* * 20", DateTime(2022,1,1,20,0,0)) == true @test iscronmatch("* * 23", DateTime(2022,1,1,23,0,0)) == true # Exact day match @test iscronmatch("* * * 1", DateTime(2022,1,1,1,0,0)) == true @test iscronmatch("* * * 5", DateTime(2022,1,5,1,0,0)) == true @test iscronmatch("* * * 12", DateTime(2022,1,12,1,0,0)) == true @test iscronmatch("* * * 20", DateTime(2022,1,20,1,0,0)) == true @test iscronmatch("* * * 31", DateTime(2022,1,31,1,0,0)) == true # Exact month match @test iscronmatch("* * * * 1", DateTime(2022,1,1,0,0,0)) == true @test iscronmatch("* * * * 4", DateTime(2022,4,1,1,0,0)) == true @test iscronmatch("* * * * 5", DateTime(2022,5,1,1,0,0)) == true @test iscronmatch("* * * * 9", DateTime(2022,9,1,1,0,0)) == true @test iscronmatch("* * * * 12", DateTime(2022,12,1,1,0,0)) == true # Exact day of week match @test iscronmatch("* * * * * MON", DateTime(2022,1,3,0,0,0)) == true @test iscronmatch("* * * * * MON", DateTime(2022,1,10,0,0,0)) == true @test iscronmatch("* * * * * MON", DateTime(2022,1,17,0,0,0)) == true @test iscronmatch("* * * * * TUE", DateTime(2022,1,4,0,0,0)) == true @test iscronmatch("* * * * * TUE", DateTime(2022,1,11,0,0,0)) == true @test iscronmatch("* * * * * TUE", DateTime(2022,1,18,0,0,0)) == true @test iscronmatch("* * * * * WED", DateTime(2022,1,5,0,0,0)) == true @test iscronmatch("* * * * * WED", DateTime(2022,1,12,0,0,0)) == true @test iscronmatch("* * * * * WED", DateTime(2022,1,19,0,0,0)) == true @test iscronmatch("* * * * * THU", DateTime(2022,1,6,0,0,0)) == true @test iscronmatch("* * * * * THU", DateTime(2022,1,13,0,0,0)) == true @test iscronmatch("* * * * * THU", DateTime(2022,1,20,0,0,0)) == true @test iscronmatch("* * * * * FRI", DateTime(2022,1,7,0,0,0)) == true @test iscronmatch("* * * * * FRI", DateTime(2022,1,14,0,0,0)) == true @test iscronmatch("* * * * * FRI", DateTime(2022,1,21,0,0,0)) == true @test iscronmatch("* * * * * SAT", DateTime(2022,1,8,0,0,0)) == true @test iscronmatch("* * * * * SAT", DateTime(2022,1,15,0,0,0)) == true @test iscronmatch("* * * * * SAT", DateTime(2022,1,22,0,0,0)) == true @test iscronmatch("* * * * * SUN", DateTime(2022,1,2,0,0,0)) == true @test iscronmatch("* * * * * SUN", DateTime(2022,1,9,0,0,0)) == true @test iscronmatch("* * * * * SUN", DateTime(2022,1,16,0,0,0)) == true end # # More specific test cases # # "0 0 * * * *" = the top of every hour of every day. # # "*/10 * * * * *" = every ten seconds. # # "0 0 8-10 * * *" = 8, 9 and 10 o'clock of every day. # # "0 0 6,19 * * *" = 6:00 AM and 7:00 PM every day. # # "0 0/30 8-10 * * *" = 8:00, 8:30, 9:00, 9:30, 10:00 and 10:30 every day. # # "0 0 9-17 * * MON-FRI" = on the hour nine-to-five weekdays # # "0 0 0 25 12 ?" = every Christmas Day at midnight # # "0 0 0 L * *" = last day of the month at midnight # # "0 0 0 L-3 * *" = third-to-last day of the month at midnight # # "0 0 0 1W * *" = first weekday of the month at midnight # # "0 0 0 LW * *" = last weekday of the month at midnight # # "0 0 0 * * 5L" = last Friday of the month at midnight # # "0 0 0 * * THUL" = last Thursday of the month at midnight # # "0 0 0 ? * 5#2" = the second Friday in the month at midnight # # "0 0 0 ? * MON#1" = the first Monday in the month at midnight @testset "the top of every hour of every day" begin for hour in 0:23 @test iscronmatch("0 0 * * * *", DateTime(2022,1,1,hour,0,0)) == true end end @testset "the 16th minute of every hour of every day" begin for hour in 0:23 @test iscronmatch("0 16 * * * *", DateTime(2022,1,1,hour,16,0)) == true end end @testset "8, 9 and 10 o'clock of every day." begin for hour in 0:23 @test iscronmatch("0 0 8-10 * * *", DateTime(2022,1,1,hour,0,0)) == (hour >= 8 && hour <= 10) end end @testset "every 10 seconds" begin @test iscronmatch("*/10 * * * * *", DateTime(2022,1,9,1,0,0)) == true @test iscronmatch("*/10 * * * * *", DateTime(2022,1,9,1,0,10)) == true @test iscronmatch("*/10 * * * * *", DateTime(2022,1,9,1,0,20)) == true @test iscronmatch("*/10 * * * * *", DateTime(2022,1,9,1,0,30)) == true @test iscronmatch("*/10 * * * * *", DateTime(2022,1,9,1,0,40)) == true @test iscronmatch("*/10 * * * * *", DateTime(2022,1,9,1,0,50)) == true end @testset "every 7 seconds" begin @test iscronmatch("*/7 * * * * *", DateTime(2022,1,9,1,0,0)) == false @test iscronmatch("*/7 * * * * *", DateTime(2022,1,9,1,0,7)) == true @test iscronmatch("*/7 * * * * *", DateTime(2022,1,9,1,0,14)) == true @test iscronmatch("*/7 * * * * *", DateTime(2022,1,9,1,0,21)) == true @test iscronmatch("*/7 * * * * *", DateTime(2022,1,9,1,0,28)) == true @test iscronmatch("*/7 * * * * *", DateTime(2022,1,9,1,0,35)) == true @test iscronmatch("*/7 * * * * *", DateTime(2022,1,9,1,0,42)) == true @test iscronmatch("*/7 * * * * *", DateTime(2022,1,9,1,0,49)) == true @test iscronmatch("*/7 * * * * *", DateTime(2022,1,9,1,0,56)) == true end @testset "every 15 seconds" begin @test iscronmatch("*/15 * * * * *", DateTime(2022,1,9,1,0,0)) == true @test iscronmatch("*/15 * * * * *", DateTime(2022,1,9,1,0,15)) == true @test iscronmatch("*/15 * * * * *", DateTime(2022,1,9,1,0,30)) == true @test iscronmatch("*/15 * * * * *", DateTime(2022,1,9,1,0,45)) == true end @testset "6:00 AM and 7:00 PM every day" begin for day in 1:20 for hour in 0:23 @test iscronmatch("0 0 6,19 * * *", DateTime(2022,1,day,hour,0,0)) == (hour == 6 || hour == 19) end end end @testset "8:00, 8:30, 9:00, 9:30, 10:00 and 10:30 every day" begin for day in 1:20 for hour in 0:23 @test iscronmatch("0 0/30 8-10 * * *", DateTime(2022,1,day,hour,30,0)) == (hour >= 8 && hour <= 10) @test iscronmatch("0 0/30 8-10 * * *", DateTime(2022,1,day,hour,0,0)) == (hour >= 8 && hour <= 10) end end end @testset "on the hour nine-to-five weekdays" begin for day in 1:20 if isweekday(DateTime(2022,1,day,0,0,0)) for hour in 0:23 @test iscronmatch("0 0 9-17 * * MON-FRI", DateTime(2022,1,day,hour,0,0)) == (hour >= 9 && hour <= 17) end end end end @testset "every Christmas Day at midnight" begin for month in 1:12 for hour in 0:23 @test iscronmatch("0 0 0 25 12 ?", DateTime(2022,month,25,hour,0,0)) == (month == 12 && hour == 0) end end end @testset "last day of the month at midnight" begin for month in 1:12 num_days = daysinmonth(2022, month) for day in 1:num_days for hour in 0:23 @test iscronmatch("0 0 0 L * *", DateTime(2022,month,day,hour,0,0)) == (day == num_days && hour == 0) end end end end @testset "third-to-last day of the month at midnight" begin for month in 1:12 num_days = daysinmonth(2022, month) for day in 1:num_days for hour in 0:23 @test iscronmatch("0 0 0 L-3 * *", DateTime(2022,month,day,hour,0,0)) == (day == (num_days-3) && hour == 0) end end end end @testset "first weekday of the month at midnight" begin @test iscronmatch("0 0 0 1W * *", DateTime(2022, 1, 3, 0, 0, 0)) @test iscronmatch("0 0 0 9W * *", DateTime(2022, 1, 10, 0, 0, 0)) @test iscronmatch("0 0 0 13W * *", DateTime(2022, 1, 13, 0, 0, 0)) @test iscronmatch("0 0 0 15W * *", DateTime(2022, 1, 14, 0, 0, 0)) @test iscronmatch("0 0 0 22W * *", DateTime(2022, 1, 21, 0, 0, 0)) @test iscronmatch("0 0 0 31W * *", DateTime(2022, 1, 31, 0, 0, 0)) end @testset "last weekday of the month at midnight" begin @test iscronmatch("0 0 0 LW * *", DateTime(2022, 1, 28, 0, 0, 0)) == false @test iscronmatch("0 0 0 LW * *", DateTime(2022, 1, 29, 0, 0, 0)) == false @test iscronmatch("0 0 0 LW * *", DateTime(2022, 1, 30, 0, 0, 0)) == false @test iscronmatch("0 0 0 LW * *", DateTime(2022, 1, 30, 0, 0, 0)) == false @test iscronmatch("0 0 0 LW * *", DateTime(2022, 1, 31, 0, 0, 0)) end @testset "last Friday of the month at midnight" begin @test iscronmatch("0 0 0 * * 5L", DateTime(2022, 1, 28, 0, 0, 0)) @test iscronmatch("0 0 0 * * 5L", DateTime(2022, 1, 29, 0, 0, 0)) == false @test iscronmatch("0 0 0 * * 5L", DateTime(2022, 1, 29, 0, 0, 0)) == false @test iscronmatch("0 0 0 * * 5L", DateTime(2022, 2, 25, 0, 0, 0)) end @testset "last Thursday of the month at midnight" begin @test iscronmatch("0 0 0 * * THUL", DateTime(2022, 1, 26, 0, 0, 0)) == false @test iscronmatch("0 0 0 * * THUL", DateTime(2022, 1, 27, 0, 0, 0)) @test iscronmatch("0 0 0 * * THUL", DateTime(2022, 1, 28, 0, 0, 0)) == false @test iscronmatch("0 0 0 * * THUL", DateTime(2022, 2, 3, 0, 0, 0)) == false end @testset "the second Friday in the month at midnight" begin @test iscronmatch("0 0 0 ? * 5#2", DateTime(2022, 1, 14, 0, 0, 0)) @test iscronmatch("0 0 0 ? * 5#2", DateTime(2022, 2, 11, 0, 0, 0)) @test iscronmatch("0 0 0 ? * 5#2", DateTime(2022, 3, 11, 0, 0, 0)) @test iscronmatch("0 0 0 ? * 5#2", DateTime(2022, 4, 8, 0, 0, 0)) @test iscronmatch("0 0 0 ? * 5#2", DateTime(2022, 5, 13, 0, 0, 0)) end @testset "the first Monday in the month at midnight" begin @test iscronmatch("0 0 0 ? * MON#1", DateTime(2022, 1, 2, 0, 0, 0)) == false @test iscronmatch("0 0 0 ? * MON#1", DateTime(2022, 1, 3, 0, 0, 0)) @test iscronmatch("0 0 0 ? * MON#1", DateTime(2022, 1, 4, 0, 0, 0)) == false @test iscronmatch("0 0 0 ? * MON#1", DateTime(2022, 2, 6, 0, 0, 0)) == false @test iscronmatch("0 0 0 ? * MON#1", DateTime(2022, 2, 7, 0, 0, 0)) @test iscronmatch("0 0 0 ? * MON#1", DateTime(2022, 2, 8, 0, 0, 0)) == false @test iscronmatch("0 0 0 ? * MON#1", DateTime(2022, 3, 6, 0, 0, 0)) == false @test iscronmatch("0 0 0 ? * MON#1", DateTime(2022, 3, 7, 0, 0, 0)) @test iscronmatch("0 0 0 ? * MON#1", DateTime(2022, 3, 8, 0, 0, 0)) == false @test iscronmatch("0 0 0 ? * MON#1", DateTime(2022, 4, 3, 0, 0, 0)) == false @test iscronmatch("0 0 0 ? * MON#1", DateTime(2022, 4, 4, 0, 0, 0)) @test iscronmatch("0 0 0 ? * MON#1", DateTime(2022, 4, 5, 0, 0, 0)) == false end localhost = "http://127.0.0.1:$PORT" crondata = Dict("api_value" => 0) @get router("/cron-increment", cron="*") function(req) crondata["api_value"] = crondata["api_value"] + 1 return crondata["api_value"] end @get "/get-cron-increment" function() return crondata["api_value"] end server = serve(async=true, port=PORT, show_banner=false) sleep(3) try internalrequest(HTTP.Request("GET", "/cron-increment")) internalrequest(HTTP.Request("GET", "/cron-increment")) @testset "Testing CRON API access" begin r = internalrequest(HTTP.Request("GET", "/get-cron-increment")) @test r.status == 200 @test parse(Int64, text(r)) > 0 end catch e println(e) finally close(server) end end end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
8516
module ExtractorTests using Base: @kwdef using Test using HTTP using Suppressor using ProtoBuf using ..Constants using Kitten; @oxidise using Kitten: extract, Param, LazyRequest, Extractor # extend the built-in validate function import Kitten: validate include("extensions/protobuf/messages/test_pb.jl") using .test_pb: MyMessage struct Person name::String age::Int end @kwdef struct Home address::String owner::Person end # Add a lower bound to age with a global validator validate(p::Person) = p.age >= 0 @testset "Extactor builder sytnax" begin @test Json{Person}(x -> x.age >= 25) isa Extractor @test Json(Person) isa Extractor @test Json(Person, x -> x.age >= 25) isa Extractor p = Person("joe", 25) @test Json(p) isa Extractor @test Json(p, x -> x.age >= 25) isa Extractor end @testset "JSON extract" begin req = HTTP.Request("GET", "/", [], """{"name": "joe", "age": 25}""") param = Param(:person, Json{Person}, missing, false) p = extract(param, LazyRequest(request=req)).payload @test p.name == "joe" @test p.age == 25 end @testset "kwarg_struct_builder Nested test" begin req = HTTP.Request("GET", "/", [], """ { "address": "123 main street", "owner": { "name": "joe", "age": 25 } } """) param = Param(:person, Json{Home}, missing, false) p = extract(param, LazyRequest(request=req)).payload @test p isa Home @test p.owner isa Person @test p.address == "123 main street" @test p.owner.name == "joe" @test p.owner.age == 25 end @testset "Partial JSON extract" begin req = HTTP.Request("GET", "/", [], """{ "person": {"name": "joe", "age": 25} }""") param = Param(:person, JsonFragment{Person}, missing, false) p = extract(param, LazyRequest(request=req)).payload @test p.name == "joe" @test p.age == 25 end @testset "Form extract" begin req = HTTP.Request("GET", "/", [], """name=joe&age=25""") param = Param(:form, Form{Person}, missing, false) p = extract(param, LazyRequest(request=req)).payload @test p.name == "joe" @test p.age == 25 # Test that negative age trips the global validator req = HTTP.Request("GET", "/", [], """name=joe&age=-4""") param = Param(:form, Form{Person}, missing, false) @test_throws ArgumentError extract(param, LazyRequest(request=req)) # Test that age < 25 trips the local validator req = HTTP.Request("GET", "/", [], """name=joe&age=10""") default_value = Form{Person}(x -> x.age > 25) param = Param(:form, Form{Person}, default_value, true) @test_throws ArgumentError extract(param, LazyRequest(request=req)) end @testset "Path extract" begin req = HTTP.Request("GET", "/person/john/20", []) req.context[:params] = Dict("name" => "john", "age" => "20") # simulate path params param = Param(:path, Path{Person}, missing, false) p = extract(param, LazyRequest(request=req)).payload @test p.name == "john" @test p.age == 20 end @testset "Query extract" begin req = HTTP.Request("GET", "/person?name=joe&age=30", []) param = Param(:query, Query{Person}, missing, false) p = extract(param, LazyRequest(request=req)).payload @test p.name == "joe" @test p.age == 30 # test custom instance validator req = HTTP.Request("GET", "/person?name=joe&age=30", []) default_value = Query{Person}(x -> x.age > 25) param = Param(:query, Query{Person}, default_value, true) p = extract(param, LazyRequest(request=req)).payload @test p.name == "joe" @test p.age == 30 end @testset "Header extract" begin req = HTTP.Request("GET", "/person", ["name" => "joe", "age" => "19"]) param = Param(:header, Header{Person}, missing, false) p = extract(param, LazyRequest(request=req)).payload @test p.name == "joe" @test p.age == 19 end @testset "Body extract" begin # Parse Float64 from body req = HTTP.Request("GET", "/", [], "3.14") param = Param(:form, Body{Float64}, missing, false) value = extract(param, LazyRequest(request=req)).payload @test value == 3.14 # Parse String from body req = HTTP.Request("GET", "/", [], "Here's a regular string") param = Param(:form, Body{String}, missing, false) value = extract(param, LazyRequest(request=req)).payload @test value == "Here's a regular string" end @kwdef struct Sample limit::Int skip::Int = 33 end @kwdef struct PersonWithDefault name::String age::Int value::Float64 = 1.5 end struct Parameters b::Int end @testset "Api tests" begin get("/") do text("home") end @get "/headers" function(req, headers = Header(Sample, s -> s.limit > 5)) return headers.payload end post("/form") do req, form::Form{Sample} return form.payload |> json end get("/query") do req, query::Query{Sample} return query.payload |> json end post("/body/string") do req, body::Body{String} return body.payload end post("/body/float") do req, body::Body{Float64} return body.payload end @post "/json" function(req, data = Json{PersonWithDefault}(s -> s.value < 10)) return data.payload end post("/protobuf") do req, data::ProtoBuffer{MyMessage} return protobuf(data.payload) end post("/json/partial") do req, p1::JsonFragment{PersonWithDefault}, p2::JsonFragment{PersonWithDefault} return json((p1=p1.payload, p2=p2.payload)) end @get "/path/add/{a}/{b}" function(req, a::Int, path::Path{Parameters}, qparams::Query{Sample}, c::Nullable{Int}=23) return a + path.payload.b end r = internalrequest(HTTP.Request("GET", "/")) @test r.status == 200 @test text(r) == "home" r = internalrequest(HTTP.Request("GET", "/path/add/3/7?limit=10")) @test r.status == 200 @test text(r) == "10" r = internalrequest(HTTP.Request("POST", "/form", [], """limit=10&skip=25""")) @test r.status == 200 data = json(r) @test data["limit"] == 10 @test data["skip"] == 25 r = internalrequest(HTTP.Request("GET", "/query?limit=10&skip=25")) @test r.status == 200 data = json(r) @test data["limit"] == 10 @test data["skip"] == 25 r = internalrequest(HTTP.Request("POST", "/body/string", [], """Hello World!""")) @test r.status == 200 @test text(r) == "Hello World!" r = internalrequest(HTTP.Request("POST", "/body/float", [], """3.14""")) @test r.status == 200 @test parse(Float64, text(r)) == 3.14 @suppress_err begin # should fail since we are missing query params r = internalrequest(HTTP.Request("GET", "/path/add/3/7")) @test r.status == 500 end r = internalrequest(HTTP.Request("GET", "/headers", ["limit" => "10"], "")) @test r.status == 200 data = json(r) @test data["limit"] == 10 @test data["skip"] == 33 @suppress_err begin # should fail since we are missing query params r = internalrequest(HTTP.Request("GET", "/headers", ["limit" => "3"], "")) @test r.status == 500 end @suppress_err begin # value is higher than the limit set in the validator r = internalrequest(HTTP.Request("POST", "/json", [], """ { "name": "joe", "age": 24, "value": 12.0 } """)) @test r.status == 500 end r = internalrequest(HTTP.Request("POST", "/json", [], """ { "name": "joe", "age": 24, "value": 4.8 } """)) data = json(r) @test data["name"] == "joe" @test data["age"] == 24 @test data["value"] == 4.8 r = internalrequest(HTTP.Request("POST", "/json/partial", [], """ { "p1": { "name": "joe", "age": "24" }, "p2": { "name": "kim", "age": "25", "value": 100.0 } } """)) @test r.status == 200 data = json(r) p1 = data["p1"] p2 = data["p2"] @test p1["name"] == "joe" @test p1["age"] == 24 @test p1["value"] == 1.5 @test p2["name"] == "kim" @test p2["age"] == 25 @test p2["value"] == 100 message = MyMessage(-1, ["a", "b"]) r = internalrequest(protobuf(message, "/protobuf")) decoded_msg = protobuf(r, MyMessage) @test decoded_msg isa MyMessage @test decoded_msg.a == -1 @test decoded_msg.b == ["a", "b"] end end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
1269
module HandlerTests using Test using HTTP using ..Constants using Kitten; @oxidise @get "/noarg" function(;request) @test isa(request, HTTP.Request) return text("Hello World") end @get "/params/double/{a}" function(req, a::Float64; request::HTTP.Request) @test isa(request, HTTP.Request) return text("$(a*2)") end @get "/singlearg" function(req; request) @test isa(req, HTTP.Request) @test isa(request, HTTP.Request) return text("Hello World") end serve(port=PORT, host=HOST, async=true, show_errors=false, show_banner=false, access_log=nothing) @testset "Handler request Injection Tests" begin @testset "Inject request into no arg function" begin response = HTTP.get("$localhost/noarg") @test response.status == 200 @test text(response) == "Hello World" end @testset "Inject request into function with path params" begin response = HTTP.get("$localhost/params/double/5") @test response.status == 200 @test text(response) == "10.0" end @testset "Inject request into function with single arg" begin response = HTTP.get("$localhost/singlearg") @test response.status == 200 @test text(response) == "Hello World" end end terminate() end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
1745
module MultiInstanceTests using Test using HTTP using Kitten using ..Constants # Setup the first app app1 = instance() app1.get("/") do "welcome to server #1" end app1.get("/subtract/{a}/{b}") do req, a::Int, b::Int Dict("answer" => a - b) |> json end # Setup the second app app2 = instance() app2.get("/") do "welcome to server #2" end app2.get("/add/{a}/{b}") do req, a::Int, b::Int Dict("answer" => a + b) |> json end # start both servers together app1.serve(port=PORT, async=true, show_errors=false, show_banner=false) app2.serve(port=PORT + 1, async=true, show_errors=false, show_banner=false) @testset "testing unqiue instances" begin r = app1.internalrequest(HTTP.Request("GET", "/")) @test r.status == 200 @test text(r) == "welcome to server #1" r = app2.internalrequest(HTTP.Request("GET", "/")) @test r.status == 200 @test text(r) == "welcome to server #2" end @testset "testing add and subtract endpoints" begin # Test subtract endpoint on server #1 r = app1.internalrequest(HTTP.Request("GET", "/subtract/10/5")) @test r.status == 200 @test json(r)["answer"] == 5 # Test add endpoint on server #2 r = app2.internalrequest(HTTP.Request("GET", "/add/10/5")) @test r.status == 200 @test json(r)["answer"] == 15 # Test subtract endpoint with negative result on server #1 r = app1.internalrequest(HTTP.Request("GET", "/subtract/5/10")) @test r.status == 200 @test json(r)["answer"] == -5 # Test add endpoint with negative numbers on server #2 r = app2.internalrequest(HTTP.Request("GET", "/add/-10/-5")) @test r.status == 200 @test json(r)["answer"] == -15 end # clean it up app1.terminate() app2.terminate() end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
5461
module MetricsTests using Test using Dates using HTTP using Kitten using ..Constants using Kitten.Core.Metrics: percentile, HTTPTransaction, TimeseriesRecord, get_history, push_history, group_transactions, get_transaction_metrics, recent_transactions, all_endpoint_metrics, server_metrics, error_distribution, prepare_timeseries_data, timeseries, series_format, bin_transactions, requests_per_unit, avg_latency_per_unit, endpoint_metrics # Mock Data const MOCK_TIMESTAMP = DateTime(2021, 1, 1, 12, 0, 0) const MOCK_HTTP_TRANSACTION = HTTPTransaction("192.168.1.1", "/test", MOCK_TIMESTAMP, 0.5, true, 200, nothing) # Helper Function to Create Mock Transactions function create_mock_transactions(n::Int) [HTTPTransaction("192.168.1.$i", "/test/$i", MOCK_TIMESTAMP, 0.1 * i, i % 2 == 0, 200 + i, nothing) for i in 1:n] end const HISTORY = Kitten.History(1_000_000) function clear_history() empty!(HISTORY) end @testset "Metrics Module Tests" begin # Test for push_history and get_history @testset "History Management" begin clear_history() push_history(HISTORY, MOCK_HTTP_TRANSACTION) @test length(get_history(HISTORY)) == 1 @test get_history(HISTORY)[1] === MOCK_HTTP_TRANSACTION end # Test for percentile @testset "Percentile Calculation" begin values = [1, 2, 3, 4, 5] @test percentile(values, 50) == 3 end # Test for group_transactions @testset "Transaction Grouping" begin transactions = create_mock_transactions(10) grouped = group_transactions(transactions, 2) @test length(grouped) > 0 end # Test for get_transaction_metrics @testset "Transaction Metrics Calculation" begin transactions = create_mock_transactions(10) metrics = get_transaction_metrics(transactions) @test metrics["total_requests"] == 10 @test metrics["avg_latency"] > 0 end # Test for recent_transactions @testset "Recent Transactions Retrieval" begin transactions = recent_transactions(get_history(HISTORY), Minute(15)) @test all(t -> now(UTC) - t.timestamp <= Minute(15) + Second(1), transactions) end # Test for all_endpoint_metrics @testset "All Endpoint Metrics Calculation" begin metrics = all_endpoint_metrics(get_history(HISTORY)) @test metrics isa Dict end # Test for server_metrics @testset "Server Metrics Calculation" begin metrics = server_metrics(get_history(HISTORY)) @test metrics["total_requests"] >= 0 end # Test for error_distribution @testset "Error Distribution Calculation" begin distribution = error_distribution(get_history(HISTORY)) @test typeof(distribution) == Dict{String, Int} end # Test for timeseries and series_format @testset "Timeseries Conversion and Formatting" begin data = Dict(MOCK_TIMESTAMP => 1, MOCK_TIMESTAMP + Minute(1) => 2) ts = timeseries(data) formatted = series_format(ts) @test length(formatted) == 2 end # Test for bin_transactions, requests_per_unit, and avg_latency_per_unit @testset "Transaction Binning and Metrics" begin bin_transactions(get_history(HISTORY), Minute(15)) req_per_unit = requests_per_unit(get_history(HISTORY), Minute(1)) avg_latency = avg_latency_per_unit(get_history(HISTORY), Minute(1)) @test typeof(req_per_unit) == Dict{Dates.DateTime, Int} @test typeof(avg_latency) == Dict{Dates.DateTime, Number} end @testset "Recent Transactions with DateTime Lower Bound" begin clear_history() push_history(HISTORY, HTTPTransaction("192.168.1.1", "/test", DateTime(2023, 1, 1, 12), 0.5, true, 200, nothing)) push_history(HISTORY, HTTPTransaction("192.168.1.2", "/test", DateTime(2023, 1, 1, 13), 0.5, true, 200, nothing)) push_history(HISTORY, HTTPTransaction("192.168.1.3", "/test", DateTime(2023, 1, 1, 14), 0.5, true, 200, nothing)) transactions = recent_transactions(get_history(HISTORY), DateTime(2023, 1, 1, 13)) @test length(transactions) == 1 @test all(t -> t.timestamp >= DateTime(2023, 1, 1, 13), transactions) end @testset "Endpoint Metrics Calculation" begin clear_history() push_history(HISTORY, HTTPTransaction("192.168.1.1", "/test", now(), 0.5, true, 200, nothing)) push_history(HISTORY, HTTPTransaction("192.168.1.2", "/test", now(), 1.0, false, 500, "Error")) metrics = endpoint_metrics(get_history(HISTORY), "/test") @test metrics["total_requests"] == 2 @test metrics["avg_latency"] == 0.75 @test metrics["total_errors"] == 1 end end module A using Kitten; @oxidise @get "/" function() text("server A") end end @testset "metrics collection & calculations" begin try A.serve(host=HOST, port=PORT, async=true, show_banner=false, access_log=nothing) # send a couple requests so we can collect metrics for i in 1:10 @test HTTP.get("$localhost/").status == 200 end r = HTTP.get("$localhost/docs/metrics/data/15/null") @test r.status == 200 data = json(r) @test data["server"]["total_requests"] == 10 @test data["server"]["total_requests"] == 10 @test data["server"]["total_errors"] == 0 finally A.terminate() end end end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
1354
module MiddlewareTests using Test using HTTP using Kitten; @oxidise invocation = [] function handler1(handler) return function(req::HTTP.Request) push!(invocation, 1) handler(req) end end function handler2(handler) return function(req::HTTP.Request) push!(invocation, 2) handler(req) end end function handler3(handler) return function(req::HTTP.Request) push!(invocation, 3) handler(req) end end @get "/multiply/{a}/{b}" function(req, a::Float64, b::Float64) return a * b end r = internalrequest(HTTP.Request("GET", "/multiply/3/6"), middleware=[handler1, handler2, handler3], catch_errors=false) @test r.status == 200 @test invocation == [1,2,3] # enusre the handlers are called in the correct order @test text(r) == "18.0" empty!(invocation) r = internalrequest(HTTP.Request("GET", "/multiply/3/6"), middleware=[handler3, handler1, handler2], catch_errors=false) @test r.status == 200 @test invocation == [3,1,2] # enusre the handlers are called in the correct order @test text(r) == "18.0" empty!(invocation) r = internalrequest(HTTP.Request("GET", "/multiply/3/6"), middleware=[handler3, handler2, handler1], catch_errors=false) @test r.status == 200 @test invocation == [3,2, 1] # enusre the handlers are called in the correct order @test text(r) == "18.0" end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
20248
module OriginalTests using Test using HTTP using JSON3 using StructTypes using Sockets using Dates using Suppressor using Kitten; @oxidise using ..Constants struct Person name::String age::Int end struct Book name::String author::String end configdocs("/docs", "/schema") StructTypes.StructType(::Type{Person}) = StructTypes.Struct() # mount all files inside the content folder under /static #@staticfiles "content" staticfiles("content") # mount files under /dynamic #@dynamicfiles "content" "/dynamic" dynamicfiles("content", "/dynamic") @get "/killserver" function () terminate() end @get "/anonymous" function() return "no args" end @get "/anyparams/{message}" function(req, message::Any) return message end @get "/test" function(req) return "hello world!" end @get "/testredirect" function(req) return redirect("/test") end function errormiddleware(handler) return function(req::HTTP.Request) throw("an random error") handler(req) end end @get router("/middleware-error", middleware=[errormiddleware]) function () return "shouldn't get here" end @get "/customerror" function () function processtring(input::String) "<$input>" end processtring(3) end @get "/data" function () return Dict("message" => "hello world") end @get "/undefinederror" function () asdf end @get "/unsupported-struct" function () return Book("mobdy dick", "blah") end try @get "/mismatched-params/{a}/{b}" function (a,c) return "$a, $c" end catch e @test true end @get "/add/{a}/{b}" function (req, a::Int32, b::Int64) return a + b end @get "/divide/{a}/{b}" function (req, a, b) return parse(Float64, a) / parse(Float64, b) end # path is missing function parameter try @get "/mismatched-params/{a}/{b}" function (req, a,b,c) return "$a, $b, $c" end catch e @test true end # request handler is missing a parameter try @get "/mismatched-params/{a}/{b}" function (req, a) return "$a, $b, $c" end catch e @test true end @get "/file" function(req) return file("content/sample.html") end @get "/multiply/{a}/{b}" function(req, a::Float64, b::Float64) return a * b end @get "/person" function(req) return Person("joe", 20) end @get "/text" function(req) return text(req) end @get "/binary" function(req) return binary(req) end @get "/json" function(req) return json(req) end @get "/person-json" function(req) return json(req, Person) end @get "/html" function(req) return html(""" <!DOCTYPE html> <html> <body> <h1>hello world</h1> </body> </html> """) end @route ["GET"] "/get" function() return "get" end @get "/query" function(req) return queryparams(req) end @post "/post" function(req) return text(req) end @put "/put" function(req) return "put" end @patch "/patch" function(req) return "patch" end @delete "/delete" function(req) return "delete" end @enum Fruit apple=1 orange=2 kiwi=3 struct Student name :: String age :: Int8 end StructTypes.StructType(::Type{Student}) = StructTypes.Struct() StructTypes.StructType(::Type{Complex{Float64}}) = StructTypes.Struct() @get "/fruit/{fruit}" function(req, fruit::Fruit) return fruit end @get "/date/{date}" function(req, date::Date) return date end @get "/datetime/{datetime}" function(req, datetime::DateTime) return datetime end @get "/complex/{complex}" function(req, complex::Complex{Float64}) return complex end @get "/list/{list}" function(req, list::Vector{Float32}) return list end @get "/dict/{dict}" function(req, dict::Dict{String, Any}) return dict end @get "/tuple/{tuple}" function(req, tuple::Tuple{String, String}) return tuple end @get "/union/{value}" function(req, value::Union{Bool, String}) return value end @get "/boolean/{bool}" function(req, bool::Bool) return bool end @get "/struct/{student}" function(req, student::Student) return student end @get "/float/{float}" function (req, float::Float32) return float end routerdict = Dict("value" => 0) repeat = router("/repeat", interval = 0.5, tags=["repeat"]) @get "/getroutervalue" function(req) return routerdict["value"] end @get repeat("/increment", tags=["increment"]) function(req) routerdict["value"] += 1 return routerdict["value"] end function middleware1(handler) return function(req::HTTP.Request) handler(req) end end function middleware2(handler) return function(req::HTTP.Request) handler(req) end end function middleware3(handler) return function(req::HTTP.Request) handler(req) end end function middleware4(handler) return function(req::HTTP.Request) handler(req) end end # case 1: no middleware setup, uses the global middleware by default @get "/math/add/{a}/{b}" function (req::HTTP.Request, a::Float64, b::Float64) return a + b end # case 1: no middleware is defined at any level -> use global middleware @get router("/math/power/{a}/{b}") function (req::HTTP.Request, a::Float64, b::Float64) return a ^ b end math = router("/math", middleware=[middleware3]) # case 2: middleware is cleared at route level so don't register any middleware @get math("/cube/{a}", middleware=[]) function(req, a::Float64) return a * a * a end # case 3: router-level is empty & route-level is defined other = router("/math", middleware=[]) @get other("/multiply/{a}/{b}", middleware=[middleware3]) function (req::HTTP.Request, a::Float64, b::Float64) return a * b end # case 4 (both defined) @get math("/divide/{a}/{b}", middleware=[middleware4]) function(req::HTTP.Request, a::Float64, b::Float64) return a / b end # case 5: only router level is defined @get math("/subtract/{a}/{b}") function(req::HTTP.Request, a::Float64, b::Float64) return a - b end # case 6: only route level middleware is defined empty = router() @get empty("/math/square/{a}", middleware=[middleware3]) function(req, a::Float64) return a * a end emptyrouter = router() @get router("emptyrouter") function(req) return "emptyrouter" end emptysubpath = router("/emptysubpath", tags=["empty"]) @get emptysubpath("", middleware=[middleware1]) function(req) return "emptysubpath" end # added another request hanlder for post requests on the same route @post emptysubpath("") function(req) return "emptysubpath - post" end serve(async=true, port=PORT, show_errors=false, show_banner=true) # query metrics endpoints r = internalrequest(HTTP.Request("GET", "/docs/metrics/data/15/null"), metrics=true) @test r.status == 200 r = internalrequest(HTTP.Request("GET", "/anonymous")) @test r.status == 200 @test text(r) == "no args" r = internalrequest(HTTP.Request("GET", "/fake-endpoint")) @test r.status == 404 r = internalrequest(HTTP.Request("GET", "/test")) @test r.status == 200 @test text(r) == "hello world!" r = internalrequest(HTTP.Request("GET", "/testredirect")) @test r.status == 307 @test Dict(r.headers)["Location"] == "/test" r = internalrequest(HTTP.Request("GET", "/multiply/5/8")) @test r.status == 200 @test text(r) == "40.0" r = internalrequest(HTTP.Request("GET", "/person")) @test r.status == 200 @test json(r, Person) == Person("joe", 20) r = internalrequest(HTTP.Request("GET", "/html")) @test r.status == 200 @test Dict(r.headers)["Content-Type"] == "text/html; charset=utf-8" # path param tests # boolean r = internalrequest(HTTP.Request("GET", "/boolean/true")) @test r.status == 200 r = internalrequest(HTTP.Request("GET", "/boolean/false")) @test r.status == 200 @suppress global r = internalrequest(HTTP.Request("GET", "/boolean/asdf")) @test r.status == 500 # Test parsing of Any type inside a request handler r = internalrequest(HTTP.Request("GET", "/anyparams/hello")) @test r.status == 200 @test text(r) == "hello" # # enums r = internalrequest(HTTP.Request("GET", "/fruit/1")) @test r.status == 200 @suppress global r = internalrequest(HTTP.Request("GET", "/fruit/4")) @test r.status == 500 @suppress global r = internalrequest(HTTP.Request("GET", "/fruit/-3")) @test r.status == 500 # date r = internalrequest(HTTP.Request("GET", "/date/2022")) @test r.status == 200 r = internalrequest(HTTP.Request("GET", "/date/2022-01-01")) @test r.status == 200 @suppress global r = internalrequest(HTTP.Request("GET", "/date/-3")) @test r.status == 500 # # datetime r = internalrequest(HTTP.Request("GET", "/datetime/2022-01-01")) @test r.status == 200 @suppress global r = internalrequest(HTTP.Request("GET", "/datetime/2022")) @test r.status == 500 @suppress global r = internalrequest(HTTP.Request("GET", "/datetime/-3")) @test r.status == 500 # complex r = internalrequest(HTTP.Request("GET", "/complex/3.2e-1")) @test r.status == 200 # list r = internalrequest(HTTP.Request("GET", "/list/[1,2,3]")) @test r.status == 200 r = internalrequest(HTTP.Request("GET", "/list/[]")) @test r.status == 200 # dictionary r = internalrequest(HTTP.Request("GET", """/dict/{"msg": "hello world"}""")) @test r.status == 200 @test json(r)["msg"] == "hello world" r = internalrequest(HTTP.Request("GET", "/dict/{}")) @test r.status == 200 # tuple r = internalrequest(HTTP.Request("GET", """/tuple/["a","b"]""")) @test r.status == 200 @test text(r) == """["a","b"]""" r = internalrequest(HTTP.Request("GET", """/tuple/["a","b","c"]""")) @test r.status == 200 @test text(r) == """["a","b"]""" # union r = internalrequest(HTTP.Request("GET", "/union/true")) @test r.status == 200 @test Dict(r.headers)["Content-Type"] == "text/plain; charset=utf-8" r = internalrequest(HTTP.Request("GET", "/union/false")) @test r.status == 200 @test Dict(r.headers)["Content-Type"] == "text/plain; charset=utf-8" r = internalrequest(HTTP.Request("GET", "/union/asdfasd")) @test r.status == 200 @test Dict(r.headers)["Content-Type"] == "text/plain; charset=utf-8" # struct r = internalrequest(HTTP.Request("GET", """/struct/{"name": "jim", "age": 20}""")) @test r.status == 200 @test json(r, Student) == Student("jim", 20) @suppress global r = internalrequest(HTTP.Request("GET", """/struct/{"aged": 20}""")) @test r.status == 500 @suppress global r = internalrequest(HTTP.Request("GET", """/struct/{"aged": 20}""")) @test r.status == 500 # float r = internalrequest(HTTP.Request("GET", "/float/3.5")) @test r.status == 200 r = internalrequest(HTTP.Request("GET", "/float/3")) @test r.status == 200 # GET, PUT, POST, PATCH, DELETE, route macro tests r = internalrequest(HTTP.Request("GET", "/get")) @test r.status == 200 @test text(r) == "get" r = internalrequest(HTTP.Request("POST", "/post", [], "this is some data")) @test r.status == 200 @test text(r) == "this is some data" r = internalrequest(HTTP.Request("PUT", "/put")) @test r.status == 200 @test text(r) == "put" r = internalrequest(HTTP.Request("PATCH", "/patch")) @test r.status == 200 @test text(r) == "patch" # # Query params tests r = internalrequest(HTTP.Request("GET", "/query?message=hello")) @test r.status == 200 @test json(r)["message"] == "hello" r = internalrequest(HTTP.Request("GET", "/query?message=hello&value=5")) data = json(r) @test r.status == 200 @test data["message"] == "hello" @test data["value"] == "5" # Get mounted static files r = internalrequest(HTTP.Request("GET", "/static/test.txt")) body = text(r) @test r.status == 200 @test Dict(r.headers)["Content-Type"] == "text/plain; charset=utf-8" @test body == file("content/test.txt") |> text @test body == "this is a sample text file" r = internalrequest(HTTP.Request("GET", "/static/sample.html")) @test r.status == 200 @test Dict(r.headers)["Content-Type"] == "text/html; charset=utf-8" @test text(r) == file("content/sample.html") |> text r = internalrequest(HTTP.Request("GET", "/static/index.html")) @test r.status == 200 @test Dict(r.headers)["Content-Type"] == "text/html; charset=utf-8" @test text(r) == file("content/index.html") |> text r = internalrequest(HTTP.Request("GET", "/static/")) @test r.status == 200 @test Dict(r.headers)["Content-Type"] == "text/html; charset=utf-8" @test text(r) == file("content/index.html") |> text # # Body transformation tests r = internalrequest(HTTP.Request("GET", "/text", [], "hello there!")) @test r.status == 200 @test text(r) == "hello there!" r = internalrequest(HTTP.Request("GET", "/binary", [], "hello there!")) @test r.status == 200 @test String(r.body) == "[104,101,108,108,111,32,116,104,101,114,101,33]" r = internalrequest(HTTP.Request("GET", "/json", [], "{\"message\": \"hi\"}")) @test r.status == 200 @test json(r)["message"] == "hi" r = internalrequest(HTTP.Request("GET", "/person")) person = json(r, Person) @test r.status == 200 @test person.name == "joe" @test person.age == 20 r = internalrequest(HTTP.Request("GET", "/person-json", [], "{\"name\":\"jim\",\"age\":25}")) person = json(r, Person) @test r.status == 200 @test person.name == "jim" @test person.age == 25 r = internalrequest(HTTP.Request("GET", "/file")) @test r.status == 200 @test text(r) == file("content/sample.html") |> text r = internalrequest(HTTP.Request("GET", "/dynamic/sample.html")) @test r.status == 200 @test text(r) == file("content/sample.html") |> text r = internalrequest(HTTP.Request("GET", "/static/sample.html")) @test r.status == 200 @test text(r) == file("content/sample.html") |> text @suppress global r = internalrequest(HTTP.Request("GET", "/multiply/a/8")) @test r.status == 500 # don't suppress error reporting for this test @suppress global r = internalrequest(HTTP.Request("GET", "/multiply/a/8")) @test r.status == 500 # hit endpoint that doesn't exist @suppress global r = internalrequest(HTTP.Request("GET", "asdfasdf")) @test r.status == 404 @suppress global r = internalrequest(HTTP.Request("GET", "asdfasdf")) @test r.status == 404 @suppress global r = internalrequest(HTTP.Request("GET", "/somefakeendpoint")) @test r.status == 404 @suppress global r = internalrequest(HTTP.Request("GET", "/customerror")) @test r.status == 500 # NOTE: previosly metrics were enabled by default and it was were the errors were handled previously # This is due to fact that the `custom_middleware` is before `serializer` middleware. This may be # an intended behaviour to seperate error handling of the router and that of the `custom_middleware`. # A fix would be seperating error handling middleware from serializer and put it before `custom_middleware`. @suppress global r = internalrequest(HTTP.Request("GET", "/middleware-error"), metrics=true) @test r.status == 500 @suppress global r = internalrequest(HTTP.Request("GET", "/undefinederror")) @test r.status == 500 try # apparently you don't need to have StructTypes setup on a custom type with the latest JSON3 library r = internalrequest(HTTP.Request("GET", "/unsupported-struct")) catch e @test e isa ArgumentError end ## docs related tests # should be set to true by default @test isdocsenabled() == true @test_throws "" disabledocs() #@test isdocsenabled() == false enabledocs() @test isdocsenabled() == true terminate() #enabledocs() @async serve(docs=true, port=PORT, show_errors=false, show_banner=false) sleep(5) # ## Router related tests # case 1 r = internalrequest(HTTP.Request("GET", "/math/add/6/5")) @test r.status == 200 @test text(r) == "11.0" # case 1 r = internalrequest(HTTP.Request("GET", "/math/power/6/5")) @test r.status == 200 @test text(r) == "7776.0" # case 2 r = internalrequest(HTTP.Request("GET", "/math/cube/3")) @test r.status == 200 @test text(r) == "27.0" # case 3 r = internalrequest(HTTP.Request("GET", "/math/multiply/3/5")) @test r.status == 200 @test text(r) == "15.0" # case 4 r = internalrequest(HTTP.Request("GET", "/math/divide/3/5")) @test r.status == 200 @test text(r) == "0.6" # case 5 r = internalrequest(HTTP.Request("GET", "/math/subtract/3/5")) @test r.status == 200 @test text(r) == "-2.0" # case 6 r = internalrequest(HTTP.Request("GET", "/math/square/3")) @test r.status == 200 @test text(r) == "9.0" r = internalrequest(HTTP.Request("GET", "/getroutervalue")) @test r.status == 200 @test parse(Int64, text(r)) > 0 r = internalrequest(HTTP.Request("GET", "/emptyrouter")) @test r.status == 200 @test text(r) == "emptyrouter" r = internalrequest(HTTP.Request("GET", "/emptysubpath")) @test r.status == 200 @test text(r) == "emptysubpath" r = internalrequest(HTTP.Request("POST", "/emptysubpath")) @test r.status == 200 @test text(r) == "emptysubpath - post" # kill any background tasks still running stoptasks() ## internal docs and metrics tests r = internalrequest(HTTP.Request("GET", "/get")) @test r.status == 200 r = internalrequest(HTTP.Request("GET", "/docs")) @test r.status == 200 r = internalrequest(HTTP.Request("GET", "/docs/swagger")) @test r.status == 200 r = internalrequest(HTTP.Request("GET", "/docs/redoc")) @test r.status == 200 r = internalrequest(HTTP.Request("GET", "/docs/schema")) @test r.status == 200 r = internalrequest(HTTP.Request("GET", "/docs/metrics"), metrics=true) @test r.status == 200 r = internalrequest(HTTP.Request("GET", "/docs/metrics/data/15/null"), metrics=true) @test r.status == 200 r = internalrequest(HTTP.Request("GET", "/docs"), middleware=[middleware1]) @test r.status == 200 r = internalrequest(HTTP.Request("GET", "/docs/schema")) @test r.status == 200 @test Dict(r.headers)["Content-Type"] == "application/json; charset=utf-8" # test emtpy dict (which should be skipped) mergeschema(Dict( "paths" => Dict( "/multiply/{a}/{b}" => Dict( "get" => Dict( "description" => "returns the result of a * b", "parameters" => [ Dict() ] ) ) ) )) mergeschema(Dict( "paths" => Dict( "/multiply/{a}/{b}" => Dict( "get" => Dict( "description" => "returns the result of a * b", "parameters" => [ Dict( "name" => "a", "in" => "path", "required" => true, "schema" => Dict( "type" => "number" ) ), Dict( "name" => "b", "in" => "path", "required" => true, "schema" => Dict( "type" => "number" ) ) ] ) ) ) )) @assert getschema()["paths"]["/multiply/{a}/{b}"]["get"]["description"] == "returns the result of a * b" mergeschema("/put", Dict( "put" => Dict( "description" => "returns a string on PUT", "parameters" => [] ) ) ) @assert getschema()["paths"]["/put"]["put"]["description"] == "returns a string on PUT" data = Dict("msg" => "this is not a valid schema dictionary") setschema(data) @assert getschema() == data terminate() @async serve(middleware=[middleware1, middleware2, middleware3], port=PORT, show_errors=false, show_banner=false) sleep(1) r = internalrequest(HTTP.Request("GET", "/get")) @test r.status == 200 # redundant terminate() calls should have no affect terminate() terminate() terminate() function errorcatcher(handle) function(req) try response = handle(req) return response catch e return HTTP.Response(500, "here's a custom error response") end end end # Test default handler by turning off serializaiton @async serve(serialize=false, middleware=[error_catcher], catch_errors=false, show_banner=false) sleep(3) r = internalrequest(HTTP.Request("GET", "/get"), catch_errors=false) @test r.status == 200 try # test the error handler inside the default handler r = HTTP.get("$localhost/undefinederror"; readtimeout=1) catch e @test true end try # service should not have started and get requests should throw some error r = HTTP.get("$localhost/data"; readtimeout=1) catch e @test true finally terminate() end terminate() resetstate() clearcronjobs() cleartasks() end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
342
module OxidiseTest using Test using HTTP using ..Constants using Kitten; @oxidise @get "/test" function(req) return "Hello World" end serve(port=PORT, host=HOST, async=true, show_errors=false, show_banner=false) r = internalrequest(HTTP.Request("GET", "/test")) @test r.status == 200 @test text(r) == "Hello World" terminate() end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
2149
module ParallelTests using Test using HTTP using Suppressor using Kitten; @oxidise using ..Constants @testset "parallel tests" begin invocation = [] function handler1(handler) return function(req::HTTP.Request) push!(invocation, 1) handler(req) end end function handler2(handler) return function(req::HTTP.Request) push!(invocation, 2) handler(req) end end function handler3(handler) return function(req::HTTP.Request) push!(invocation, 3) handler(req) end end get("/get") do return "Hello World" end post("/post") do req::Request return text(req) end @get("/customerror") do function processtring(input::String) "<$input>" end processtring(3) end if Threads.nthreads() <= 1 # the service should work even when we only have a single thread available (not ideal) @async serveparallel(port=PORT, show_errors=false, show_banner=false, queuesize=100) r = HTTP.get("$localhost/get") @test r.status == 200 # clean up the server on tests without additional threads terminate() end # only run these tests if we have more than one thread to work with if Threads.nthreads() > 1 serveparallel(host=HOST, port=PORT, show_errors=true, async=true, show_banner=true) sleep(3) r = HTTP.get("$localhost/get") @test r.status == 200 r = HTTP.post("$localhost/post", body="some demo content") @test text(r) == "some demo content" try @suppress_err r = HTTP.get("$localhost/customerror", connect_timeout=3) catch e @test e isa MethodError || e isa HTTP.ExceptionRequest.StatusError end terminate() serveparallel(host=HOST, port=PORT, middleware=[handler1, handler2, handler3], show_errors=true, async=true, show_banner=false) sleep(1) r = HTTP.get("$localhost/get") @test r.status == 200 terminate() end end end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
998
module PrecompilationTests using Test using HTTP using Kitten: text using ..Constants # Load in the custom pacakge & trigger any precompilation push!(LOAD_PATH, "./TestPackage") using TestPackage # call the start function from the TestPackage start(;async=true, host=HOST, port=PORT, show_banner=false, access_log=nothing) @testset "TestPackage" begin r = HTTP.get("$localhost") @test r.status == 200 @test text(r) == "hello world" r = HTTP.get("$localhost/add?a=5&b=10") @test r.status == 200 @test text(r) == "15" # test default value which should be 3 r = HTTP.get("$localhost/add?a=3") @test r.status == 200 @test text(r) == "6" r = HTTP.get("$localhost/add/extractor?a=5&b=10") @test r.status == 200 @test text(r) == "15" # test default value which should be 3 r = HTTP.get("$localhost/add/extractor?a=3") @test r.status == 200 @test text(r) == "6" end # Call the stop() function from the TestPackage stop() end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
8342
module ReflectionTests using Test using Base: @kwdef using Kitten: splitdef, Json using Kitten.Core.Reflection: getsignames, parsetype, kwarg_struct_builder global message = Dict("message" => "Hello, World!") struct Person name::String age::Int end @kwdef struct Home address::String owner::Person end function getinfo(f::Function) return splitdef(f) end @testset "getsignames tests" begin function test_func(a::Int, b::Float64; c="default", d=true, request) return a, b, c, d end args, arg_types, kwarg_names = getsignames(test_func) @test args == [:a, :b] @test arg_types == [Int, Float64] @test kwarg_names == [:c, :d, :request] end @testset "parsetype tests" begin parsetype(Int, 3) == 3 parsetype(Int, "3") == 3 parsetype(Float64, "3") == 3.0 parsetype(Float64, 3) == 3.0 end @testset "JSON Nested extract" begin converted = kwarg_struct_builder(Home, Dict( :address => "123 main street", :owner => Dict( :name => "joe", :age => 25 ) )) @test converted == Home("123 main street", Person("joe", 25)) end @testset "splitdef tests" begin # Define a function for testing function test_func(a::Int, b::Float64; c="default", d=true, request) return a, b, c, d end # Parse the function info info = splitdef(test_func) @testset "Function name" begin @test info.name == :test_func end @testset "counts" begin @test length(info.args) == 2 @test length(info.kwargs) == 3 @test length(info.sig) == 5 end @testset "Args" begin @test info.args[1].name == :a @test info.args[1].type == Int @test info.args[2].name == :b @test info.args[2].type == Float64 end @testset "Kwargs" begin @test length(info.kwargs) == 3 @test info.kwargs[1].name == :c @test info.kwargs[1].type == Any @test info.kwargs[1].default == "default" @test info.kwargs[1].hasdefault == true @test info.kwargs[2].name == :d @test info.kwargs[2].type == Any @test info.kwargs[2].default == true @test info.kwargs[2].hasdefault == true @test info.kwargs[3].name == :request @test info.kwargs[3].type == Any @test info.kwargs[3].default isa Missing @test info.kwargs[3].hasdefault == false end @testset "Sig_map" begin @test length(info.sig_map) == 5 @test info.sig_map[:a].name == :a @test info.sig_map[:a].type == Int @test info.sig_map[:b].name == :b @test info.sig_map[:b].type == Float64 @test info.sig_map[:c].name == :c @test info.sig_map[:c].type == Any @test info.sig_map[:c].default == "default" @test info.sig_map[:c].hasdefault == true @test info.sig_map[:d].name == :d @test info.sig_map[:d].type == Any @test info.sig_map[:d].default == true @test info.sig_map[:d].hasdefault == true @test info.sig_map[:request].name == :request @test info.sig_map[:request].type == Any @test info.sig_map[:request].default isa Missing @test info.sig_map[:request].hasdefault == false end end @testset "splitdef anonymous function tests" begin # Define a function for testing # Parse the function info info = getinfo(function(a::Int, b::Float64; c="default", d=true, request) return a, b, c, d end ) @testset "counts" begin @test length(info.args) == 2 @test length(info.kwargs) == 3 @test length(info.sig) == 5 end @testset "Args" begin @test info.args[1].name == :a @test info.args[1].type == Int @test info.args[2].name == :b @test info.args[2].type == Float64 end @testset "Kwargs" begin @test length(info.kwargs) == 3 @test info.kwargs[1].name == :c @test info.kwargs[1].type == Any @test info.kwargs[1].default == "default" @test info.kwargs[1].hasdefault == true @test info.kwargs[2].name == :d @test info.kwargs[2].type == Any @test info.kwargs[2].default == true @test info.kwargs[2].hasdefault == true @test info.kwargs[3].name == :request @test info.kwargs[3].type == Any @test info.kwargs[3].default isa Missing @test info.kwargs[3].hasdefault == false end @testset "Sig_map" begin @test length(info.sig_map) == 5 @test info.sig_map[:a].name == :a @test info.sig_map[:a].type == Int @test info.sig_map[:b].name == :b @test info.sig_map[:b].type == Float64 @test info.sig_map[:c].name == :c @test info.sig_map[:c].type == Any @test info.sig_map[:c].default == "default" @test info.sig_map[:c].hasdefault == true @test info.sig_map[:d].name == :d @test info.sig_map[:d].type == Any @test info.sig_map[:d].default == true @test info.sig_map[:d].hasdefault == true @test info.sig_map[:request].name == :request @test info.sig_map[:request].type == Any @test info.sig_map[:request].default isa Missing @test info.sig_map[:request].hasdefault == false end end @testset "splitdef do..end syntax" begin # Parse the function info info = splitdef() do a::Int, b::Float64 return a, b end @testset "counts" begin @test length(info.args) == 2 @test length(info.sig) == 2 end @testset "Args" begin @test info.args[1].name == :a @test info.args[1].type == Int @test info.args[2].name == :b @test info.args[2].type == Float64 end @testset "Sig_map" begin @test length(info.sig_map) == 2 @test info.sig_map[:a].name == :a @test info.sig_map[:a].type == Int @test info.sig_map[:b].name == :b @test info.sig_map[:b].type == Float64 end end @testset "splitdef extractor default value" begin # Define a function for testing f = function(a::Int, house = Json{Home}(house -> house.owner.age >= 25), msg = message; request, b = 3.0) return a, house, msg end # Parse the function info info = splitdef(f) @testset "counts" begin @test length(info.args) == 3 @test length(info.kwargs) == 2 @test length(info.sig) == 5 @test length(info.sig_map) == 5 end @testset "Args" begin @test info.args[1].name == :a @test info.args[1].type == Int @test info.args[2].name == :house @test info.args[2].type == Json{Home} @test info.args[2].default isa Json{Home} @test info.args[3].name == :msg @test info.args[3].type == Dict{String, String} end @testset "Kwargs" begin @test info.kwargs[1].name == :request @test info.kwargs[1].type == Any @test info.kwargs[1].default isa Missing @test info.kwargs[1].hasdefault == false @test info.kwargs[2].name == :b @test info.kwargs[2].type == Any @test info.kwargs[2].default == 3.0 @test info.kwargs[2].hasdefault == true end @testset "Sig_map" begin @test info.sig_map[:a].name == :a @test info.sig_map[:a].type == Int @test info.sig_map[:a].default isa Missing @test info.sig_map[:a].hasdefault == false @test info.sig_map[:house].name == :house @test info.sig_map[:house].type == Json{Home} @test info.sig_map[:house].default isa Json{Home} @test info.sig_map[:house].hasdefault == true @test info.sig_map[:msg].name == :msg @test info.sig_map[:msg].type == Dict{String, String} @test info.sig_map[:msg].default == Dict("message" => "Hello, World!") @test info.sig_map[:msg].hasdefault == true @test info.sig_map[:request].name == :request @test info.sig_map[:request].type == Any @test info.sig_map[:request].default isa Missing @test info.sig_map[:request].hasdefault == false @test info.sig_map[:b].name == :b @test info.sig_map[:b].type == Any @test info.sig_map[:b].default == 3.0 @test info.sig_map[:b].hasdefault == true end end end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
3712
module BodyParserTests using Test using HTTP using Kitten @testset "Render Module Tests" begin @testset "html function" begin response = html("<h1>Hello, World!</h1>") @test response.status == 200 @test text(response) == "<h1>Hello, World!</h1>" @test Dict(response.headers)["Content-Type"] == "text/html; charset=utf-8" end @testset "text function" begin response = text("Hello, World!") @test response.status == 200 @test text(response) == "Hello, World!" @test Dict(response.headers)["Content-Type"] == "text/plain; charset=utf-8" end @testset "json function" begin response = json(Dict("message" => "Hello, World!")) @test response.status == 200 @test text(response) == "{\"message\":\"Hello, World!\"}" @test Dict(response.headers)["Content-Type"] == "application/json; charset=utf-8" end @testset "json binary function" begin response = json(Vector{UInt8}("{\"message\":\"Hello, World!\"}")) @test response.status == 200 @test text(response) == "{\"message\":\"Hello, World!\"}" @test Dict(response.headers)["Content-Type"] == "application/json; charset=utf-8" end @testset "xml function" begin response = xml("<message>Hello, World!</message>") @test response.status == 200 @test text(response) == "<message>Hello, World!</message>" @test Dict(response.headers)["Content-Type"] == "application/xml; charset=utf-8" end @testset "js function" begin response = js("console.log('Hello, World!');") @test response.status == 200 @test text(response) == "console.log('Hello, World!');" @test Dict(response.headers)["Content-Type"] == "application/javascript; charset=utf-8" end @testset "css function" begin response = css("body { background-color: #f0f0f0; }") @test response.status == 200 @test text(response) == "body { background-color: #f0f0f0; }" @test Dict(response.headers)["Content-Type"] == "text/css; charset=utf-8" end @testset "binary function" begin response = binary(UInt8[72, 101, 108, 108, 111]) # "Hello" in ASCII @test response.status == 200 @test response.body == UInt8[72, 101, 108, 108, 111] @test Dict(response.headers)["Content-Type"] == "application/octet-stream" end end @testset "Repeated calls do not duplicate headers" begin response1 = css("body { background-color: #f0f0f0; }") response2 = css("body { background-color: #f0f0f0; }") @test Dict(response1.headers)["Content-Type"] == "text/css; charset=utf-8" @test Dict(response2.headers)["Content-Type"] == "text/css; charset=utf-8" @test length(response1.headers) == length(response2.headers) response1 = binary(UInt8[72, 101, 108, 108, 111]) # "Hello" in ASCII response2 = binary(UInt8[72, 101, 108, 108, 111]) # "Hello" in ASCII @test Dict(response1.headers)["Content-Type"] == "application/octet-stream" @test Dict(response2.headers)["Content-Type"] == "application/octet-stream" @test length(response1.headers) == length(response2.headers) == 2 end @testset "Repeated calls do not duplicate headers for file renderer" begin response1 = file("content/index.html") response2 = file("content/index.html") @test findfirst(x -> x == ("Content-Type" => "text/html; charset=utf-8"), response1.headers) !== nothing @test findfirst(x -> x == ("Content-Type" => "text/html; charset=utf-8"), response2.headers) !== nothing count1 = length(response1.headers) count2 = length(response2.headers) @test count1 == count2 == 2 end end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
3146
module RoutingFunctionsTests using Test using HTTP using JSON3 using StructTypes using Sockets using Dates using Kitten ##### Setup Routes ##### inline = router("/inline") get(inline("/add/{x}/{y}")) do request::HTTP.Request, x::Int, y::Int x + y end get("/add/{x}/{y}") do request::HTTP.Request, x::Int, y::Int x + y end post(inline("/sub/{x}/{y}")) do request::HTTP.Request, x::Int, y::Int x - y end post("/sub/{x}/{y}") do request::HTTP.Request, x::Int, y::Int x - y end put(inline("/power/{x}/{y}")) do request::HTTP.Request, x::Int, y::Int x ^ y end put("/power/{x}/{y}") do request::HTTP.Request, x::Int, y::Int x ^ y end patch(inline("/mulitply/{x}/{y}")) do request::HTTP.Request, x::Int, y::Int x * y end patch("/mulitply/{x}/{y}") do request::HTTP.Request, x::Int, y::Int x * y end delete(inline("/divide/{x}/{y}")) do request::HTTP.Request, x::Int, y::Int x / y end delete("/divide/{x}/{y}") do request::HTTP.Request, x::Int, y::Int x / y end route(["GET"], inline("/route/add/{x}/{y}")) do request::HTTP.Request, x::Int, y::Int x + y end route(["GET"], "/route/add/{x}/{y}") do request::HTTP.Request, x::Int, y::Int x + y end ##### Begin tests ##### @testset "Routing Function Tests" begin @testset "GET routing functions" begin r = internalrequest(HTTP.Request("GET", "/inline/add/5/4")) @test r.status == 200 @test text(r) == "9" r = internalrequest(HTTP.Request("GET", "/add/5/4")) @test r.status == 200 @test text(r) == "9" r = internalrequest(HTTP.Request("GET", "/inline/route/add/5/4")) @test r.status == 200 @test text(r) == "9" r = internalrequest(HTTP.Request("GET", "/route/add/5/4")) @test r.status == 200 @test text(r) == "9" end @testset "POST routing functions" begin r = internalrequest(HTTP.Request("POST", "/inline/sub/5/4")) @test r.status == 200 @test text(r) == "1" r = internalrequest(HTTP.Request("POST", "/sub/5/4")) @test r.status == 200 @test text(r) == "1" end @testset "PUT routing functions" begin r = internalrequest(HTTP.Request("PUT", "/inline/power/5/4")) @test r.status == 200 @test text(r) == "625" r = internalrequest(HTTP.Request("PUT", "/power/5/4")) @test r.status == 200 @test text(r) == "625" end @testset "PATCH routing functions" begin r = internalrequest(HTTP.Request("PATCH", "/inline/mulitply/5/4")) @test r.status == 200 @test text(r) == "20" r = internalrequest(HTTP.Request("PATCH", "/mulitply/5/4")) @test r.status == 200 @test text(r) == "20" end @testset "DELETE routing functions" begin r = internalrequest(HTTP.Request("DELETE", "/inline/divide/5/4")) @test r.status == 200 @test text(r) == "1.25" r = internalrequest(HTTP.Request("DELETE", "/divide/5/4")) @test r.status == 200 @test text(r) == "1.25" end # clear any routes setup in this file resetstate() end end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
913
module RunTests include("constants.jl"); using .Constants #### Extension Tests #### include("extensions/templatingtests.jl") include("extensions/protobuf/protobuftests.jl") include("extensions/cairomakietests.jl") include("extensions/wglmakietests.jl") include("extensions/bonitotests.jl") #### Sepcial Handler Tests #### include("ssetests.jl") # Causing issues include("websockettests.jl") include("streamingtests.jl") include("handlertests.jl") # #### Core Tests #### include("precompilationtest.jl") include("extractortests.jl") include("reflectiontests.jl") include("metricstests.jl") include("routingfunctionstests.jl") include("rendertests.jl") include("bodyparsertests.jl") include("crontests.jl") include("oxidise.jl") include("instancetests.jl") include("paralleltests.jl") include("taskmanagement.jl") include("cronmanagement.jl") include("middlewaretests.jl") include("originaltests.jl") end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
2422
module SSETests using Test using Dates using HTTP using ..Constants using Kitten; @oxidise @get "/health" function() return text("I'm alive") end stream("/events/{name}") do stream::HTTP.Stream, name::String HTTP.setheader(stream, "Access-Control-Allow-Origin" => "*") HTTP.setheader(stream, "Access-Control-Allow-Methods" => "GET") HTTP.setheader(stream, "Content-Type" => "text/event-stream") HTTP.setheader(stream, "Cache-Control" => "no-cache") startwrite(stream) message = "Hello, $name" for _ in 1:5 write(stream, format_sse_message(message)) sleep(0.1) end closewrite(stream) return nothing end serve(port=PORT, host=HOST, async=true, show_errors=false, show_banner=false, access_log=nothing) @testset "Stream Function tests" begin HTTP.open("GET", "$localhost/events/john", headers=Dict("Connection" => "close")) do io while !eof(io) message = String(readavailable(io)) if !isempty(message) && message != "null" @test message == "data: Hello, john\n\n" end end end HTTP.open("GET", "$localhost/events/matt", headers=Dict("Connection" => "close")) do io while !eof(io) message = String(readavailable(io)) if !isempty(message) && message != "null" @test message == "data: Hello, matt\n\n" end end end end terminate() println() @testset "format_sse_message tests" begin @testset "basic functionality" begin @test format_sse_message("Hello") == "data: Hello\n\n" @test format_sse_message("Hello\nWorld") == "data: Hello\ndata: World\n\n" end @testset "optional parameters" begin @test format_sse_message("Hello", event="greeting") == "data: Hello\nevent: greeting\n\n" @test format_sse_message("Hello", id="1") == "data: Hello\nid: 1\n\n" @test format_sse_message("Hello", retry=1000) == "data: Hello\nretry: 1000\n\n" end @testset "newline in event or id" begin @test_throws ArgumentError format_sse_message("Hello", event="greeting\n") @test_throws ArgumentError format_sse_message("Hello", id="1\n") end @testset "retry is not positive" begin @test_throws ArgumentError format_sse_message("Hello", retry=0) @test_throws ArgumentError format_sse_message("Hello", retry=-1) end end end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
2005
module StreamingTests using Test using HTTP using ..Constants using Kitten; @oxidise function explicit_stream(stream::HTTP.Stream) # Set headers HTTP.setheader(stream, "Content-Type" => "text/plain") HTTP.setheader(stream, "Transfer-Encoding" => "chunked") # Start writing (if you need to send headers before the body) startwrite(stream) data = ["a", "b", "c"] for chunk in data write(stream, chunk) end # Close the stream to end the HTTP response properly closewrite(stream) end function implicit_stream(stream) explicit_stream(stream) end srouter = router("/stream") @stream "/api/chunked/text" implicit_stream stream(implicit_stream, srouter("/api/func/chunked/text")) @post "/api/post/chunked/text" explicit_stream @get "/api/error" implicit_stream serve(port=PORT, host=HOST, async=true, show_errors=false, show_banner=false, access_log=nothing) @testset "StreamingChunksDemo Tests" begin @testset "macro stream handler" begin response = HTTP.get("$localhost/api/chunked/text", headers=Dict("Connection" => "close")) @test response.status == 200 @test text(response) == "abc" end @testset "function stream handler" begin response = HTTP.get("$localhost/stream/api/func/chunked/text", headers=Dict("Connection" => "close")) @test response.status == 200 @test text(response) == "abc" end @testset "/api/post/chunked/text" begin response = HTTP.post("$localhost/api/post/chunked/text", headers=Dict("Connection" => "close")) @test response.status == 200 @test text(response) == "abc" end @testset "Can't setup implicit stream handler on regular routing macros & functions " begin try response = HTTP.get("$localhost/api/error", headers=Dict("Connection" => "close")) @test false catch e @test e isa HTTP.Exceptions.StatusError end end end terminate() println() end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
607
module TaskManagementTests using Test using Kitten; @oxidise const iterations = Ref{Int}(0) get(router("/one", interval=1)) do iterations[] += 1 end get(router("/three", interval=3)) do iterations[] += 1 end @repeat 3.4 function() iterations[] += 1 end @repeat 4 "every 4 seconds" function() iterations[] += 1 end starttasks() starttasks() # all active tasks should be filtered out and not started again # register a new task after the others have already began @repeat 5 function() iterations[] += 1 end starttasks() while iterations[] < 15 sleep(1) end terminate() end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
2365
module WebSocketTests using Test using HTTP using HTTP.WebSockets using ..Constants using Kitten; @oxidise websocket("/ws") do ws::HTTP.WebSocket try for msg in ws send(ws, "Received message: $msg") end catch e if !isa(e, HTTP.WebSockets.WebSocketError) rethrow(e) end end end wsrouter = router("/router") websocket(wsrouter("/ws")) do ws::HTTP.WebSocket try for msg in ws send(ws, "Received message: $msg") end catch e if !isa(e, HTTP.WebSockets.WebSocketError) rethrow(e) end end end @websocket "/ws/{x}" function(ws, x::Int) try for msg in ws send(ws, "Received message from $x: $msg") end catch e if !isa(e, HTTP.WebSockets.WebSocketError) rethrow(e) end end end # Test if @get works with WebSockets (based on the type of the first argument) @get "/ws/get" function(ws::HTTP.WebSocket) try for msg in ws send(ws, "Received message: $msg") end catch e if !isa(e, HTTP.WebSockets.WebSocketError) rethrow(e) end end end serve(port=PORT, host=HOST, async=true, show_errors=false, show_banner=false, access_log=nothing) @testset "Websocket Tests" begin @testset "/ws route" begin WebSockets.open("ws://$HOST:$PORT/ws") do ws send(ws, "Test message") response = receive(ws) @test response == "Received message: Test message" end end @testset "/router/ws route" begin WebSockets.open("ws://$HOST:$PORT/router/ws") do ws send(ws, "Test message") response = receive(ws) @test response == "Received message: Test message" end end @testset "/ws with arg route" begin WebSockets.open("ws://$HOST:$PORT/ws/9") do ws send(ws, "Test message") response = receive(ws) @test response == "Received message from 9: Test message" end end @testset "/ws with @get" begin WebSockets.open("ws://$HOST:$PORT/ws/get") do ws send(ws, "Test message") response = receive(ws) @test response == "Received message: Test message" end end end terminate() println() end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
451
module TestPackage using Base: @kwdef push!(LOAD_PATH, "../../") using Kitten @oxidise export start, stop @kwdef struct Add a::Int b::Int = 3 end get("/") do text("hello world") end @get "/add" function (req::Request, a::Int, b::Int=3) a + b end @get "/add/extractor" function (req::Request, qparams::Query{Add}) add = qparams.payload add.a + add.b end start(; kwargs...) = serve(; kwargs...) stop() = terminate() end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
1575
module CairoMakieTests using HTTP using Test using Bonito using Kitten @oxidise import Kitten: text, html using ..Constants @testset "Bonito Utils tests" begin app = App() do return DOM.div(DOM.h1("hello world"), js"""console.log('hello world')""") end response = html(app) @test response isa HTTP.Response @test response.status == 200 @test HTTP.header(response, "Content-Type") == "text/html" @test parse(Int, HTTP.header(response, "Content-Length")) >= 0 end @testset "WGLMakie server tests" begin get("/") do text("hello world") end get("/html") do html("hello world") end get("/plot/html") do app = App() do return DOM.div(DOM.h1("hello world")) end html(app) end serve(host=HOST, port=PORT, async=true, show_banner=false, access_log=nothing) # Test overloaded text() function r = HTTP.get("$localhost/") @test r.status == 200 @test HTTP.header(r, "Content-Type") == "text/plain; charset=utf-8" @test parse(Int, HTTP.header(r, "Content-Length")) >= 0 # Test overloaded html function r = HTTP.get("$localhost/html") @test r.status == 200 @test HTTP.header(r, "Content-Type") == "text/html; charset=utf-8" @test parse(Int, HTTP.header(r, "Content-Length")) >= 0 # Test for /plot/html endpoint r = HTTP.get("$localhost/plot/html") @test r.status == 200 @test HTTP.header(r, "Content-Type") == "text/html" @test parse(Int, HTTP.header(r, "Content-Length")) >= 0 terminate() end end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
3212
module CairoMakieTests using HTTP using Test using CairoMakie: heatmap using Kitten @oxidise import Kitten: text using ..Constants @testset "CairoMakie Utils" begin # create a random heatmap fig, ax, pl = heatmap(rand(50, 50)) response = png(fig) @test response isa HTTP.Response @test response.status == 200 @test HTTP.header(response, "Content-Type") == "image/png" @test parse(Int, HTTP.header(response, "Content-Length")) >= 0 response = svg(fig) @test response isa HTTP.Response @test response.status == 200 @test HTTP.header(response, "Content-Type") == "image/svg+xml" @test parse(Int, HTTP.header(response, "Content-Length")) >= 0 response = pdf(fig) @test response isa HTTP.Response @test response.status == 200 @test HTTP.header(response, "Content-Type") == "application/pdf" @test parse(Int, HTTP.header(response, "Content-Length")) >= 0 response = html(fig) @test response isa HTTP.Response @test response.status == 200 @test HTTP.header(response, "Content-Type") == "text/html" @test parse(Int, HTTP.header(response, "Content-Length")) >= 0 end @testset "CairoMakie server" begin get("/") do text("hello world") end get("/html") do html("hello world") end # generate a random plot get("/plot/png") do fig, ax, pl = heatmap(rand(50, 50)) # or something png(fig) end get("/plot/svg") do fig, ax, pl = heatmap(rand(50, 50)) # or something svg(fig) end get("/plot/pdf") do fig, ax, pl = heatmap(rand(50, 50)) # or something pdf(fig) end get("/plot/html") do fig, ax, pl = heatmap(rand(50, 50)) # or something html(fig) end serve(host=HOST, port=PORT, async=true, show_banner=false, access_log=nothing) # Test overloaded text() function r = HTTP.get("$localhost/") @test r.status == 200 @test HTTP.header(r, "Content-Type") == "text/plain; charset=utf-8" @test parse(Int, HTTP.header(r, "Content-Length")) >= 0 # Test overloaded html function r = HTTP.get("$localhost/html") @test r.status == 200 @test HTTP.header(r, "Content-Type") == "text/html; charset=utf-8" @test parse(Int, HTTP.header(r, "Content-Length")) >= 0 # Test for /plot/png endpoint r = HTTP.get("$localhost/plot/png") @test r.status == 200 @test HTTP.header(r, "Content-Type") == "image/png" @test parse(Int, HTTP.header(r, "Content-Length")) >= 0 # Test for /plot/svg endpoint r = HTTP.get("$localhost/plot/svg") @test r.status == 200 @test HTTP.header(r, "Content-Type") == "image/svg+xml" @test parse(Int, HTTP.header(r, "Content-Length")) >= 0 # Test for /plot/pdf endpoint r = HTTP.get("$localhost/plot/pdf") @test r.status == 200 @test HTTP.header(r, "Content-Type") == "application/pdf" @test parse(Int, HTTP.header(r, "Content-Length")) >= 0 # Test for /plot/html endpoint r = HTTP.get("$localhost/plot/html") @test r.status == 200 @test HTTP.header(r, "Content-Type") == "text/html" @test parse(Int, HTTP.header(r, "Content-Length")) >= 0 terminate() end end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
9808
module TemplatingTests using MIMEs using Test using HTTP using Mustache using OteraEngine using Kitten function clean_output(result::String) # Replace carriage returns followed by line feeds (\r\n) with a single newline (\n) tmp = replace(result, "\r\n" => "\n") # Replace sequences of newline followed by spaces (\n\s*) with a single newline (\n) tmp = replace(tmp, r"\n\s*\n" => "\n") return tmp end function remove_trailing_newline(s::String)::String if !isempty(s) && last(s) == '\n' return s[1:end-1] end return s end data = Dict( "name" => "Chris", "value" => 10000, "taxed_value" => 10000 - (10000 * 0.4), "in_ca" => true ) mustache_template = mt""" Hello {{name}} You have just won {{value}} dollars! {{#in_ca}} Well, {{taxed_value}} dollars, after taxes. {{/in_ca}} """ mustache_template_str = """ Hello {{name}} You have just won {{value}} dollars! {{#in_ca}} Well, {{taxed_value}} dollars, after taxes. {{/in_ca}} """ expected_output = """ Hello Chris You have just won 10000 dollars! Well, 6000.0 dollars, after taxes. """ @testset "Templating Module Tests" begin @testset "mustache() from string no args " begin plain_temp = "Hello World!" render = mustache(plain_temp, mime_type="text/plain") response = render() @test response.body |> String |> clean_output == plain_temp end @testset "mustache() from string tests " begin render = mustache(mustache_template_str, mime_type="text/plain") response = render(data) @test response.body |> String |> clean_output == expected_output end @testset "mustache() from string tests w/ content type" begin render = mustache(mustache_template_str) response = render(data) @test response.body |> String |> clean_output == expected_output end @testset "mustache() from file no content type" begin render = mustache("./content/mustache_template.txt", from_file=true) response = render(data) @test response.body |> String |> clean_output == expected_output end @testset "mustache() from file w/ content type" begin render = mustache("./content/mustache_template.txt", mime_type="text/plain", from_file=true) response = render(data) @test response.body |> String |> clean_output == expected_output end @testset "mustache() from file with no content type" begin render = open(mustache, "./content/mustache_template.txt") response = render(data) @test response.body |> String |> clean_output == expected_output end @testset "mustache() from file with content type" begin render = open(io -> mustache(io; mime_type="text/plain"), "./content/mustache_template.txt") response = render(data) @test response.body |> String |> clean_output == expected_output end @testset "mustache() from template" begin render = mustache(mustache_template) response = render(data) @test response.body |> String |> clean_output == expected_output end @testset "mustache() from template with content type" begin render = mustache(mustache_template, mime_type="text/plain") response = render(data) @test response.body |> String |> clean_output == expected_output end # @testset "mustache api tests" begin mus_str = mustache(mustache_template_str) mus_tpl = mustache(mustache_template) mus_file = mustache("./content/mustache_template.txt", from_file=true) @get "/mustache/string" function () return mus_str(data) end @get "/mustache/template" function () return mus_tpl(data) end @get "/mustache/file" function () return mus_file(data) end r = internalrequest(HTTP.Request("GET", "/mustache/string")) @test r.status == 200 @test r.body |> String |> clean_output == expected_output r = internalrequest(HTTP.Request("GET", "/mustache/template")) @test r.status == 200 @test r.body |> String |> clean_output == expected_output r = internalrequest(HTTP.Request("GET", "/mustache/file")) @test r.status == 200 @test r.body |> String |> clean_output == expected_output # end @testset "otera() from string" begin template = """ <html> <head><title>MyPage</title></head> <body> {% if name=="watasu" %} your name is {{ name }}, right? {% end %} {% for i in 1 : 10 %} Hello {{i}} {% end %} {% if age == 15 %} and your age is {{ age }}. {% end %} </body> </html> """ |> remove_trailing_newline expected_output = """ <html> <head><title>MyPage</title></head> <body> your name is watasu, right? Hello 1 Hello 2 Hello 3 Hello 4 Hello 5 Hello 6 Hello 7 Hello 8 Hello 9 Hello 10 and your age is 15. </body> </html> """ |> remove_trailing_newline # detect content type data = Dict("name" => "watasu", "age" => 15) render = otera(template) result = render(data) @test result.body |> String |> clean_output == expected_output # with explicit content type data = Dict("name" => "watasu", "age" => 15) render = otera(template; mime_type="text/html") result = render(data) @test result.body |> String |> clean_output == expected_output end @testset "otera() from template file" begin expected_output = """ <html> <head><title>MyPage</title></head> <body> your name is watasu, right? Hello 1 Hello 2 Hello 3 Hello 4 Hello 5 Hello 6 Hello 7 Hello 8 Hello 9 Hello 10 and your age is 15. </body> </html> """ |> remove_trailing_newline data = Dict("name" => "watasu", "age" => 15) render = otera("./content/otera_template.html", from_file=true) result = render(data) @test result.body |> String |> clean_output == expected_output # with explicit content type render = open(io -> otera(io; mime_type="text/html"), "./content/otera_template.html") result = render(data) @test result.body |> String |> clean_output == expected_output end @testset "otera() from template file with no args" begin expected_output = """ <html> <head><title>MyPage</title></head> <body> your name is watasu, right? Hello 1 Hello 2 Hello 3 Hello 4 Hello 5 Hello 6 Hello 7 Hello 8 Hello 9 Hello 10 and your age is 15. </body> </html> """ |> remove_trailing_newline render = otera("./content/otera_template_no_vars.html", from_file=true) result = render() @test result.body |> String |> clean_output == expected_output render = otera("./content/otera_template_no_vars.html", mime_type="text/html", from_file=true) result = render() @test result.body |> String |> clean_output == expected_output end @testset "otera() from template file with jl init data" begin expected_output = """ <html> <head><title>MyPage</title></head> <body> <h1>Hello World!</h1> </body> </html> """ |> remove_trailing_newline render = otera("./content/otera_template_jl.html", from_file=true) result = render(Dict("name" => "World")) @test result.body |> String |> clean_output == expected_output end @testset "otera() running julia code in template" begin template = "{< 3 ^ 3 >}. Hello {{ name }}!" expected_output = "27. Hello world!" render = otera(template) result = render(Dict("name" => "world")) @test result.body |> String |> clean_output == expected_output template = """ <html> <head><title>Jinja Test Page</title></head> <body> Hello, {<name>}! </body> </html> """ |> remove_trailing_newline expected_output = """ <html> <head><title>Jinja Test Page</title></head> <body> Hello, world! </body> </html> """ |> remove_trailing_newline render = otera(template) result = render(Dict("name" => "world")) @test result.body |> String |> clean_output == expected_output end @testset "otera() combined tmp_init & init test" begin template = "{< parse(Int, value) ^ 3 >}. Hello {{name}}!" expected_output = "27. Hello World!" render = otera(template) result = render(Dict("name" => "World", "value" => "3")) end @testset "otera() combined tmp_init & init test with content type" begin template = "{< parse(Int, value) ^ 3 >}. Hello {{name}}!" expected_output = "27. Hello World!" render = otera(template, mime_type="text/plain") result = render(Dict("name" => "World", "value" => "3")) end end end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
1533
module CairoMakieTests using HTTP using Test using Bonito using WGLMakie: heatmap using Kitten @oxidise import Kitten: text, html using ..Constants @testset "WGLMakie Utils tests" begin # create a random heatmap fig = heatmap(rand(50, 50)) response = html(fig) @test response isa HTTP.Response @test response.status == 200 @test HTTP.header(response, "Content-Type") == "text/html" @test parse(Int, HTTP.header(response, "Content-Length")) >= 0 end @testset "WGLMakie server tests" begin get("/") do text("hello world") end get("/html") do html("hello world") end # generate a random plot get("/plot/html") do fig = heatmap(rand(50, 50)) html(fig) end serve(host=HOST, port=PORT, async=true, show_banner=false, access_log=nothing) # Test overloaded text() function r = HTTP.get("$localhost/") @test r.status == 200 @test HTTP.header(r, "Content-Type") == "text/plain; charset=utf-8" @test parse(Int, HTTP.header(r, "Content-Length")) >= 0 # Test overloaded html function r = HTTP.get("$localhost/html") @test r.status == 200 @test HTTP.header(r, "Content-Type") == "text/html; charset=utf-8" @test parse(Int, HTTP.header(r, "Content-Length")) >= 0 # Test for /plot/html endpoint r = HTTP.get("$localhost/plot/html") @test r.status == 200 @test HTTP.header(r, "Content-Type") == "text/html" @test parse(Int, HTTP.header(r, "Content-Length")) >= 0 terminate() end end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
1880
module ProtobufTests using Test using HTTP using ProtoBuf using Kitten: protobuf include("messages/people_pb.jl") using .people_pb: People, Person include("messages/test_pb.jl") using .test_pb: MyMessage @testset "Protobuf decoder test" begin message = MyMessage(-1, ["a", "b"]) req::HTTP.Request = protobuf(message, "/data") decoded_msg = protobuf(req, MyMessage) @test decoded_msg isa MyMessage @test decoded_msg.a == -1 @test decoded_msg.b == ["a", "b"] end @testset "Protobuf People Decoder test" begin message = People([ Person("John Doe", 20), Person("Jane Doe", 25), Person("Alice", 30), Person("Bob", 35), Person("Charlie", 40) ]) req::HTTP.Request = protobuf(message, "/data", method="POST") decoded_msg = protobuf(req, People) @test decoded_msg isa People for person in decoded_msg.people @test person isa Person end end @testset "Protobuf encoder test" begin message = MyMessage(-1, ["a", "b"]) response = protobuf(message) @test response isa HTTP.Response @test response.status == 200 @test response.body isa Vector{UInt8} @test HTTP.header(response, "Content-Type") == "application/octet-stream" @test HTTP.header(response, "Content-Length") == string(sizeof(response.body)) end @testset "Protobuf People encoder test" begin message = People([ Person("John Doe", 20), Person("Jane Doe", 25), Person("Alice", 30), Person("Bob", 35), Person("Charlie", 40) ]) response = protobuf(message) @test response isa HTTP.Response @test response.status == 200 @test response.body isa Vector{UInt8} @test HTTP.header(response, "Content-Type") == "application/octet-stream" @test HTTP.header(response, "Content-Length") == string(sizeof(response.body)) end end
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
2234
# Autogenerated using ProtoBuf.jl v1.0.15 on 2024-03-10T22:46:41.410 # original file: D:\Programming\JuliaProjects\kitten-demo\src\people.proto (proto3 syntax) module people_pb import ProtoBuf as PB using ProtoBuf: OneOf using ProtoBuf.EnumX: @enumx export Person, People struct Person name::String age::Int32 end PB.default_values(::Type{Person}) = (;name = "", age = zero(Int32)) PB.field_numbers(::Type{Person}) = (;name = 1, age = 2) function PB.decode(d::PB.AbstractProtoDecoder, ::Type{<:Person}) name = "" age = zero(Int32) while !PB.message_done(d) field_number, wire_type = PB.decode_tag(d) if field_number == 1 name = PB.decode(d, String) elseif field_number == 2 age = PB.decode(d, Int32, Val{:zigzag}) else PB.skip(d, wire_type) end end return Person(name, age) end function PB.encode(e::PB.AbstractProtoEncoder, x::Person) initpos = position(e.io) !isempty(x.name) && PB.encode(e, 1, x.name) x.age != zero(Int32) && PB.encode(e, 2, x.age, Val{:zigzag}) return position(e.io) - initpos end function PB._encoded_size(x::Person) encoded_size = 0 !isempty(x.name) && (encoded_size += PB._encoded_size(x.name, 1)) x.age != zero(Int32) && (encoded_size += PB._encoded_size(x.age, 2, Val{:zigzag})) return encoded_size end struct People people::Vector{Person} end PB.default_values(::Type{People}) = (;people = Vector{Person}()) PB.field_numbers(::Type{People}) = (;people = 1) function PB.decode(d::PB.AbstractProtoDecoder, ::Type{<:People}) people = PB.BufferedVector{Person}() while !PB.message_done(d) field_number, wire_type = PB.decode_tag(d) if field_number == 1 PB.decode!(d, people) else PB.skip(d, wire_type) end end return People(people[]) end function PB.encode(e::PB.AbstractProtoEncoder, x::People) initpos = position(e.io) !isempty(x.people) && PB.encode(e, 1, x.people) return position(e.io) - initpos end function PB._encoded_size(x::People) encoded_size = 0 !isempty(x.people) && (encoded_size += PB._encoded_size(x.people, 1)) return encoded_size end end # module
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
code
1387
# Autogenerated using ProtoBuf.jl v1.0.15 on 2024-02-27T23:51:29.590 # original file: D:\Programming\JuliaProjects\kitten-demo\src\test.proto (proto3 syntax) module test_pb import ProtoBuf as PB using ProtoBuf: OneOf using ProtoBuf.EnumX: @enumx export MyMessage struct MyMessage a::Int32 b::Vector{String} end PB.default_values(::Type{MyMessage}) = (;a = zero(Int32), b = Vector{String}()) PB.field_numbers(::Type{MyMessage}) = (;a = 1, b = 2) function PB.decode(d::PB.AbstractProtoDecoder, ::Type{<:MyMessage}) a = zero(Int32) b = PB.BufferedVector{String}() while !PB.message_done(d) field_number, wire_type = PB.decode_tag(d) if field_number == 1 a = PB.decode(d, Int32, Val{:zigzag}) elseif field_number == 2 PB.decode!(d, b) else PB.skip(d, wire_type) end end return MyMessage(a, b[]) end function PB.encode(e::PB.AbstractProtoEncoder, x::MyMessage) initpos = position(e.io) x.a != zero(Int32) && PB.encode(e, 1, x.a, Val{:zigzag}) !isempty(x.b) && PB.encode(e, 2, x.b) return position(e.io) - initpos end function PB._encoded_size(x::MyMessage) encoded_size = 0 x.a != zero(Int32) && (encoded_size += PB._encoded_size(x.a, 1, Val{:zigzag})) !isempty(x.b) && (encoded_size += PB._encoded_size(x.b, 2)) return encoded_size end end # module
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
docs
40855
# Kitten.jl ## About Kitten is a micro-framework built on top of the HTTP.jl library. ## Features - Straightforward routing - Real-time Metrics Dashboard - Auto-generated swagger documentation - Out-of-the-box JSON serialization & deserialization (customizable) - Type definition support for path parameters - Request Extractors - Multiple Instance Support - Multithreading support - Websockets, Streaming, and Server-Sent Events - Cron Scheduling (on endpoints & functions) - Middleware chaining (at the application, router, and route levels) - Static & Dynamic file hosting - Templating Support - Plotting Support - Protocol Buffer Support - Route tagging - Repeat tasks ## Installation ```julia pkg> add Kitten ``` ## Minimalistic Example Create a web-server with very few lines of code ```julia using Kitten using HTTP @get "/greet" function(req::HTTP.Request) return "hello world!" end # start the web server serve() ``` ## Handlers Handlers are used to connect your code to the server in a clean & straightforward way. They assign a url to a function and invoke the function when an incoming request matches that url. - Handlers can be imported from other modules and distributed across multiple files for better organization and modularity - All handlers have equivalent macro & function implementations and support `do..end` block syntax - The type of first argument is used to identify what kind of handler is being registered - This package assumes it's a `Request` handler by default when no type information is provided There are 3 types of supported handlers: - `Request` Handlers - `Stream` Handlers - `Websocket` Handlers ```julia using HTTP using Kitten # Request Handler @get "/" function(req::HTTP.Request) ... end # Stream Handler @stream "/stream" function(stream::HTTP.Stream) ... end # Websocket Handler @websocket "/ws" function(ws::HTTP.WebSocket) ... end ``` They are just functions which means there are many ways that they can be expressed and defined. Below is an example of several different ways you can express and assign a `Request` handler. ```julia @get "/greet" function() "hello world!" end @get("/gruessen") do "Hallo Welt!" end @get "/saluer" () -> begin "Bonjour le monde!" end @get "/saludar" () -> "Β‘Hola Mundo!" @get "/salutare" f() = "ciao mondo!" # This function can be declared in another module function subtract(req, a::Float64, b::Float64) return a - b end # register foreign request handlers like this @get "/subtract/{a}/{b}" subtract ``` <details> <summary><b>More Handler Docs</b></summary> ### Request Handlers Request handlers are used to handle HTTP requests. They are defined using macros or their function equivalents, and accept a `HTTP.Request` object as the first argument. These handlers support both function and do-block syntax. - The default Handler when no type information is provided - Routing Macros: `@get`, `@post`, `@put`, `@patch`, `@delete`, `@route` - Routing Functions: `get()`, `post()`, `put()`, `patch()`, `delete()`, `route()` ### Stream Handlers Stream handlers are used to stream data. They are defined using the `@stream` macro or the `stream()` function and accept a `HTTP.Stream` object as the first argument. These handlers support both function and do-block syntax. - `@stream` and `stream()` don't require a type definition on the first argument, they assume it's a stream. - `Stream` handlers can be assigned with standard routing macros & functions: `@get`, `@post`, etc - You need to explicitly include the type definition so Kitten can identify this as a `Stream` handler ### Websocket Handlers Websocket handlers are used to handle websocket connections. They are defined using the `@websocket` macro or the `websocket()` function and accept a `HTTP.WebSocket` object as the first argument. These handlers support both function and do-block syntax. - `@websocket` and `websocket()` don't require a type definition on the first argument, they assume it's a websocket. - `Websocket` handlers can also be assigned with the `@get` macro or `get()` function, because the websocket protocol requires a `GET` request to initiate the handshake. - You need to explicitly include the type definition so Kitten can identify this as a `Websocket` handler </details> ## Routing Macro & Function Syntax There are two primary ways to register your request handlers: the standard routing macros or the routing functions which utilize the do-block syntax. For each routing macro, we now have a an equivalent routing function ```julia @get -> get() @post -> post() @put -> put() @patch -> patch() @delete -> delete() @route -> route() ``` The only practical difference between the two is that the routing macros are called during the precompilation stage, whereas the routing functions are only called when invoked. (The routing macros call the routing functions under the hood) ```julia # Routing Macro syntax @get "/add/{x}/{y}" function(request::HTTP.Request, x::Int, y::Int) x + y end # Routing Function syntax get("/add/{x}/{y}") do request::HTTP.Request, x::Int, y::Int x + y end ``` ## Render Functions Kitten, by default, automatically identifies the Content-Type of the return value from a request handler when building a Response. This default functionality is quite useful, but it does have an impact on performance. In situations where the return type is known, It's recommended to use one of the pre-existing render functions to speed things up. Here's a list of the currently supported render functions: `html`, `text`, `json`, `file`, `xml`, `js`, `css`, `binary` Below is an example of how to use these functions: ```julia using Kitten get("/html") do html("<h1>Hello World</h1>") end get("/text") do text("Hello World") end get("/json") do json(Dict("message" => "Hello World")) end serve() ``` In most cases, these functions accept plain strings as inputs. The only exceptions are the `binary` function, which accepts a `Vector{UInt8}`, and the `json` function which accepts any serializable type. - Each render function accepts a status and custom headers. - The Content-Type and Content-Length headers are automatically set by these render functions ## Path parameters Path parameters are declared with braces and are passed directly to your request handler. ```julia using Kitten # use path params without type definitions (defaults to Strings) @get "/add/{a}/{b}" function(req, a, b) return parse(Float64, a) + parse(Float64, b) end # use path params with type definitions (they are automatically converted) @get "/multiply/{a}/{b}" function(req, a::Float64, b::Float64) return a * b end # The order of the parameters doesn't matter (just the name matters) @get "/subtract/{a}/{b}" function(req, b::Int64, a::Int64) return a - b end # start the web server serve() ``` ## Query parameters Query parameters can be declared directly inside of your handlers signature. Any parameter that isn't mentioned inside the route path is assumed to be a query parameter. - If a default value is not provided, it's assumed to be a required parameter ```julia @get "/query" function(req::HTTP.Request, a::Int, message::String="hello world") return (a, message) end ``` Alternatively, you can use the `queryparams()` function to extract the raw values from the url as a dictionary. ```julia @get "/query" function(req::HTTP.Request) return queryparams(req) end ``` ## HTML Forms Use the `formdata()` function to extract and parse the form data from the body of a request. This function returns a dictionary of key-value pairs from the form ```julia using Kitten # Setup a basic form @get "/" function() html(""" <form action="/form" method="post"> <label for="firstname">First name:</label><br> <input type="text" id="firstname" name="firstname"><br> <label for="lastname">Last name:</label><br> <input type="text" id="lastname" name="lastname"><br><br> <input type="submit" value="Submit"> </form> """) end # Parse the form data and return it @post "/form" function(req) data = formdata(req) return data end serve() ``` ## Return JSON All objects are automatically deserialized into JSON using the JSON3 library ```julia using Kitten using HTTP @get "/data" function(req::HTTP.Request) return Dict("message" => "hello!", "value" => 99.3) end # start the web server serve() ``` ## Deserialize & Serialize custom structs Kitten provides some out-of-the-box serialization & deserialization for most objects but requires the use of StructTypes when converting structs ```julia using Kitten using HTTP using StructTypes struct Animal id::Int type::String name::String end # Add a supporting struct type definition so JSON3 can serialize & deserialize automatically StructTypes.StructType(::Type{Animal}) = StructTypes.Struct() @get "/get" function(req::HTTP.Request) # serialize struct into JSON automatically (because we used StructTypes) return Animal(1, "cat", "whiskers") end @post "/echo" function(req::HTTP.Request) # deserialize JSON from the request body into an Animal struct animal = json(req, Animal) # serialize struct back into JSON automatically (because we used StructTypes) return animal end # start the web server serve() ``` ## Extractors Kitten comes with several built-in extractors designed to reduce the amount of boilerplate required to serialize inputs to your handler functions. By simply defining a struct and specifying the data source, these extractors streamline the process of data ingestion & validation through a uniform api. - The serialized data is accessible through the `payload` property - Can be used alongside other parameters and extractors - Default values can be assigned when defined with the `@kwdef` macro - Includes both global and local validators - Struct definitions can be deeply nested Supported Extractors: - `Path` - extracts from path parameters - `Query` - extracts from query parameters, - `Header` - extracts from request headers - `Form` - extracts form data from the request body - `Body` - serializes the entire request body to a given type (String, Float64, etc..) - `ProtoBuffer` - extracts the `ProtoBuf` message from the request body (available through a package extension) - `Json` - extracts json from the request body - `JsonFragment` - extracts a "fragment" of the json body using the parameter name to identify and extract the corresponding top-level key #### Using Extractors & Parameters In this example we show that the `Path` extractor can be used alongside regular path parameters. This Also works with regular query parameters and the `Query` extractor. ```julia struct Add b::Int c::Int end @get "/add/{a}/{b}/{c}" function(req, a::Int, pathparams::Path{Add}) add = pathparams.payload # access the serialized payload return a + add.b + add.c end ``` #### Default Values Default values can be setup with structs using the `@kwdef` macro. ```julia @kwdef struct Pet name::String age::Int = 10 end @post "/pet" function(req, params::Json{Pet}) return params.payload # access the serialized payload end ``` #### Validation On top of serializing incoming data, you can also define your own validation rules by using the `validate` function. In the example below we show how to use both `global` and `local` validators in your code. - Validators are completely optional - During the validation phase, Kitten will call the `global` validator before running a `local` validator. ```julia import Kitten: validate struct Person name::String age::Int end # Define a global validator validate(p::Person) = p.age >= 0 # Only the global validator is ran here @post "/person" function(req, newperson::Json{Person}) return newperson.payload end # In this case, both global and local validators are ran (this also makes sure the person is age 21+) # You can also use this sytnax instead: Json(Person, p -> p.age >= 21) @post "/adult" function(req, newperson = Json{Person}(p -> p.age >= 21)) return newperson.payload end ``` ## Interpolating variables into endpoints You can interpolate variables directly into the paths, which makes dynamically registering routes a breeze (Thanks to @anandijain for the idea) ```julia using Kitten operations = Dict("add" => +, "multiply" => *) for (pathname, operator) in operations @get "/$pathname/{a}/{b}" function (req, a::Float64, b::Float64) return operator(a, b) end end # start the web server serve() ``` ## Routers The `router()` function is an HOF (higher order function) that allows you to reuse the same path prefix & properties across multiple endpoints. This is helpful when your api starts to grow and you want to keep your path operations organized. Below are the arguments the `router()` function can take: ```julia router(prefix::String; tags::Vector, middleware::Vector, interval::Real, cron::String) ``` - `tags` - are used to organize endpoints in the autogenerated docs - `middleware` - is used to setup router & route-specific middleware - `interval` - is used to support repeat actions (_calling a request handler on a set interval in seconds_) - `cron` - is used to specify a cron expression that determines when to call the request handler. ```julia using Kitten # Any routes that use this router will be automatically grouped # under the 'math' tag in the autogenerated documenation math = router("/math", tags=["math"]) # You can also assign route specific tags @get math("/multiply/{a}/{b}", tags=["multiplication"]) function(req, a::Float64, b::Float64) return a * b end @get math("/divide/{a}/{b}") function(req, a::Float64, b::Float64) return a / b end serve() ``` ## Cron Scheduling Kitten comes with a built-in cron scheduling system that allows you to call endpoints and functions automatically when the cron expression matches the current time. When a job is scheduled, a new task is created and runs in the background. Each task uses its given cron expression and the current time to determine how long it needs to sleep before it can execute. The cron parser in Kitten is based on the same specifications as the one used in Spring. You can find more information about this on the [Spring Cron Expressions](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/support/CronExpression.html) page. ### Cron Expression Syntax The following is a breakdown of what each parameter in our cron expression represents. While our specification closely resembles the one defined by Spring, it's not an exact 1-to-1 match. ``` The string has six single space-separated time and date fields: β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ second (0-59) β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ minute (0 - 59) β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ hour (0 - 23) β”‚ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ day of the month (1 - 31) β”‚ β”‚ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ month (1 - 12) (or JAN-DEC) β”‚ β”‚ β”‚ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ day of the week (1 - 7) β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ (Monday is 1, Tue is 2... and Sunday is 7) β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ * * * * * * ``` Partial expressions are also supported, which means that subsequent expressions can be left out (they are defaulted to `'*'`). ```julia # In this example we see only the `seconds` part of the expression is defined. # This means that all following expressions are automatically defaulted to '*' expressions @cron "*/2" function() println("runs every 2 seconds") end ``` ### Scheduling Endpoints The `router()` function has a keyword argument called `cron`, which accepts a cron expression that determines when an endpoint is called. Just like the other keyword arguments, it can be reused by endpoints that share routers or be overridden by inherited endpoints. ```julia # execute at 8, 9 and 10 o'clock of every day. @get router("/cron-example", cron="0 0 8-10 * * *") function(req) println("here") end # execute this endpoint every 5 seconds (whenever current_seconds % 5 == 0) every5 = router("/cron", cron="*/5") # this endpoint inherits the cron expression @get every5("/first") function(req) println("first") end # Now this endpoint executes every 2 seconds ( whenever current_seconds % 2 == 0 ) instead of every 5 @get every5("/second", cron="*/2") function(req) println("second") end ``` ### Scheduling Functions In addition to scheduling endpoints, you can also use the new `@cron` macro to schedule functions. This is useful if you want to run code at specific times without making it visible or callable in the API. ```julia @cron "*/2" function() println("runs every 2 seconds") end @cron "0 0/30 8-10 * * *" function() println("runs at 8:00, 8:30, 9:00, 9:30, 10:00 and 10:30 every day") end ``` ### Starting & Stopping Cron Jobs When you run `serve()` or `serveparallel()`, all registered cron jobs are automatically started. If the server is stopped or killed, all running jobs will also be terminated. You can stop the server and all repeat tasks and cron jobs by calling the `terminate()` function or manually killing the server with `ctrl+C`. In addition, Kitten provides utility functions to manually start and stop cron jobs: `startcronjobs()` and `stopcronjobs()`. These functions can be used outside of a web server as well. ## Repeat Tasks Repeat tasks provide a simple api to run a function on a set interval. There are two ways to register repeat tasks: - Through the `interval` parameter in a `router()` - Using the `@repeat` macro **It's important to note that request handlers that use this property can't define additional function parameters outside of the default `HTTP.Request` parameter.** In the example below, the `/repeat/hello` endpoint is called every 0.5 seconds and `"hello"` is printed to the console each time. The `router()` function has an `interval` parameter which is used to call a request handler on a set interval (in seconds). ```julia using Kitten taskrouter = router("/repeat", interval=0.5, tags=["repeat"]) @get taskrouter("/hello") function() println("hello") end # you can override properties by setting route specific values @get taskrouter("/bonjour", interval=1.5) function() println("bonjour") end serve() ``` Below is an example of how to register a repeat task outside of the router ```julia @repeat 1.5 function() println("runs every 1.5 seconds") end # you can also "name" a repeat task @repeat 5 "every-five" function() println("runs every 5 seconds") end ``` When the server is ran, all tasks are started automatically. But the module also provides utilities to have more fine-grained control over the running tasks using the following functions: `starttasks()`, `stoptasks()`, and `cleartasks()` ## Multiple Instances In some advanced scenarios, you might need to spin up multiple web severs within the same module on different ports. Kitten provides both a static and dynamic way to create multiple instances of a web server. As a general rule of thumb, if you know how many instances you need ahead of time it's best to go with the static approach. ### Static: multiple instance's with `@oxidise` Kitten provides a new macro which makes it possible to setup and run multiple instances. It generates methods and binds them to a new internal state for the current module. In the example below, two simple servers are defined within modules A and B and are started in the parent module. Both modules contain all of the functions exported from Kitten which can be called directly as shown below. ```julia module A using Kitten; @oxidise get("/") do text("server A") end end module B using Kitten; @oxidise get("/") do text("server B") end end try # start both instances A.serve(port=8001, async=true) B.serve(port=8002, async=false) finally # shut down if we `Ctrl+C` A.terminate() B.terminate() end ``` ### Dynamic: multiple instance's with `instance()` The `instance` function helps you create a completely independent instance of an Kitten web server at runtime. It works by dynamically creating a julia module at runtime and loading the Kitten code within it. All of the same methods from Kitten are available under the named instance. In the example below we can use the `get`, and `serve` by simply using dot syntax on the `app1` variable to access the underlying methods. ```julia using Kitten ######### Setup the first app ######### app1 = instance() app1.get("/") do text("server A") end ######### Setup the second app ######### app2 = instance() app2.get("/") do text("server B") end ######### Start both instances ######### try # start both servers together app1.serve(port=8001, async=true) app2.serve(port=8002) finally # clean it up app1.terminate() app2.terminate() end ``` ## Multithreading & Parallelism For scenarios where you need to handle higher amounts of traffic, you can run Kitten in a multithreaded mode. In order to utilize this mode, julia must have more than 1 thread to work with. You can start a julia session with 4 threads using the command below ```shell julia --threads 4 ``` `serveparallel()` Starts the webserver in streaming mode and handles requests in a cooperative multitasking approach. This function uses `Threads.@spawn` to schedule a new task on any available thread. Meanwhile, @async is used inside this task when calling each request handler. This allows the task to yield during I/O operations. ```julia using Kitten using StructTypes using Base.Threads # Make the Atomic struct serializable StructTypes.StructType(::Type{Atomic{Int64}}) = StructTypes.Struct() x = Atomic{Int64}(0); @get "/show" function() return x end @get "/increment" function() atomic_add!(x, 1) return x end # start the web server in parallel mode serveparallel() ``` ## Protocol Buffers Kitten includes an extension for the [ProtoBuf.jl](https://github.com/JuliaIO/ProtoBuf.jl) package. This extension provides a `protobuf()` function, simplifying the process of working with Protocol Buffers in the context of web server. For a better understanding of this package, please refer to its official documentation. This function has overloads for the following scenarios: - Decoding a protobuf message from the body of an HTTP request. - Encoding a protobuf message into the body of an HTTP request. - Encoding a protobuf message into the body of an HTTP response. ```julia using HTTP using ProtoBuf using Kitten # The generated classes need to be created ahead of time (check the protobufs) include("people_pb.jl"); using .people_pb: People, Person # Decode a Protocol Buffer Message @post "/count" function(req::HTTP.Request) # decode the request body into a People object message = protobuf(req, People) # count the number of Person objects return length(message.people) end # Encode & Return Protocol Buffer message @get "/get" function() message = People([ Person("John Doe", 20), Person("Alice", 30), Person("Bob", 35) ]) # seralize the object inside the body of a HTTP.Response return protobuf(message) end ``` The following is an example of a schema that was used to create the necessary Julia bindings. These bindings allow for the encoding and decoding of messages in the above example. ```protobuf syntax = "proto3"; message Person { string name = 1; sint32 age = 2; } message People { repeated Person people = 1; } ``` ## Plotting Kitten is equipped with several package extensions that enhance its plotting capabilities. These extensions make it easy to return plots directly from request handlers. All operations are performed in-memory using an IOBuffer and return a `HTTP.Response` Supported Packages and their helper utils: - CairoMakie.jl: `png`, `svg`, `pdf`, `html` - WGLMakie.jl: `html` - Bonito.jl: `html` #### CairoMakie.jl ```julia using CairoMakie: heatmap using Kitten @get "/cairo" function() fig, ax, pl = heatmap(rand(50, 50)) png(fig) end serve() ``` #### WGLMakie.jl ```julia using Bonito using WGLMakie: heatmap using Kitten using Kitten: html # Bonito also exports html @get "/wgl" function() fig = heatmap(rand(50, 50)) html(fig) end serve() ``` #### Bonito.jl ```julia using Bonito using WGLMakie: heatmap using Kitten using Kitten: html # Bonito also exports html @get "/bonito" function() app = App() do return DOM.div( DOM.h1("Random 50x50 Heatmap"), DOM.div(heatmap(rand(50, 50))) ) end return html(app) end serve() ``` ## Templating Rather than building an internal engine for templating or adding additional dependencies, Kitten provides two package extensions to support `Mustache.jl` and `OteraEngine.jl` templates. Kitten provides a simple wrapper api around both packages that makes it easy to render templates from strings, templates, and files. This wrapper api returns a `render` function which accepts a dictionary of inputs to fill out the template. In all scenarios, the rendered template is returned inside a HTTP.Response object ready to get served by the api. By default, the mime types are auto-detected either by looking at the content of the template or the extension name on the file. If you know the mime type you can pass it directly through the `mime_type` keyword argument to skip the detection process. ### Mustache Templating Please take a look at the [Mustache.jl](https://jverzani.github.io/Mustache.jl/dev/) documentation to learn the full capabilities of the package Example 1: Rendering a Mustache Template from a File ```julia using Mustache using Kitten # Load the Mustache template from a file and create a render function render = mustache("./templates/greeting.txt", from_file=false) @get "/mustache/file" function() data = Dict("name" => "Chris") return render(data) # This will return an HTML.Response with the rendered template end ``` Example 2: Specifying MIME Type for a plain string Mustache Template ```julia using Mustache using Kitten # Define a Mustache template (both plain strings and mustache templates are supported) template_str = "Hello, {{name}}!" # Create a render function, specifying the MIME type as text/plain render = mustache(template_str, mime_type="text/plain") # mime_type keyword arg is optional @get "/plain/text" function() data = Dict("name" => "Chris") return render(data) # This will return a plain text response with the rendered template end ``` ### Otera Templating Please take a look at the [OteraEngine.jl](https://mommawatasu.github.io/OteraEngine.jl/dev/tutorial/#API) documentation to learn the full capabilities of the package Example 1: Rendering an Otera Template with Logic and Loops ```julia using OteraEngine using Kitten # Define an Otera template template_str = """ <html> <head><title>{{ title }}</title></head> <body> {% for name in names %} Hello {{ name }}<br> {% end %} </body> </html> """ # Create a render function for the Otera template render = otera(template_str) @get "/otera/loop" function() data = Dict("title" => "Greetings", "names" => ["Alice", "Bob", "Chris"]) return render(data) # This will return an HTML.Response with the rendered template end ``` In this example, an Otera template is defined with a for-loop that iterates over a list of names, greeting each name. Example 2: Running Julia Code in Otera Template ```julia using OteraEngine using Kitten # Define an Otera template with embedded Julia code template_str = """ The square of {{ number }} is {< number^2 >}. """ # Create a render function for the Otera template render = otera(template_str) @get "/otera/square" function() data = Dict("number" => 5) return render(data) # This will return an HTML.Response with the rendered template end ``` In this example, an Otera template is defined with embedded Julia code that calculates the square of a given number. ## Mounting Static Files You can mount static files using this handy function which recursively searches a folder for files and mounts everything. All files are loaded into memory on startup. ```julia using Kitten # mount all files inside the "content" folder under the "/static" path staticfiles("content", "static") # start the web server serve() ``` ## Mounting Dynamic Files Similar to staticfiles, this function mounts each path and re-reads the file for each request. This means that any changes to the files after the server has started will be displayed. ```julia using Kitten # mount all files inside the "content" folder under the "/dynamic" path dynamicfiles("content", "dynamic") # start the web server serve() ``` ## Performance Tips Disabling the internal logger can provide some massive performance gains, which can be helpful in some scenarios. Anecdotally, i've seen a 2-3x speedup in `serve()` and a 4-5x speedup in `serveparallel()` performance. ```julia # This is how you disable internal logging in both modes serve(access_log=nothing) serveparallel(access_log=nothing) ``` ## Logging Kitten provides a default logging format but allows you to customize the format using the `access_log` parameter. This functionality is available in both the `serve()` and `serveparallel()` functions. You can read more about the logging options [here](https://juliaweb.github.io/HTTP.jl/stable/reference/#HTTP.@logfmt_str) ```julia # Uses the default logging format serve() # Customize the logging format serve(access_log=logfmt"[$time_iso8601] \"$request\" $status") # Disable internal request logging serve(access_log=nothing) ``` ## Middleware Middleware functions make it easy to create custom workflows to intercept all incoming requests and outgoing responses. They are executed in the same order they are passed in (from left to right). They can be set at the application, router, and route layer with the `middleware` keyword argument. All middleware is additive and any middleware defined in these layers will be combined and executed. Middleware will always be executed in the following order: ``` application -> router -> route ``` Now lets see some middleware in action: ```julia using Kitten using HTTP const CORS_HEADERS = [ "Access-Control-Allow-Origin" => "*", "Access-Control-Allow-Headers" => "*", "Access-Control-Allow-Methods" => "POST, GET, OPTIONS" ] # https://juliaweb.github.io/HTTP.jl/stable/examples/#Cors-Server function CorsMiddleware(handler) return function(req::HTTP.Request) println("CORS middleware") # determine if this is a pre-flight request from the browser if HTTP.method(req)=="OPTIONS" return HTTP.Response(200, CORS_HEADERS) else return handler(req) # passes the request to the AuthMiddleware end end end function AuthMiddleware(handler) return function(req::HTTP.Request) println("Auth middleware") # ** NOT an actual security check ** # if !HTTP.headercontains(req, "Authorization", "true") return HTTP.Response(403) else return handler(req) # passes the request to your application end end end function middleware1(handle) function(req) println("middleware1") handle(req) end end function middleware2(handle) function(req) println("middleware2") handle(req) end end # set middleware at the router level math = router("math", middleware=[middleware1]) # set middleware at the route level @get math("/divide/{a}/{b}", middleware=[middleware2]) function(req, a::Float64, b::Float64) return a / b end # set application level middleware serve(middleware=[CorsMiddleware, AuthMiddleware]) ``` ## Custom Response Serializers If you don't want to use Kitten's default response serializer, you can turn it off and add your own! Just create your own special middleware function to serialize the response and add it at the end of your own middleware chain. Both `serve()` and `serveparallel()` have a `serialize` keyword argument which can toggle off the default serializer. ```julia using Kitten using HTTP using JSON3 @get "/divide/{a}/{b}" function(req::HTTP.Request, a::Float64, b::Float64) return a / b end # This is just a regular middleware function function myserializer(handle) function(req) try response = handle(req) # convert all responses to JSON return HTTP.Response(200, [], body=JSON3.write(response)) catch error @error "ERROR: " exception=(error, catch_backtrace()) return HTTP.Response(500, "The Server encountered a problem") end end end # make sure 'myserializer' is the last middleware function in this list serve(middleware=[myserializer], serialize=false) ``` ## Autogenerated Docs with Swagger Swagger documentation is automatically generated for each route you register in your application. Only the route name, parameter types, and 200 & 500 responses are automatically created for you by default. You can view your generated documentation at `/docs`, and the schema can be found under `/docs/schema`. Both of these values can be changed to whatever you want using the `configdocs()` function. You can also opt out of autogenerated docs entirely by calling the `disabledocs()` function before starting your application. To add additional details you can either use the built-in `mergeschema()` or `setschema()` functions to directly modify the schema yourself or merge the generated schema from the `SwaggerMarkdown.jl` package (I'd recommend the latter) Below is an example of how to merge the schema generated from the `SwaggerMarkdown.jl` package. ```julia using Kitten using SwaggerMarkdown # Here's an example of how you can merge autogenerated docs from SwaggerMarkdown.jl into your api @swagger """ /divide/{a}/{b}: get: description: Return the result of a / b parameters: - name: a in: path required: true description: this is the value of the numerator schema: type : number responses: '200': description: Successfully returned an number. """ @get "/divide/{a}/{b}" function (req, a::Float64, b::Float64) return a / b end # title and version are required info = Dict("title" => "My Demo Api", "version" => "1.0.0") openApi = OpenAPI("3.0", info) swagger_document = build(openApi) # merge the SwaggerMarkdown schema with the internal schema mergeschema(swagger_document) # start the web server serve() ``` Below is an example of how to manually modify the schema ```julia using Kitten using SwaggerMarkdown # Only the basic information is parsed from this route when generating docs @get "/multiply/{a}/{b}" function (req, a::Float64, b::Float64) return a * b end # Here's an example of how to update a part of the schema yourself mergeschema("/multiply/{a}/{b}", Dict( "get" => Dict( "description" => "return the result of a * b" ) ) ) # Here's another example of how to update a part of the schema yourself, but this way allows you to modify other properties defined at the root of the schema (title, summary, etc.) mergeschema( Dict( "paths" => Dict( "/multiply/{a}/{b}" => Dict( "get" => Dict( "description" => "return the result of a * b" ) ) ) ) ) ``` # API Reference (macros) #### @get, @post, @put, @patch, @delete ```julia @get(path, func) ``` | Parameter | Type | Description | | :-------- | :--------------------- | :----------------------------------------------- | | `path` | `string` or `router()` | **Required**. The route to register | | `func` | `function` | **Required**. The request handler for this route | Used to register a function to a specific endpoint to handle that corresponding type of request #### @route ```julia @route(methods, path, func) ``` | Parameter | Type | Description | | :-------- | :--------------------- | :----------------------------------------------------------------- | | `methods` | `array` | **Required**. The types of HTTP requests to register to this route | | `path` | `string` or `router()` | **Required**. The route to register | | `func` | `function` | **Required**. The request handler for this route | Low-level macro that allows a route to be handle multiple request types #### staticfiles ```julia staticfiles(folder, mount) ``` | Parameter | Type | Description | | :------------ | :--------- | :------------------------------------------------------------- | | `folder` | `string` | **Required**. The folder to serve files from | | `mountdir` | `string` | The root endpoint to mount files under (default is "static") | | `set_headers` | `function` | Customize the http response headers when returning these files | | `loadfile` | `function` | Customize behavior when loading files | Serve all static files within a folder. This function recursively searches a directory and mounts all files under the mount directory using their relative paths. #### dynamicfiles ```julia dynamicfiles(folder, mount) ``` | Parameter | Type | Description | | :------------ | :--------- | :------------------------------------------------------------- | | `folder` | `string` | **Required**. The folder to serve files from | | `mountdir` | `string` | The root endpoint to mount files under (default is "static") | | `set_headers` | `function` | Customize the http response headers when returning these files | | `loadfile` | `function` | Customize behavior when loading files | Serve all static files within a folder. This function recursively searches a directory and mounts all files under the mount directory using their relative paths. The file is loaded on each request, potentially picking up any file changes. ### Request helper functions #### html() ```julia html(content, status, headers) ``` | Parameter | Type | Description | | :-------- | :-------- | :---------------------------------------------------------------------------------------------------- | | `content` | `string` | **Required**. The string to be returned as HTML | | `status` | `integer` | The HTTP response code (default is 200) | | `headers` | `dict` | The headers for the HTTP response (default has content-type header set to "text/html; charset=utf-8") | Helper function to designate when content should be returned as HTML #### queryparams() ```julia queryparams(request) ``` | Parameter | Type | Description | | :-------- | :------------- | :------------------------------------ | | `req` | `HTTP.Request` | **Required**. The HTTP request object | Returns the query parameters from a request as a Dict() ### Body Functions #### text() ```julia text(request) ``` | Parameter | Type | Description | | :-------- | :------------- | :------------------------------------ | | `req` | `HTTP.Request` | **Required**. The HTTP request object | Returns the body of a request as a string #### binary() ```julia binary(request) ``` | Parameter | Type | Description | | :-------- | :------------- | :------------------------------------ | | `req` | `HTTP.Request` | **Required**. The HTTP request object | Returns the body of a request as a binary file (returns a vector of `UInt8`s) #### json() ```julia json(request, classtype) ``` | Parameter | Type | Description | | :---------- | :------------- | :----------------------------------------- | | `req` | `HTTP.Request` | **Required**. The HTTP request object | | `classtype` | `struct` | A struct to deserialize a JSON object into | Deserialize the body of a request into a julia struct ## License MIT License, see [LICENSE.md](./LICENSE.md) for more information. Migrated from [Oxygen.jl](https://oxygenframework.github.io/Oxygen.jl/stable/) and modified to work with JuliaKit project.
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
docs
872
# Api Documentation for Kitten.jl ## Starting the webserver ```@docs serve serveparallel ``` ## Routing ```@docs @get(path, func) @post(path, func) @put(path, func) @patch(path, func) @delete(path, func) @route(methods, path, func) get(path, func) post(path, func) put(path, func) patch(path, func) delete(path, func) route(methods, path, func) ``` ## Mounting Files ```@docs @staticfiles @dynamicfiles staticfiles dynamicfiles ``` ## Autogenerated Docs ```@docs configdocs enabledocs disabledocs isdocsenabled mergeschema setschema getschema ``` ## Helper functions ```@docs queryparams formdata html text file xml js json css binary ``` ## Repeat Tasks & Cron Scheduling ```@docs @cron starttasks stoptasks cleartasks startcronjobs stopcronjobs clearcronjobs clearcronjobs ``` ## Extra's ```@docs router internalrequest redirect terminate resetstate ```
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
docs
40835
# Kitten.jl ## About Kitten is a micro-framework built on top of the HTTP.jl library. Breathe easy knowing you can quickly spin up a web server with abstractions you're already familiar with. ## Contact Need Help? Feel free to reach out on our social media channels. ## Features - Straightforward routing - Real-time Metrics Dashboard - Auto-generated swagger documentation - Out-of-the-box JSON serialization & deserialization (customizable) - Type definition support for path parameters - Request Extractors - Multiple Instance Support - Multithreading support - Websockets, Streaming, and Server-Sent Events - Cron Scheduling (on endpoints & functions) - Middleware chaining (at the application, router, and route levels) - Static & Dynamic file hosting - Templating Support - Plotting Support - Protocol Buffer Support - Route tagging - Repeat tasks ## Installation ```julia pkg> add Kitten ``` ## Minimalistic Example Create a web-server with very few lines of code ```julia using Kitten using HTTP @get "/greet" function(req::HTTP.Request) return "hello world!" end # start the web server serve() ``` ## Handlers Handlers are used to connect your code to the server in a clean & straightforward way. They assign a url to a function and invoke the function when an incoming request matches that url. - Handlers can be imported from other modules and distributed across multiple files for better organization and modularity - All handlers have equivalent macro & function implementations and support `do..end` block syntax - The type of first argument is used to identify what kind of handler is being registered - This package assumes it's a `Request` handler by default when no type information is provided There are 3 types of supported handlers: - `Request` Handlers - `Stream` Handlers - `Websocket` Handlers ```julia using HTTP using Kitten # Request Handler @get "/" function(req::HTTP.Request) ... end # Stream Handler @stream "/stream" function(stream::HTTP.Stream) ... end # Websocket Handler @websocket "/ws" function(ws::HTTP.WebSocket) ... end ``` They are just functions which means there are many ways that they can be expressed and defined. Below is an example of several different ways you can express and assign a `Request` handler. ```julia @get "/greet" function() "hello world!" end @get("/gruessen") do "Hallo Welt!" end @get "/saluer" () -> begin "Bonjour le monde!" end @get "/saludar" () -> "Β‘Hola Mundo!" @get "/salutare" f() = "ciao mondo!" # This function can be declared in another module function subtract(req, a::Float64, b::Float64) return a - b end # register foreign request handlers like this @get "/subtract/{a}/{b}" subtract ``` <details> <summary><b>More Handler Docs</b></summary> ### Request Handlers Request handlers are used to handle HTTP requests. They are defined using macros or their function equivalents, and accept a `HTTP.Request` object as the first argument. These handlers support both function and do-block syntax. - The default Handler when no type information is provided - Routing Macros: `@get`, `@post`, `@put`, `@patch`, `@delete`, `@route` - Routing Functions: `get()`, `post()`, `put()`, `patch()`, `delete()`, `route()` ### Stream Handlers Stream handlers are used to stream data. They are defined using the `@stream` macro or the `stream()` function and accept a `HTTP.Stream` object as the first argument. These handlers support both function and do-block syntax. - `@stream` and `stream()` don't require a type definition on the first argument, they assume it's a stream. - `Stream` handlers can be assigned with standard routing macros & functions: `@get`, `@post`, etc - You need to explicitly include the type definition so Kitten can identify this as a `Stream` handler ### Websocket Handlers Websocket handlers are used to handle websocket connections. They are defined using the `@websocket` macro or the `websocket()` function and accept a `HTTP.WebSocket` object as the first argument. These handlers support both function and do-block syntax. - `@websocket` and `websocket()` don't require a type definition on the first argument, they assume it's a websocket. - `Websocket` handlers can also be assigned with the `@get` macro or `get()` function, because the websocket protocol requires a `GET` request to initiate the handshake. - You need to explicitly include the type definition so Kitten can identify this as a `Websocket` handler </details> ## Routing Macro & Function Syntax There are two primary ways to register your request handlers: the standard routing macros or the routing functions which utilize the do-block syntax. For each routing macro, we now have a an equivalent routing function ```julia @get -> get() @post -> post() @put -> put() @patch -> patch() @delete -> delete() @route -> route() ``` The only practical difference between the two is that the routing macros are called during the precompilation stage, whereas the routing functions are only called when invoked. (The routing macros call the routing functions under the hood) ```julia # Routing Macro syntax @get "/add/{x}/{y}" function(request::HTTP.Request, x::Int, y::Int) x + y end # Routing Function syntax get("/add/{x}/{y}") do request::HTTP.Request, x::Int, y::Int x + y end ``` ## Render Functions Kitten, by default, automatically identifies the Content-Type of the return value from a request handler when building a Response. This default functionality is quite useful, but it does have an impact on performance. In situations where the return type is known, It's recommended to use one of the pre-existing render functions to speed things up. Here's a list of the currently supported render functions: `html`, `text`, `json`, `file`, `xml`, `js`, `css`, `binary` Below is an example of how to use these functions: ```julia using Kitten get("/html") do html("<h1>Hello World</h1>") end get("/text") do text("Hello World") end get("/json") do json(Dict("message" => "Hello World")) end serve() ``` In most cases, these functions accept plain strings as inputs. The only exceptions are the `binary` function, which accepts a `Vector{UInt8}`, and the `json` function which accepts any serializable type. - Each render function accepts a status and custom headers. - The Content-Type and Content-Length headers are automatically set by these render functions ## Path parameters Path parameters are declared with braces and are passed directly to your request handler. ```julia using Kitten # use path params without type definitions (defaults to Strings) @get "/add/{a}/{b}" function(req, a, b) return parse(Float64, a) + parse(Float64, b) end # use path params with type definitions (they are automatically converted) @get "/multiply/{a}/{b}" function(req, a::Float64, b::Float64) return a * b end # The order of the parameters doesn't matter (just the name matters) @get "/subtract/{a}/{b}" function(req, b::Int64, a::Int64) return a - b end # start the web server serve() ``` ## Query parameters Query parameters can be declared directly inside of your handlers signature. Any parameter that isn't mentioned inside the route path is assumed to be a query parameter. - If a default value is not provided, it's assumed to be a required parameter ```julia @get "/query" function(req::HTTP.Request, a::Int, message::String="hello world") return (a, message) end ``` Alternatively, you can use the `queryparams()` function to extract the raw values from the url as a dictionary. ```julia @get "/query" function(req::HTTP.Request) return queryparams(req) end ``` ## HTML Forms Use the `formdata()` function to extract and parse the form data from the body of a request. This function returns a dictionary of key-value pairs from the form ```julia using Kitten # Setup a basic form @get "/" function() html(""" <form action="/form" method="post"> <label for="firstname">First name:</label><br> <input type="text" id="firstname" name="firstname"><br> <label for="lastname">Last name:</label><br> <input type="text" id="lastname" name="lastname"><br><br> <input type="submit" value="Submit"> </form> """) end # Parse the form data and return it @post "/form" function(req) data = formdata(req) return data end serve() ``` ## Return JSON All objects are automatically deserialized into JSON using the JSON3 library ```julia using Kitten using HTTP @get "/data" function(req::HTTP.Request) return Dict("message" => "hello!", "value" => 99.3) end # start the web server serve() ``` ## Deserialize & Serialize custom structs Kitten provides some out-of-the-box serialization & deserialization for most objects but requires the use of StructTypes when converting structs ```julia using Kitten using HTTP using StructTypes struct Animal id::Int type::String name::String end # Add a supporting struct type definition so JSON3 can serialize & deserialize automatically StructTypes.StructType(::Type{Animal}) = StructTypes.Struct() @get "/get" function(req::HTTP.Request) # serialize struct into JSON automatically (because we used StructTypes) return Animal(1, "cat", "whiskers") end @post "/echo" function(req::HTTP.Request) # deserialize JSON from the request body into an Animal struct animal = json(req, Animal) # serialize struct back into JSON automatically (because we used StructTypes) return animal end # start the web server serve() ``` ## Extractors Kitten comes with several built-in extractors designed to reduce the amount of boilerplate required to serialize inputs to your handler functions. By simply defining a struct and specifying the data source, these extractors streamline the process of data ingestion & validation through a uniform api. - The serialized data is accessible through the `payload` property - Can be used alongside other parameters and extractors - Default values can be assigned when defined with the `@kwdef` macro - Includes both global and local validators - Struct definitions can be deeply nested Supported Extractors: - `Path` - extracts from path parameters - `Query` - extracts from query parameters, - `Header` - extracts from request headers - `Form` - extracts form data from the request body - `Body` - serializes the entire request body to a given type (String, Float64, etc..) - `ProtoBuffer` - extracts the `ProtoBuf` message from the request body (available through a package extension) - `Json` - extracts json from the request body - `JsonFragment` - extracts a "fragment" of the json body using the parameter name to identify and extract the corresponding top-level key #### Using Extractors & Parameters In this example we show that the `Path` extractor can be used alongside regular path parameters. This Also works with regular query parameters and the `Query` extractor. ```julia struct Add b::Int c::Int end @get "/add/{a}/{b}/{c}" function(req, a::Int, pathparams::Path{Add}) add = pathparams.payload # access the serialized payload return a + add.b + add.c end ``` #### Default Values Default values can be setup with structs using the `@kwdef` macro. ```julia @kwdef struct Pet name::String age::Int = 10 end @post "/pet" function(req, params::Json{Pet}) return params.payload # access the serialized payload end ``` #### Validation On top of serializing incoming data, you can also define your own validation rules by using the `validate` function. In the example below we show how to use both `global` and `local` validators in your code. - Validators are completely optional - During the validation phase, Kitten will call the `global` validator before running a `local` validator. ```julia import Kitten: validate struct Person name::String age::Int end # Define a global validator validate(p::Person) = p.age >= 0 # Only the global validator is ran here @post "/person" function(req, newperson::Json{Person}) return newperson.payload end # In this case, both global and local validators are ran (this also makes sure the person is age 21+) # You can also use this sytnax instead: Json(Person, p -> p.age >= 21) @post "/adult" function(req, newperson = Json{Person}(p -> p.age >= 21)) return newperson.payload end ``` ## Interpolating variables into endpoints You can interpolate variables directly into the paths, which makes dynamically registering routes a breeze (Thanks to @anandijain for the idea) ```julia using Kitten operations = Dict("add" => +, "multiply" => *) for (pathname, operator) in operations @get "/$pathname/{a}/{b}" function (req, a::Float64, b::Float64) return operator(a, b) end end # start the web server serve() ``` ## Routers The `router()` function is an HOF (higher order function) that allows you to reuse the same path prefix & properties across multiple endpoints. This is helpful when your api starts to grow and you want to keep your path operations organized. Below are the arguments the `router()` function can take: ```julia router(prefix::String; tags::Vector, middleware::Vector, interval::Real, cron::String) ``` - `tags` - are used to organize endpoints in the autogenerated docs - `middleware` - is used to setup router & route-specific middleware - `interval` - is used to support repeat actions (_calling a request handler on a set interval in seconds_) - `cron` - is used to specify a cron expression that determines when to call the request handler. ```julia using Kitten # Any routes that use this router will be automatically grouped # under the 'math' tag in the autogenerated documenation math = router("/math", tags=["math"]) # You can also assign route specific tags @get math("/multiply/{a}/{b}", tags=["multiplication"]) function(req, a::Float64, b::Float64) return a * b end @get math("/divide/{a}/{b}") function(req, a::Float64, b::Float64) return a / b end serve() ``` ## Cron Scheduling Kitten comes with a built-in cron scheduling system that allows you to call endpoints and functions automatically when the cron expression matches the current time. When a job is scheduled, a new task is created and runs in the background. Each task uses its given cron expression and the current time to determine how long it needs to sleep before it can execute. The cron parser in Kitten is based on the same specifications as the one used in Spring. You can find more information about this on the [Spring Cron Expressions](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/support/CronExpression.html) page. ### Cron Expression Syntax The following is a breakdown of what each parameter in our cron expression represents. While our specification closely resembles the one defined by Spring, it's not an exact 1-to-1 match. ``` The string has six single space-separated time and date fields: β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ second (0-59) β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ minute (0 - 59) β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ hour (0 - 23) β”‚ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ day of the month (1 - 31) β”‚ β”‚ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ month (1 - 12) (or JAN-DEC) β”‚ β”‚ β”‚ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ day of the week (1 - 7) β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ (Monday is 1, Tue is 2... and Sunday is 7) β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ * * * * * * ``` Partial expressions are also supported, which means that subsequent expressions can be left out (they are defaulted to `'*'`). ```julia # In this example we see only the `seconds` part of the expression is defined. # This means that all following expressions are automatically defaulted to '*' expressions @cron "*/2" function() println("runs every 2 seconds") end ``` ### Scheduling Endpoints The `router()` function has a keyword argument called `cron`, which accepts a cron expression that determines when an endpoint is called. Just like the other keyword arguments, it can be reused by endpoints that share routers or be overridden by inherited endpoints. ```julia # execute at 8, 9 and 10 o'clock of every day. @get router("/cron-example", cron="0 0 8-10 * * *") function(req) println("here") end # execute this endpoint every 5 seconds (whenever current_seconds % 5 == 0) every5 = router("/cron", cron="*/5") # this endpoint inherits the cron expression @get every5("/first") function(req) println("first") end # Now this endpoint executes every 2 seconds ( whenever current_seconds % 2 == 0 ) instead of every 5 @get every5("/second", cron="*/2") function(req) println("second") end ``` ### Scheduling Functions In addition to scheduling endpoints, you can also use the new `@cron` macro to schedule functions. This is useful if you want to run code at specific times without making it visible or callable in the API. ```julia @cron "*/2" function() println("runs every 2 seconds") end @cron "0 0/30 8-10 * * *" function() println("runs at 8:00, 8:30, 9:00, 9:30, 10:00 and 10:30 every day") end ``` ### Starting & Stopping Cron Jobs When you run `serve()` or `serveparallel()`, all registered cron jobs are automatically started. If the server is stopped or killed, all running jobs will also be terminated. You can stop the server and all repeat tasks and cron jobs by calling the `terminate()` function or manually killing the server with `ctrl+C`. In addition, Kitten provides utility functions to manually start and stop cron jobs: `startcronjobs()` and `stopcronjobs()`. These functions can be used outside of a web server as well. ## Repeat Tasks Repeat tasks provide a simple api to run a function on a set interval. There are two ways to register repeat tasks: - Through the `interval` parameter in a `router()` - Using the `@repeat` macro **It's important to note that request handlers that use this property can't define additional function parameters outside of the default `HTTP.Request` parameter.** In the example below, the `/repeat/hello` endpoint is called every 0.5 seconds and `"hello"` is printed to the console each time. The `router()` function has an `interval` parameter which is used to call a request handler on a set interval (in seconds). ```julia using Kitten taskrouter = router("/repeat", interval=0.5, tags=["repeat"]) @get taskrouter("/hello") function() println("hello") end # you can override properties by setting route specific values @get taskrouter("/bonjour", interval=1.5) function() println("bonjour") end serve() ``` Below is an example of how to register a repeat task outside of the router ```julia @repeat 1.5 function() println("runs every 1.5 seconds") end # you can also "name" a repeat task @repeat 5 "every-five" function() println("runs every 5 seconds") end ``` When the server is ran, all tasks are started automatically. But the module also provides utilities to have more fine-grained control over the running tasks using the following functions: `starttasks()`, `stoptasks()`, and `cleartasks()` ## Multiple Instances In some advanced scenarios, you might need to spin up multiple web severs within the same module on different ports. Kitten provides both a static and dynamic way to create multiple instances of a web server. As a general rule of thumb, if you know how many instances you need ahead of time it's best to go with the static approach. ### Static: multiple instance's with `@oxidise` Kitten provides a new macro which makes it possible to setup and run multiple instances. It generates methods and binds them to a new internal state for the current module. In the example below, two simple servers are defined within modules A and B and are started in the parent module. Both modules contain all of the functions exported from Kitten which can be called directly as shown below. ```julia module A using Kitten; @oxidise get("/") do text("server A") end end module B using Kitten; @oxidise get("/") do text("server B") end end try # start both instances A.serve(port=8001, async=true) B.serve(port=8002, async=false) finally # shut down if we `Ctrl+C` A.terminate() B.terminate() end ``` ### Dynamic: multiple instance's with `instance()` The `instance` function helps you create a completely independent instance of an Kitten web server at runtime. It works by dynamically creating a julia module at runtime and loading the Kitten code within it. All of the same methods from Kitten are available under the named instance. In the example below we can use the `get`, and `serve` by simply using dot syntax on the `app1` variable to access the underlying methods. ```julia using Kitten ######### Setup the first app ######### app1 = instance() app1.get("/") do text("server A") end ######### Setup the second app ######### app2 = instance() app2.get("/") do text("server B") end ######### Start both instances ######### try # start both servers together app1.serve(port=8001, async=true) app2.serve(port=8002) finally # clean it up app1.terminate() app2.terminate() end ``` ## Multithreading & Parallelism For scenarios where you need to handle higher amounts of traffic, you can run Kitten in a multithreaded mode. In order to utilize this mode, julia must have more than 1 thread to work with. You can start a julia session with 4 threads using the command below ```shell julia --threads 4 ``` `serveparallel()` Starts the webserver in streaming mode and handles requests in a cooperative multitasking approach. This function uses `Threads.@spawn` to schedule a new task on any available thread. Meanwhile, @async is used inside this task when calling each request handler. This allows the task to yield during I/O operations. ```julia using Kitten using StructTypes using Base.Threads # Make the Atomic struct serializable StructTypes.StructType(::Type{Atomic{Int64}}) = StructTypes.Struct() x = Atomic{Int64}(0); @get "/show" function() return x end @get "/increment" function() atomic_add!(x, 1) return x end # start the web server in parallel mode serveparallel() ``` ## Protocol Buffers Kitten includes an extension for the [ProtoBuf.jl](https://github.com/JuliaIO/ProtoBuf.jl) package. This extension provides a `protobuf()` function, simplifying the process of working with Protocol Buffers in the context of web server. For a better understanding of this package, please refer to its official documentation. This function has overloads for the following scenarios: - Decoding a protobuf message from the body of an HTTP request. - Encoding a protobuf message into the body of an HTTP request. - Encoding a protobuf message into the body of an HTTP response. ```julia using HTTP using ProtoBuf using Kitten # The generated classes need to be created ahead of time (check the protobufs) include("people_pb.jl"); using .people_pb: People, Person # Decode a Protocol Buffer Message @post "/count" function(req::HTTP.Request) # decode the request body into a People object message = protobuf(req, People) # count the number of Person objects return length(message.people) end # Encode & Return Protocol Buffer message @get "/get" function() message = People([ Person("John Doe", 20), Person("Alice", 30), Person("Bob", 35) ]) # seralize the object inside the body of a HTTP.Response return protobuf(message) end ``` The following is an example of a schema that was used to create the necessary Julia bindings. These bindings allow for the encoding and decoding of messages in the above example. ```protobuf syntax = "proto3"; message Person { string name = 1; sint32 age = 2; } message People { repeated Person people = 1; } ``` ## Plotting Kitten is equipped with several package extensions that enhance its plotting capabilities. These extensions make it easy to return plots directly from request handlers. All operations are performed in-memory using an IOBuffer and return a `HTTP.Response` Supported Packages and their helper utils: - CairoMakie.jl: `png`, `svg`, `pdf`, `html` - WGLMakie.jl: `html` - Bonito.jl: `html` #### CairoMakie.jl ```julia using CairoMakie: heatmap using Kitten @get "/cairo" function() fig, ax, pl = heatmap(rand(50, 50)) png(fig) end serve() ``` #### WGLMakie.jl ```julia using Bonito using WGLMakie: heatmap using Kitten using Kitten: html # Bonito also exports html @get "/wgl" function() fig = heatmap(rand(50, 50)) html(fig) end serve() ``` #### Bonito.jl ```julia using Bonito using WGLMakie: heatmap using Kitten using Kitten: html # Bonito also exports html @get "/bonito" function() app = App() do return DOM.div( DOM.h1("Random 50x50 Heatmap"), DOM.div(heatmap(rand(50, 50))) ) end return html(app) end serve() ``` ## Templating Rather than building an internal engine for templating or adding additional dependencies, Kitten provides two package extensions to support `Mustache.jl` and `OteraEngine.jl` templates. Kitten provides a simple wrapper api around both packages that makes it easy to render templates from strings, templates, and files. This wrapper api returns a `render` function which accepts a dictionary of inputs to fill out the template. In all scenarios, the rendered template is returned inside a HTTP.Response object ready to get served by the api. By default, the mime types are auto-detected either by looking at the content of the template or the extension name on the file. If you know the mime type you can pass it directly through the `mime_type` keyword argument to skip the detection process. ### Mustache Templating Please take a look at the [Mustache.jl](https://jverzani.github.io/Mustache.jl/dev/) documentation to learn the full capabilities of the package Example 1: Rendering a Mustache Template from a File ```julia using Mustache using Kitten # Load the Mustache template from a file and create a render function render = mustache("./templates/greeting.txt", from_file=false) @get "/mustache/file" function() data = Dict("name" => "Chris") return render(data) # This will return an HTML.Response with the rendered template end ``` Example 2: Specifying MIME Type for a plain string Mustache Template ```julia using Mustache using Kitten # Define a Mustache template (both plain strings and mustache templates are supported) template_str = "Hello, {{name}}!" # Create a render function, specifying the MIME type as text/plain render = mustache(template_str, mime_type="text/plain") # mime_type keyword arg is optional @get "/plain/text" function() data = Dict("name" => "Chris") return render(data) # This will return a plain text response with the rendered template end ``` ### Otera Templating Please take a look at the [OteraEngine.jl](https://mommawatasu.github.io/OteraEngine.jl/dev/tutorial/#API) documentation to learn the full capabilities of the package Example 1: Rendering an Otera Template with Logic and Loops ```julia using OteraEngine using Kitten # Define an Otera template template_str = """ <html> <head><title>{{ title }}</title></head> <body> {% for name in names %} Hello {{ name }}<br> {% end %} </body> </html> """ # Create a render function for the Otera template render = otera(template_str) @get "/otera/loop" function() data = Dict("title" => "Greetings", "names" => ["Alice", "Bob", "Chris"]) return render(data) # This will return an HTML.Response with the rendered template end ``` In this example, an Otera template is defined with a for-loop that iterates over a list of names, greeting each name. Example 2: Running Julia Code in Otera Template ```julia using OteraEngine using Kitten # Define an Otera template with embedded Julia code template_str = """ The square of {{ number }} is {< number^2 >}. """ # Create a render function for the Otera template render = otera(template_str) @get "/otera/square" function() data = Dict("number" => 5) return render(data) # This will return an HTML.Response with the rendered template end ``` In this example, an Otera template is defined with embedded Julia code that calculates the square of a given number. ## Mounting Static Files You can mount static files using this handy function which recursively searches a folder for files and mounts everything. All files are loaded into memory on startup. ```julia using Kitten # mount all files inside the "content" folder under the "/static" path staticfiles("content", "static") # start the web server serve() ``` ## Mounting Dynamic Files Similar to staticfiles, this function mounts each path and re-reads the file for each request. This means that any changes to the files after the server has started will be displayed. ```julia using Kitten # mount all files inside the "content" folder under the "/dynamic" path dynamicfiles("content", "dynamic") # start the web server serve() ``` ## Performance Tips Disabling the internal logger can provide some massive performance gains, which can be helpful in some scenarios. Anecdotally, i've seen a 2-3x speedup in `serve()` and a 4-5x speedup in `serveparallel()` performance. ```julia # This is how you disable internal logging in both modes serve(access_log=nothing) serveparallel(access_log=nothing) ``` ## Logging Kitten provides a default logging format but allows you to customize the format using the `access_log` parameter. This functionality is available in both the `serve()` and `serveparallel()` functions. You can read more about the logging options [here](https://juliaweb.github.io/HTTP.jl/stable/reference/#HTTP.@logfmt_str) ```julia # Uses the default logging format serve() # Customize the logging format serve(access_log=logfmt"[$time_iso8601] \"$request\" $status") # Disable internal request logging serve(access_log=nothing) ``` ## Middleware Middleware functions make it easy to create custom workflows to intercept all incoming requests and outgoing responses. They are executed in the same order they are passed in (from left to right). They can be set at the application, router, and route layer with the `middleware` keyword argument. All middleware is additive and any middleware defined in these layers will be combined and executed. Middleware will always be executed in the following order: ``` application -> router -> route ``` Now lets see some middleware in action: ```julia using Kitten using HTTP const CORS_HEADERS = [ "Access-Control-Allow-Origin" => "*", "Access-Control-Allow-Headers" => "*", "Access-Control-Allow-Methods" => "POST, GET, OPTIONS" ] # https://juliaweb.github.io/HTTP.jl/stable/examples/#Cors-Server function CorsMiddleware(handler) return function(req::HTTP.Request) println("CORS middleware") # determine if this is a pre-flight request from the browser if HTTP.method(req)=="OPTIONS" return HTTP.Response(200, CORS_HEADERS) else return handler(req) # passes the request to the AuthMiddleware end end end function AuthMiddleware(handler) return function(req::HTTP.Request) println("Auth middleware") # ** NOT an actual security check ** # if !HTTP.headercontains(req, "Authorization", "true") return HTTP.Response(403) else return handler(req) # passes the request to your application end end end function middleware1(handle) function(req) println("middleware1") handle(req) end end function middleware2(handle) function(req) println("middleware2") handle(req) end end # set middleware at the router level math = router("math", middleware=[middleware1]) # set middleware at the route level @get math("/divide/{a}/{b}", middleware=[middleware2]) function(req, a::Float64, b::Float64) return a / b end # set application level middleware serve(middleware=[CorsMiddleware, AuthMiddleware]) ``` ## Custom Response Serializers If you don't want to use Kitten's default response serializer, you can turn it off and add your own! Just create your own special middleware function to serialize the response and add it at the end of your own middleware chain. Both `serve()` and `serveparallel()` have a `serialize` keyword argument which can toggle off the default serializer. ```julia using Kitten using HTTP using JSON3 @get "/divide/{a}/{b}" function(req::HTTP.Request, a::Float64, b::Float64) return a / b end # This is just a regular middleware function function myserializer(handle) function(req) try response = handle(req) # convert all responses to JSON return HTTP.Response(200, [], body=JSON3.write(response)) catch error @error "ERROR: " exception=(error, catch_backtrace()) return HTTP.Response(500, "The Server encountered a problem") end end end # make sure 'myserializer' is the last middleware function in this list serve(middleware=[myserializer], serialize=false) ``` ## Autogenerated Docs with Swagger Swagger documentation is automatically generated for each route you register in your application. Only the route name, parameter types, and 200 & 500 responses are automatically created for you by default. You can view your generated documentation at `/docs`, and the schema can be found under `/docs/schema`. Both of these values can be changed to whatever you want using the `configdocs()` function. You can also opt out of autogenerated docs entirely by calling the `disabledocs()` function before starting your application. To add additional details you can either use the built-in `mergeschema()` or `setschema()` functions to directly modify the schema yourself or merge the generated schema from the `SwaggerMarkdown.jl` package (I'd recommend the latter) Below is an example of how to merge the schema generated from the `SwaggerMarkdown.jl` package. ```julia using Kitten using SwaggerMarkdown # Here's an example of how you can merge autogenerated docs from SwaggerMarkdown.jl into your api @swagger """ /divide/{a}/{b}: get: description: Return the result of a / b parameters: - name: a in: path required: true description: this is the value of the numerator schema: type : number responses: '200': description: Successfully returned an number. """ @get "/divide/{a}/{b}" function (req, a::Float64, b::Float64) return a / b end # title and version are required info = Dict("title" => "My Demo Api", "version" => "1.0.0") openApi = OpenAPI("3.0", info) swagger_document = build(openApi) # merge the SwaggerMarkdown schema with the internal schema mergeschema(swagger_document) # start the web server serve() ``` Below is an example of how to manually modify the schema ```julia using Kitten using SwaggerMarkdown # Only the basic information is parsed from this route when generating docs @get "/multiply/{a}/{b}" function (req, a::Float64, b::Float64) return a * b end # Here's an example of how to update a part of the schema yourself mergeschema("/multiply/{a}/{b}", Dict( "get" => Dict( "description" => "return the result of a * b" ) ) ) # Here's another example of how to update a part of the schema yourself, but this way allows you to modify other properties defined at the root of the schema (title, summary, etc.) mergeschema( Dict( "paths" => Dict( "/multiply/{a}/{b}" => Dict( "get" => Dict( "description" => "return the result of a * b" ) ) ) ) ) ``` # API Reference (macros) #### @get, @post, @put, @patch, @delete ```julia @get(path, func) ``` | Parameter | Type | Description | | :-------- | :--------------------- | :----------------------------------------------- | | `path` | `string` or `router()` | **Required**. The route to register | | `func` | `function` | **Required**. The request handler for this route | Used to register a function to a specific endpoint to handle that corresponding type of request #### @route ```julia @route(methods, path, func) ``` | Parameter | Type | Description | | :-------- | :--------------------- | :----------------------------------------------------------------- | | `methods` | `array` | **Required**. The types of HTTP requests to register to this route | | `path` | `string` or `router()` | **Required**. The route to register | | `func` | `function` | **Required**. The request handler for this route | Low-level macro that allows a route to be handle multiple request types #### staticfiles ```julia staticfiles(folder, mount) ``` | Parameter | Type | Description | | :------------ | :--------- | :------------------------------------------------------------- | | `folder` | `string` | **Required**. The folder to serve files from | | `mountdir` | `string` | The root endpoint to mount files under (default is "static") | | `set_headers` | `function` | Customize the http response headers when returning these files | | `loadfile` | `function` | Customize behavior when loading files | Serve all static files within a folder. This function recursively searches a directory and mounts all files under the mount directory using their relative paths. #### dynamicfiles ```julia dynamicfiles(folder, mount) ``` | Parameter | Type | Description | | :------------ | :--------- | :------------------------------------------------------------- | | `folder` | `string` | **Required**. The folder to serve files from | | `mountdir` | `string` | The root endpoint to mount files under (default is "static") | | `set_headers` | `function` | Customize the http response headers when returning these files | | `loadfile` | `function` | Customize behavior when loading files | Serve all static files within a folder. This function recursively searches a directory and mounts all files under the mount directory using their relative paths. The file is loaded on each request, potentially picking up any file changes. ### Request helper functions #### html() ```julia html(content, status, headers) ``` | Parameter | Type | Description | | :-------- | :-------- | :---------------------------------------------------------------------------------------------------- | | `content` | `string` | **Required**. The string to be returned as HTML | | `status` | `integer` | The HTTP response code (default is 200) | | `headers` | `dict` | The headers for the HTTP response (default has content-type header set to "text/html; charset=utf-8") | Helper function to designate when content should be returned as HTML #### queryparams() ```julia queryparams(request) ``` | Parameter | Type | Description | | :-------- | :------------- | :------------------------------------ | | `req` | `HTTP.Request` | **Required**. The HTTP request object | Returns the query parameters from a request as a Dict() ### Body Functions #### text() ```julia text(request) ``` | Parameter | Type | Description | | :-------- | :------------- | :------------------------------------ | | `req` | `HTTP.Request` | **Required**. The HTTP request object | Returns the body of a request as a string #### binary() ```julia binary(request) ``` | Parameter | Type | Description | | :-------- | :------------- | :------------------------------------ | | `req` | `HTTP.Request` | **Required**. The HTTP request object | Returns the body of a request as a binary file (returns a vector of `UInt8`s) #### json() ```julia json(request, classtype) ``` | Parameter | Type | Description | | :---------- | :------------- | :----------------------------------------- | | `req` | `HTTP.Request` | **Required**. The HTTP request object | | `classtype` | `struct` | A struct to deserialize a JSON object into | Deserialize the body of a request into a julia struct
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
docs
7117
# Bigger Applications - Multiple Files If you are building an application or a web API, it's rarely the case that you can put everything on a single file. As your application grows you'll need to spread your application's logic across multiple files. Kitten provides some tools to help you do this while staying organized. Let's say you have an application that looks something like this: ``` app β”œβ”€β”€ src β”‚ β”œβ”€β”€ main.jl β”‚ └── MathOperations.jl β”‚ β”œβ”€β”€ Project.toml └── Manifest.toml ``` ## How to use the `router()` function Let's say you have a file dedicated to handling mathematical operations in the submodule at `/src/MathOperations.jl.` You might want the first part of each path to have the same value and just switch out the subpath to keep things organized in your api. You can use the `router` function to do just that. The `router()` function is an HOF (higher order function) that allows you to reuse the same properties across multiple endpoints. Because the generated router is just a function, they can be exported and shared across multiple files & modules. ```julia using Kitten math = router("/math", tags=["math"]) @get math("/multiply/{a}/{b}", tags=["multiplication"]) function(req, a::Float64, b::Float64) return a * b end @get math("/divide/{a}/{b}") function(req, a::Float64, b::Float64) return a / b end serve() ``` ## Tagging your routes By using the hello router in both endpoints, it passes along all the properties as default values. For example If we look at the routes registered in the application they will look like: ``` /math/multiply/{a}/{b} /math/divide/{a}/{b} ``` Both endpoints in this case will be tagged to the `math` tag and the `/multiply` endpoint will have an additional tag appended just to this endpoint called `multiplication`. These tags are used by Kitten when auto-generating the documentation to organize it by separating the endpoints into sections based off their tags. ## Middleware & `router()` The `router()` function has a `middleware` parameter which takes a vector of middleware functions which are used to intercept all incoming requests & outgoing responses. All middleware is additive and any middleware defined in these layers will be combined and executed. You can assign middleware at three levels: - `application` - `router` - `route` Middleware will always get executed in the following order: ``` application -> router -> route ``` the `application` layer can only be set from the `serve()` and `serveparallel()` functions. While the other two layers can be set using the `router()` function. ```julia # Set middleware at the application level serve(middleware=[]) # Set middleware at the Router level myrouter = router("/router", middleware=[]) # Set middleware at the Route level @get myrouter("/example", middleware=[]) function() return "example" end ``` ### Router Level Middleware At the router level, any middleware defined here will be reused across all other routes that use this router(). In the example below, both `/greet/hello` and `/greet/bonjour` routes will send requests through the same middleware functions before either endpoint is called ```julia function middleware1(handle) function(req) println("this is the 1st middleware function") handle(req) end end # middleware1 is defined at the router level greet = router("/greet", middleware=[middleware1]) @get greet("/hello") function() println("hello") end @get greet("/bonjour") function() println("bonjour") end ``` ### Route Specific Middleware At the route level, you can customize what middleware functions should be applied on a route by route basis. In the example below, the `/greet/hello` route gets both `middleware1` & `middleware2` functions applied to it, while the `/greet/bonjour` route only has `middleware1` function which it inherited from the `greet` router. ```julia function middleware1(handle) function(req) println("this is the 1st middleware function") handle(req) end end function middleware2(handle) function(req) println("this is the 2nd middleware function") handle(req) end end # middleware1 is added at the router level greet = router("/greet", middleware=[middleware1]) # middleware2 is added at the route level @get greet("/hello", middleware=[middleware2]) function() println("hello") end @get greet("/bonjour") function() println("bonjour") end serve() ``` ### Skipping Middleware layers Well, what if we don't want previous layers of middleware to run? By setting `middleware=[]`, it clears all middleware functions at that layer and skips all layers that come before it. These changes are localized and only affect the components where these values are set. For example, setting `middleware=[]` at the: - application layer -> clears the application layer - router layer -> no application middleware is applied to this router - route layer -> no router middleware is applied to this route You can set the router's `middleware` parameter to an empty vector to bypass any application level middleware. In the example below, all requests to endpoints registered to the `greet` router() will skip any application level middleware and get executed directly. ```julia function middleware1(handle) function(req) println("this is the 1st middleware function") handle(req) end end greet = router("/greet", middleware=[]) @get greet("/hello") function() println("hello") end @get greet("/bonjour") function() println("bonjour") end serve(middleware=[middleware1]) ``` ## Repeat Actions The `router()` function has an `interval` parameter which is used to call a request handler on a set interval (in seconds). **It's important to note that request handlers that use this property can't define additional function parameters outside of the default `HTTP.Request` parameter.** In the example below, the `/repeat/hello` endpoint is called every 0.5 seconds and `"hello"` is printed to the console each time. ```julia using Kitten repeat = router("/repeat", interval=0.5, tags=["repeat"]) @get repeat("/hello") function() println("hello") end # you can override properties by setting route specific values @get repeat("/bonjour", interval=1.5) function() println("bonjour") end serve() ``` If you want to call an endpoint with parameters on a set interval, you're better off creating an endpoint to perform the action you want and a second endpoint to call the first on a set interval. ```julia using HTTP using Kitten repeat = router("/repeat", interval=1.5, tags=["repeat"]) @get "/multiply/{a}/{b}" function(req, a::Float64, b::Float64) return a * b end @get repeat("/multiply") function() response = internalrequest(HTTP.Request("GET", "/multiply/3/5")) println(response) return response end serve() ``` The example above will print the response from the `/multiply` endpoint in the console below every 1.5 seconds and should look like this: ``` """ HTTP/1.1 200 OK Content-Type: application/json; charset=utf-8 15.0""" ```
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
docs
3489
# Cron Scheduling Kitten comes with a built-in cron scheduling system that allows you to call endpoints and functions automatically when the cron expression matches the current time. When a job is scheduled, a new task is created and runs in the background. Each task uses its given cron expression and the current time to determine how long it needs to sleep before it can execute. The cron parser in Kitten is based on the same specifications as the one used in Spring. You can find more information about this on the [Spring Cron Expressions](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/support/CronExpression.html) page. ## Cron Expression Syntax The following is a breakdown of what each parameter in our cron expression represents. While our specification closely resembles the one defined by Spring, it's not an exact 1-to-1 match. ``` The string has six single space-separated time and date fields: β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ second (0-59) β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ minute (0 - 59) β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ hour (0 - 23) β”‚ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ day of the month (1 - 31) β”‚ β”‚ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ month (1 - 12) (or JAN-DEC) β”‚ β”‚ β”‚ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ day of the week (1 - 7) β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ (Monday is 1, Tue is 2... and Sunday is 7) β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ * * * * * * ``` Partial expressions are also supported, which means that subsequent expressions can be left out (they are defaulted to `'*'`). ```julia # In this example we see only the `seconds` part of the expression is defined. # This means that all following expressions are automatically defaulted to '*' expressions @cron "*/2" function() println("runs every 2 seconds") end ``` ## Scheduling Endpoints The `router()` function has a keyword argument called `cron`, which accepts a cron expression that determines when an endpoint is called. Just like the other keyword arguments, it can be reused by endpoints that share routers or be overridden by inherited endpoints. ```julia # execute at 8, 9 and 10 o'clock of every day. @get router("/cron-example", cron="0 0 8-10 * * *") function(req) println("here") end # execute this endpoint every 5 seconds (whenever current_seconds % 5 == 0) every5 = router("/cron", cron="*/5") # this endpoint inherits the cron expression @get every5("/first") function(req) println("first") end # Now this endpoint executes every 2 seconds ( whenever current_seconds % 2 == 0 ) instead of every 5 @get every5("/second", cron="*/2") function(req) println("second") end ``` ## Scheduling Functions In addition to scheduling endpoints, you can also use the new `@cron` macro to schedule functions. This is useful if you want to run code at specific times without making it visible or callable in the API. ```julia @cron "*/2" function() println("runs every 2 seconds") end @cron "0 0/30 8-10 * * *" function() println("runs at 8:00, 8:30, 9:00, 9:30, 10:00 and 10:30 every day") end ``` ## Starting & Stopping Cron Jobs When you run `serve()` or `serveparallel()`, all registered cron jobs are automatically started. If the server is stopped or killed, all running jobs will also be terminated. You can stop the server and all repeat tasks and cron jobs by calling the `terminate()` function or manually killing the server with `ctrl+C`. In addition, Kitten provides utility functions to manually start and stop cron jobs: `startcronjobs()` and `stopcronjobs()`. These functions can be used outside of a web server as well.
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
docs
3230
# First Steps In this tutorial, you'll learn about all the core features of Kitten ia a simple step-by-step approach. This guide will be aimed at beginner/intermediate users and will gradually build upon each other. ## Setup your first project Navigate to your projects folder (If you're using and editor like vscode, just open up your project folder `cd /path/to/your/project` Open open a terminal and start the julia repl with this command ``` julia ``` Before we go any further, lets create a new environment for this project. Press the `]` key inside the repl to use Pkg (julia's jult in package manager) you should see something similar to `(v1.7) pkg>` in the repl Activate your current environment ``` pkg> activate . ``` Install the latest version of Kitten and HTTP ``` pkg> add Kitten HTTP ``` Press the backspace button to exit the package manager and return to the julia repl If everything was done correctly, you should see a `Project.toml` and `Manifest.toml` file created in your project folder Next lets create our `src` folder and our `main.jl` file. Once that's complete, our project should ook something like this. ``` project β”œβ”€β”€ src β”‚ β”œβ”€β”€ main.jl β”œβ”€β”€ Project.toml β”œβ”€β”€ Manifest.toml ``` For the duration of this guide, we will be working out of the `src/main.jl` file ## Creating your first web server Here's an example of what a simple Kitten server could look like ```julia module Main using Kitten using HTTP @get "/greet" function(req::HTTP.Request) return "hello world!" end serve() end ``` Start the webserver with: ```julia include("src/main.jl") ``` ## Line by line ```julia using Kitten using HTTP ``` Here we pull in the both libraries our api depends on. The `@get` macro and `serve()` function come from Kitten and the `HTTP.Request` type comes from the HTTP library. Next we move into the core snippet where we define a route for our api. This route is made up of several components. - http method => from `@get` macro (it's a GET request) - path => the endpoint that will get added to our api which is `"/greet"` - request handler => The function that accepts a request and returns a response ```julia @get "/greet" function(req::HTTP.Request) return "hello world!" end ``` Finally at the bottom of our `Main` module we have this function to start up our brand new webserver. This function can take a number of keyword arguments such as the `host` & `port`, which can be helpful if you don't want to use the default values. ```julia serve() ``` For example, you can start your server on port `8000` instead of `8080` which is used by default ```julia serve(port=8000) ``` ## Try out your endpoints You should see the server starting up inside the console. You should be able to hit `http://127.0.0.1:8080/greet` inside your browser and see the following: ``` "hello world!" ``` ## Interactive API documenation Open your browser to http://127.0.0.1:8080/docs Here you'll see the auto-generated documentation for your api. This is done internally by generating a JSON object that conforms to the openapi format. Once generated, you can feed this same schema to libraries like swagger which translate this into an interactive api for you to explore.
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
docs
5053
# OAuth2 with Umbrella.jl [Umbrella.jl](https://github.com/jiachengzhang1/Umbrella.jl) is a simple Julia authentication plugin, it supports Google and GitHub OAuth2 with more to come. Umbrella integrates with Julia web framework such as [Genie.jl](https://github.com/GenieFramework/Genie.jl), [Kitten.jl](https://github.com/JuliaKit/Kitten.jl) or [Mux.jl](https://github.com/JuliaWeb/Mux.jl) effortlessly. ## Prerequisite Before using the plugin, you need to obtain OAuth 2 credentials, see [Google Identity Step 1](https://developers.google.com/identity/protocols/oauth2#1.-obtain-oauth-2.0-credentials-from-the-dynamic_data.setvar.console_name-.), [GitHub: Creating an OAuth App](https://docs.github.com/en/developers/apps/building-oauth-apps/creating-an-oauth-app) for details. ## Installation ```julia pkg> add Umbrella ``` ## Basic Usage Many resources are available describing how OAuth 2 works, please advice [OAuth 2.0](https://oauth.net/2/), [Google Identity](https://developers.google.com/identity/protocols/oauth2/web-server#obtainingaccesstokens), or [GitHub OAuth 2](https://docs.github.com/en/developers/apps/building-oauth-apps/creating-an-oauth-app) for details Follow the steps below to enable OAuth 2 in your application. ### 1. Configuration OAuth 2 required parameters such as `client_id`, `client_secret` and `redirect_uri` need to be configured through `Configuration.Options`. `scopes` is a list of resources the application will access on user's behalf, it is vary from one provider to another. `providerOptions` configures the additional parameters at the redirection step, it is dependent on the provider. ```julia const options = Configuration.Options(; client_id = "", # client id from an OAuth 2 provider client_secret = "", # secret from an OAuth 2 provider redirect_uri = "http://localhost:3000/oauth2/google/callback", success_redirect = "/protected", failure_redirect = "/error", scopes = ["profile", "openid", "email"], providerOptions = GoogleOptions(access_type="online") ) ``` `init` function takes the provider and options, then returns an OAuth 2 instance. Available provider values are `:google`, `:github` and `facebook`. This list is growing as more providers are supported. ```julia oauth2_instance = init(:google, options) ``` The examples will use [Kitten.jl](https://github.com/JuliaKit/Kitten.jl) as the web framework, but the concept is the same for other web frameworks. ### 2. Handle provider redirection Create two endpoints, - `/` serve the login page which, in this case, is a Google OAuth 2 link. - `/oauth2/google` handles redirections to an OAuth 2 server. ```julia @get "/" function () return "<a href='/oauth2/google'>Authenticate with Google</a>" end @get "/oauth2/google" function () oauth2_instance.redirect() end ``` `redirect` function generates the URL using the parameters in step 1, and redirects users to provider's OAuth 2 server to initiate the authentication and authorization process. Once the users consent to grant access to one or more scopes requested by the application, OAuth 2 server responds the `code` for retrieving access token to a callback endpoint. ### 3. Retrieves tokens Finally, create the endpoint handling callback from the OAuth 2 server. The path must be identical to the path in `redirect_uri` from `Configuration.Options`. `token_exchange` function performs two actions, 1. Use `code` responded by the OAuth 2 server to exchange an access token. 2. Get user profile using the access token. A handler is required for access/refresh tokens and user profile handling. ```julia @get "/oauth2/google/callback" function (req) query_params = queryparams(req) code = query_params["code"] oauth2_instance.token_exchange(code, function (tokens, user) # handle tokens and user profile here end ) end ``` ## Full Example ```julia using Kitten using Umbrella using HTTP const oauth_path = "/oauth2/google" const oauth_callback = "/oauth2/google/callback" const options = Configuration.Options(; client_id="", # client id from Google API Console client_secret="", # secret from Google API Console redirect_uri="http://127.0.0.1:8080$(oauth_callback)", success_redirect="/protected", failure_redirect="/no", scopes=["profile", "openid", "email"] ) const google_oauth2 = Umbrella.init(:google, options) @get "/" function() return "<a href='$(oauth_path)'>Authenticate with Google</a>" end @get oauth_path function() # this handles the Google oauth2 redirect in the background google_oauth2.redirect() end @get oauth_callback function(req) query_params = queryparams(req) code = query_params["code"] # handle tokens and user details google_oauth2.token_exchange(code, function (tokens::Google.Tokens, user::Google.User) println(tokens.access_token) println(tokens.refresh_token) println(user.email) end ) end @get "/protected" function() "Congrets, You signed in Successfully!" end # start the web server serve() ```
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
docs
3603
# Path Parameters You can declare path "parameters" or "variables" inside your route with braces and those values are passed directly to your request handler. ```julia @get "/multiply/{a}/{b}" function(req, a::Float64, b::Float64) return a * b end ``` The values of `{a}` & `{b}` in the path will get passed to the request handler with the parameter with the same name. ## Path parameters with types You can declare the type of a path parameter in the function, using standard Julia type annotations Let's take a look back at our first example above we have code to add two numbers. ```julia @get "/multiply/{a}/{b}" function(req, a::Float64, b::Float64) ``` In this line we have our request type, route, and function handler defined. Looking closer at our request handler, we can see our variables have type annotations attached to them. Kitten will use any type annotations you give it to try to convert the incoming data into that type. Granted, these are completely optional, if you leave out the type annotation then Kitten will assume it's a string by default. Below is another way to write the same function without type annotations. ```julia @get "/multiply/{a}/{b}" function(req, a, b) return parse(Float64, a) * parse(Float64, b) end ``` ## Autogenerated Docs & Path Types And when you open your browser at http://127.0.0.1:8080/docs, you will see the autogenerated interactive documentation for your api. If type annotations were provided in the request handler, they will be taken into account when generating the openapi spec. This means that the generated documentation will know what the input types will be and will not only show, but enforce those types through the interactive documentation. Practically, this means that your users will know exactly how to call your endpoint and your inputs will always remain up to date with the code. ## Additional Parameter Type Support Kitten supports a lot of different path parameter types outside of Julia's base primitives. More complex types & structs are automatically parsed and passed to your request handlers. In most cases, Kitten uses the built-in `parse()` function to parse incoming parameters. But when the parameter types start getting more complex (eg. `Vector{Int64}` or a custom struct), then Kitten assumes the parameter is a JSON string and uses the JSON3 library to serialize the parameter into the corresponding type ```julia using Dates using Kitten using StructTypes @enum Fruit apple=1 orange=2 kiwi=3 struct Person name :: String age :: Int8 end # Add a supporting struct types StructTypes.StructType(::Type{Person}) = StructTypes.Struct() StructTypes.StructType(::Type{Complex{Float64}}) = StructTypes.Struct() @get "/fruit/{fruit}" function(req, fruit::Fruit) return fruit end @get "/date/{date}" function(req, date::Date) return date end @get "/datetime/{datetime}" function(req, datetime::DateTime) return datetime end @get "/complex/{complex}" function(req, complex::Complex{Float64}) return complex end @get "/list/{list}" function(req, list::Vector{Float32}) return list end @get "/data/{dict}" function(req, dict::Dict{String, Any}) return dict end @get "/tuple/{tuple}" function(req, tuple::Tuple{String, String}) return tuple end @get "/union/{value}" function(req, value::Union{Bool, String, Float64}) return value end @get "/boolean/{bool}" function(req, bool::Bool) return bool end @get "/struct/{person}" function(req, person::Person) return person end @get "/float/{float}" function (req, float::Float32) return float end serve() ```
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
docs
949
# Query Parameters When you declare other function parameters that are not part of the path parameters, they are automatically interpreted as "query" parameters. In the example below, we have two query parameters passed to our request handler 1. debug = true 2. limit = 10 ``` http://127.0.0.1:8000/echo?debug=true&limit=10 ``` To show how this works, lets take a look at this route below: ```julia @get "/echo" function(req) # the queryparams() function will extract all query paramaters from the url return queryparams(req) end ``` If we hit this route with a url like the one below we should see the query parameters returned as a JSON object ``` { "debug": "true", "limit": "10" } ``` The important distinction between `query parameters` and `path parameters` is that they are not automatically converted for you. In this example `debug` & `limit` are set to a string even though those aren't the "correct" data types.
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
docs
1959
# Request Body Whenever you need to send data from a client to your API, you send it as a request body. A request body is data sent by the client to your API (usually JSON). A response body is the data your API sends to the client. Request bodies are useful when you need to send more complicated information to an API. Imagine we wanted to request an uber/lyft to come pick us up. The app (a client) will have to send a lot of information to make this happen. It'd need to send information about the user (like location data, membership info) and data about the destination. The api in turn will have to figure out pricing, available drivers and potential routes to take. The inputs of this api are pretty complicated which means it's a perfect case where we'd want to use the request body to send this information. You could send this kind of information through the URL, but I'd highly recommend you don't. Request bodies can store data in pretty much any format which is a lot more flexible than what a URL can support. ## Example The request bodies can be read and converted to a Julia object by using the built-in `json()` helper function. ```julia struct Person name::String age::String end @post "/create/struct" function(req) # this will convert the request body directly into a Person struct person = json(req, Person) return "hello $(person.name)!" end @post "/create/dict" function(req) # this will convert the request body into a Julia Dict data = json(req) return """hello $(data["name"])!""" end ``` When converting JSON into struct's Kitten will throw an error if the request body doesn't match the struct, all properties need to be visible and match the right type. If you don't pass a struct to convert the JSON into, then it will convert the JSON into a Julia Dictionary. This has the benefit of being able to take JSON of any shape which is helpful when your data can change shape or is unknown.
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
0.1.0
9be647522c1dc531739aae8b9320cf6ae221e616
docs
2313
# Request Types When designing an API you need to first think about what `type` of requests and what `routes` or `paths` your api would need to function. For example, if we were to design a weather app we'd probably want a way to lookup weather alerts for a particular state ``` http://localhost:8080/weather/alerts/{state} ``` This url can be broken down into several parts - `host` β†’ `http://localhost` - `port` β†’ `8080` - `route` or `path` β†’ `/weather/alerts/{state}` - `path parameter` β†’ `{state}` Before we start writing code for we need to answer some questions: 1. What kind of data manipulation is this route going to perform? - Are we adding/removing/updating data? (This determines our http method) 2. Will this endpoint need any inputs? - If so, will we need to pass them through the path or inside the body of the http request? This is when knowing the different type of http methods comes in handy. Common HTTP methods: - POST β†’ when you want to **create** some data - GET β†’ when you want to **get** data - PUT β†’ **update** some data if it already exists or **create** it - PATCH β†’ when you want to **update** some data - DELETE β†’ when you want to **delete** some data (there are more methods that aren't in this list) In the HTTP protocol, you can communicate to each path using one (or more) of these "methods". In reality you can use any of these http methods to do any of those operations. But it's heavily recommended to use the appropriate http method so that people & machines can easily understand your web api. Now back to our web example. Lets answer those questions: 1. This endpoint will return alerts from the US National Weather service api 2. The only input we will need is the state abbreviation Since we will only be fetching data and not creating/updating/deleting anything, that means we will want to setup a `GET` route for our api to handle this type of action. ```julia using Kitten using HTTP @get "/weather/alerts/{state}" function(req::HTTP.Request, state::String) return HTTP.get("https://api.weather.gov/alerts/active?area=$state") end serve() ``` With our code in place, we can run this code and visit the endpoint in our browser to view the alerts. Try it out yourself by clicking on the link below. http://127.0.0.1:8080/weather/alerts/NY
Kitten
https://github.com/JuliaKit/Kitten.jl.git
[ "MIT" ]
1.2.5
fc1bcee6037ea393ce28426929eff65c76a86779
code
90
using Documenter using StochasticGene makedocs( sitename = "StochasticGene.jl")
StochasticGene
https://github.com/nih-niddk-mbs/StochasticGene.jl.git
[ "MIT" ]
1.2.5
fc1bcee6037ea393ce28426929eff65c76a86779
code
24456
# # Gillespie Algorithm functions to compute: # Live Cell ON/OFF distributions # smFISH steady state histograms # G state and R step Occupancy probabilities # Mean dwell time for being ON # # Compute ON OFF time histograms function telegraphprefast(range::Array,n::Int,zeta::Int,rin::Vector,total::Int,nbursts::Int,nalleles::Int) # Generalized n-zeta telegraph model # Compute dwell time histograms # n+1 total gene states # gene states are labeled from 1 to n+1 # zeta pre-mRNA steps # There are 2n gene reactions, zeta pre-mRNA reactions, and 1 mRNA decay reaction # rin = reaction rates # forward gene reactions are labeled by odd numbers <2n, backward reactions are even numbers <= 2n # reactions [2n+1, 2n+zeta] are pre-mRNA recations,organized by starting spot, reaction 2n(zeta+1)+1 is mRNA decay reaction # Use Gillespie direct method with speed up from Gibson and Bruck # copy rates # r = copy(rin) # nbursts = 100000 # nbursts = 1000 # decay reaction index reactiondecay = 2*n + zeta + 2 # dwell time arrays ndt = length(range) dt = range[2]-range[1] histofftdd = zeros(Int,ndt) histontdd = zeros(Int,ndt) # time t=0. # tIA and TAI are times when gene state transitions between active and inactive states # they are used to compute dwell times tIA = zeros(Float64,nalleles) tAI = zeros(Float64,nalleles) #Initialize output arrays # mRNA = Array{Int,1}(total) # times = Array{Float64,1}(total) # active start site mu = n #print(n," ",mu," ",zeta,'\n') # Initialize rates gammaf = zeros(n+1) gammab = zeros(n+1) nu = Array{Float64,1}(undef,zeta+1) # assign gene rates for i = 1:n gammaf[i] = rin[2*(i-1)+1] gammab[i+1] = rin[2*i] end # assign pre-mRNA rates for i = 1:zeta+1 nu[i] = rin[2*n + i] end # assign decay rate delta = rin[reactiondecay] # assign correlation rate if length(rin) > reactiondecay rcorr = rin[reactiondecay+1] else rcorr = 0. end #initialize mRNA number to 0 m = 0 # Initialize gene states state = ones(Int,nalleles) #state[1] = mu + 1 # state[1] = 2 # nindex = n + 1 # pre-mRNA states z = Array{Array{Int,1},1}(undef,nalleles) # initialize propensities af = Array{Float64,1}(undef,nalleles) ab = Array{Float64,1}(undef,nalleles) apre1 = Array{Float64,1}(undef,nalleles) az = Array{Array{Float64,1},1}(undef,nalleles) apremid = zeros(nalleles) # sum(az[2:zeta]) middle pre-mRNAstep afree = zeros(nalleles) # az[zeta+1] create free mRNA for i = 1:nalleles z[i] = zeros(Int,zeta) # Intialize pre-mRNA state to all 0 af[i] = gammaf[state[i]] ab[i] = gammab[state[i]] az[i] = zeros(zeta+1) # apre1[i] = float(1-z[i][1])*nu[1]*float(state[i]==n+1) #first pre-mRNA step apre1[i] = 0. #first pre-mRNA step end astate = af + ab adecay = 0. #m*delta amrna = apre1 + apremid + afree bursts = 0 steps = 0 # for steps = 1:total while bursts < nbursts && steps < total steps += 1 asum = sum(amrna) + sum(astate) + adecay if asum > 0. # choose which state to update and time of update r = asum*rand() tau = -log(rand())/asum # update time t += tau #print(tau,' ',asum,' ',state,'\n') # times[steps] = tau # mRNA[steps] = m if r > sum(amrna + astate) # mRNA decay m -= 1 adecay = m*delta else agenecs = amrna[1] + astate[1] agene0 = 0. l = 1 while r > agenecs agene0 = agenecs agenecs += amrna[1+l] + astate[l+1] l += 1 end if l > 1 r -= agene0 end if r > amrna[l] # state update if r > ab[l] + amrna[l] # update forward reaction state[l] += 1 else # update backward reaction state[l] -= 1 end # update propensities af[l] = gammaf[state[l]] ab[l] = gammab[state[l]] astate[l] = af[l] + ab[l] # Activate coupling if any alleles are in state mu + 1 if rcorr > 0. ba = false for k = 1:nalleles ba |= state[k] > mu end if ba for k = 1:nalleles if state[k] == mu af[k] = gammaf[state[k]] + rcorr astate[k] = af[k] + ab[k] end end else for k = 1:nalleles if state[k] == mu af[k] = gammaf[state[k]] astate[k] = af[k] + ab[k] end end end end if state[l] > mu apre1[l] = float(1-z[l][1])*nu[1] # apre1 = az[l][1] else apre1[l] = 0. end amrna[l] = apremid[l] + apre1[l] + afree[l] else # premRNA update if r > apremid[l] + apre1[l] # increase free mRNA m += 1 adecay = m*delta z[l][zeta] = 0 #az[l][zeta+1] = 0 afree[l] = 0. if sum(z[l]) == 0 #&& nhist == 0 tAI[l] = t tactive = ceil(Int,(tAI[l] - tIA[l])/dt) if tactive <= ndt && tactive > 0 histontdd[tactive] += 1 end end if zeta == 1 if state[l] > mu #az[l][1] = nu[1] apre1[l] = nu[1] else #az[l][1] = 0 apre1[l] = 0. end else az[l][zeta] = float(z[l][zeta-1])*nu[zeta] apremid[l] = sum(az[l][2:zeta]) end amrna[l] = apre1[l] + apremid[l] + afree[l] elseif r > apremid[l] # increase first pre-mRNA state if sum(z[l]) == 0 #&& nhist == 0 tIA[l] = t tinactive = ceil(Int,(tIA[l] - tAI[l])/dt) if tinactive <= ndt && tinactive > 0 histofftdd[tinactive] += 1 bursts += 1 end end z[l][1] = 1 #az[l][1] = 0 apre1[l] = 0. if zeta == 1 #az[l][2] = nu[2] afree[l] = nu[2] else az[l][2] = float(1-z[l][2])*nu[2] apremid[l] = sum(az[l][2:zeta]) end amrna[l] = apre1[l] + apremid[l] + afree[l] else # update mid pre-mRNA state azsum = az[l][2] k = 1 while r > azsum azsum += az[l][2+k] k += 1 end i = k + 1 if i <= zeta z[l][i] = 1 z[l][i-1] = 0 az[l][i] = 0. if i == zeta #az[l][i+1] = nu[i+1] afree[l] = nu[i+1] else az[l][i+1] = float(1-z[l][i+1])*nu[i+1] end if i == 2 if state[l] > mu #az[l][1] = nu[1] apre1[l] = nu[1] else az[l][1] = 0. apre1[l] = 0. end else az[l][i-1] = float(z[l][i-2])*nu[i-1] end end apremid[l] = sum(az[l][2:zeta]) amrna[l] = apre1[l] + apremid[l] + afree[l] end # if r > apremid[l] + apre1[l] end # if r > amrna[l] end #if r > sum(amrna + adecay) end #if asum > 0 end # for steps = 1:total sumoff = sum(histofftdd) sumon = sum(histontdd) if sumon > 0 && sumoff > 0 #return [histofftdd[2]/sumoff; histontdd[2]/sumon], mhistn return cumsum(histofftdd/sumoff), cumsum(histontdd/sumon) else return zeros(length(histofftdd)),zeros(length(histontdd)) end end # Compute smFISH histogram function telegraphprefast(n::Int,zeta::Int,rin::Vector,total::Int,tmax::Float64,nhist::Int,nalleles::Int,count=false) # Generalized n, zeta, telegraph model, # Compute steady state mRNA histogram # n+1 total gene states # gene states are labeled from 1 to n+1 # zeta pre-mRNA steps # There are 2n gene reactions, zeta pre-mRNA reactions, and 1 mRNA decay reaction # rin = reaction rates # forward gene reactions are labeled by odd numbers <2n, backward reactions are even numbers <= 2n # reactions [2n+1, 2n+zeta] are pre-mRNA reactions,organized by starting spot, reaction 2n(zeta+1)+1 is mRNA decay reaction # Use Gillespie direct method with speed up from Gibson and Bruck # decay reaction index reactiondecay = 2*n + zeta + 2 # time t=0. # tIA and TAI are times when gene state transitions between active and inactive states # they are used to compute dwell times # tIA = zeros(Float64,nalleles) # tAI = zeros(Float64,nalleles) #Initialize m histogram mhist=zeros(nhist+1) # mRNA = Array{Int,1}(total) # times = Array{Float64,1}(total) # active start site mu = n #print(n," ",mu," ",zeta,'\n') # Initialize rates gammaf = zeros(n+1) gammab = zeros(n+1) nu = Array{Float64,1}(undef,zeta+1) # assign gene rates for i = 1:n gammaf[i] = rin[2*(i-1)+1] gammab[i+1] = rin[2*i] end # assign pre-mRNA rates for i = 1:zeta+1 nu[i] = rin[2*n + i] end # assign decay rate delta = rin[reactiondecay] # assign correlation rate if length(rin) > reactiondecay rcorr = rin[reactiondecay+1] else rcorr = 0. end rcorr = 0. #initialize mRNA number to 0 m = 0 # Initialize gene states state = ones(Int,nalleles) #state[1] = mu + 1 # state[1] = 2 # nindex = n + 1 # pre-mRNA states z = Array{Array{Int,1},1}(undef,nalleles) # initialize propensities af = Array{Float64,1}(undef,nalleles) ab = Array{Float64,1}(undef,nalleles) apre1 = Array{Float64,1}(undef,nalleles) az = Array{Array{Float64,1},1}(undef,nalleles) apremid = zeros(nalleles) # sum(az[2:zeta]) middle pre-mRNAstep afree = zeros(nalleles) # az[zeta+1] create free mRNA for i = 1:nalleles z[i] = zeros(Int,zeta) # Intialize pre-mRNA state to all 0 af[i] = gammaf[state[i]] ab[i] = gammab[state[i]] az[i] = zeros(zeta+1) apre1[i] = 0. #first pre-mRNA step end astate = af + ab adecay = 0. #m*delta amrna = apre1 + apremid + afree bursts = 0 steps = 0 # Begin simulation while t < tmax && steps < total steps += 1 asum = sum(amrna) + sum(astate) + adecay if asum > 0. # choose which state to update and time of update r = asum*rand() tau = -log(rand())/asum # update time t += tau #print(tau,' ',asum,' ',state,'\n') # times[steps] = tau # mRNA[steps] = m if m + 1 <= nhist mhist[m+1] += tau else mhist[nhist+1] += tau end if r > sum(amrna + astate) # mRNA decay m -= 1 adecay = m*delta else agenecs = amrna[1] + astate[1] agene0 = 0. l = 1 while r > agenecs agene0 = agenecs agenecs += amrna[1+l] + astate[l+1] l += 1 end if l > 1 r -= agene0 end if r > amrna[l] # state update if r > ab[l] + amrna[l] # update forward reaction state[l] += 1 else # update backward reaction state[l] -= 1 end # update propensities af[l] = gammaf[state[l]] ab[l] = gammab[state[l]] astate[l] = af[l] + ab[l] # Activate coupling if any alleles are in state mu + 1 if rcorr > 0. ba = false for k = 1:nalleles ba |= state[k] > mu end if ba for k = 1:nalleles if state[k] == mu af[k] = gammaf[state[k]] + rcorr astate[k] = af[k] + ab[k] end end else for k = 1:nalleles if state[k] == mu af[k] = gammaf[state[k]] astate[k] = af[k] + ab[k] end end end end if state[l] > mu apre1[l] = float(1-z[l][1])*nu[1] # apre1 = az[l][1] else apre1[l] = 0. end amrna[l] = apremid[l] + apre1[l] + afree[l] else # premRNA update if r > apremid[l] + apre1[l] # increase free mRNA m += 1 adecay = m*delta z[l][zeta] = 0 #az[l][zeta+1] = 0 afree[l] = 0. if zeta == 1 if state[l] > mu #az[l][1] = nu[1] apre1[l] = nu[1] else #az[l][1] = 0 apre1[l] = 0. end else az[l][zeta] = float(z[l][zeta-1])*nu[zeta] apremid[l] = sum(az[l][2:zeta]) end amrna[l] = apre1[l] + apremid[l] + afree[l] elseif r > apremid[l] # increase first pre-mRNA state z[l][1] = 1 #az[l][1] = 0 apre1[l] = 0. if zeta == 1 #az[l][2] = nu[2] afree[l] = nu[2] else az[l][2] = float(1-z[l][2])*nu[2] apremid[l] = sum(az[l][2:zeta]) end amrna[l] = apre1[l] + apremid[l] + afree[l] else # update mid pre-mRNA state azsum = az[l][2] k = 1 while r > azsum azsum += az[l][2+k] k += 1 end i = k + 1 if i <= zeta z[l][i] = 1 z[l][i-1] = 0 az[l][i] = 0. if i == zeta #az[l][i+1] = nu[i+1] afree[l] = nu[i+1] else az[l][i+1] = float(1-z[l][i+1])*nu[i+1] end if i == 2 if state[l] > mu #az[l][1] = nu[1] apre1[l] = nu[1] else az[l][1] = 0. apre1[l] = 0. end else az[l][i-1] = float(z[l][i-2])*nu[i-1] end end apremid[l] = sum(az[l][2:zeta]) amrna[l] = apre1[l] + apremid[l] + afree[l] end # if r > apremid[l] + apre1[l] end # if r > amrna[l] end #if r > sum(amrna + adecay) end #if asum > 0 end # for steps = 1:total counts = max(sum(mhist),1) mhist /= counts if count return mhist[1:nhist],counts else return mhist[1:nhist] end end # Compute steady state occupancy probabilities for all G states and R steps function telegraphprefastSS(n::Int,zeta::Int,rin::Vector,total::Int,nalleles::Int) #Steady state arrays Gss = zeros(n+1) Rss = 0. Rssc = 0. # copy rates r = copy(rin) # decay reaction index reactiondecay = 2*n + zeta + 2 # time t=0. # active start site mu = n # Initialize rates gammaf = zeros(n+1) gammab = zeros(n+1) nu = Array{Float64}(undef,zeta+1) # assign gene rates for i = 1:n gammaf[i] = r[2*(i-1)+1] gammab[i+1] = r[2*i] end # assign pre-mRNA rates for i = 1:zeta+1 nu[i] = r[2*n + i] end # assign decay rate delta = r[reactiondecay] # assign correlation rate if length(r) > reactiondecay rcorr = r[reactiondecay+1] else rcorr = 0. end #initialize mRNA number to 0 m=0 # Initialize to gene state 1, all other states are zero state = ones(Int,nalleles) #state[1] = mu + 1 #state[2] = mu nindex = n + 1 # pre-mRNA states z = Array{Array{Int,1}}(undef,nalleles) # initialize propensities af = Array{Float64}(undef,nalleles) ab = similar(af) apre1 = similar(af) az = Array{Array{Float64,1}}(undef,nalleles) apremid = zeros(nalleles) # sum(az[2:zeta]) middle pre-mRNAstep afree = zeros(nalleles) # az[zeta+1] create free mRNA for i = 1:nalleles z[i] = zeros(Int8,zeta) # Intialize pre-mRNA state to all 0 af[i] = gammaf[state[i]] ab[i] = gammab[state[i]] az[i] = zeros(zeta+1) apre1[i] = float(1-z[i][1])*nu[1]*float(state[i]==n+1) #first pre-mRNA step end astate = af + ab adecay = 0. #m*delta amrna = apre1 + apremid + afree for steps = 1:total asum = sum(amrna) + sum(astate) + adecay if asum > 0. # choose which state to update and time of update r = asum*rand() tau = -log(rand())/asum # update time t += tau #print(tau,' ',asum,' ',state,'\n') #times[steps]=tau #mRNA[steps] = m for j = 1:nalleles Gss[state[j]] += tau if state[j]> mu && z[j][1] == 1 #&& sum(z[j]) == 1 Rss += tau end end if reduce(|,state) > 1 && reduce(|,z[:][1]) == 1 Rssc += tau end if r > sum(amrna + astate) # mRNA decay m -= 1 adecay = m*delta else agenecs = amrna[1] + astate[1] agene0 = 0. l = 1 while r > agenecs agene0 = agenecs agenecs += amrna[1+l] + astate[l+1] l += 1 end if l > 1 r -= agene0 end if r > amrna[l] # state update if r > ab[l] + amrna[l] # update forward reaction state[l] += 1 else # update backward reaction state[l] -= 1 end # update propensities af[l] = gammaf[state[l]] ab[l] = gammab[state[l]] astate[l] = af[l] + ab[l] # Activate coupling if any alleles are in state mu + 1 ba = false for k = 1:nalleles ba |= state[k] > mu end if ba for k = 1:nalleles if state[k] == mu af[k] = gammaf[state[k]] + rcorr astate[k] = af[k] + ab[k] end end else for k = 1:nalleles if state[k] == mu af[k] = gammaf[state[k]] astate[k] = af[k] + ab[k] end end end # if ba # for k = 1:nalleles # af[k] = gammaf[state[k]] + rcorr*float(state[k]==mu) # astate[k] = af[k] + ab[k] # end # else # for k = 1:nalleles # af[k] = gammaf[state[k]] # astate[k] = af[k] + ab[k] # end # end if state[l] > mu apre1[l] = float(1-z[l][1])*nu[1] # apre1 = az[l][1] else apre1[l] = 0. end amrna[l] = apremid[l] + apre1[l] + afree[l] else # premRNA update if r > apremid[l] + apre1[l] # increase free mRNA m += 1 adecay = m*delta z[l][zeta] = 0 #az[l][zeta+1] = 0 afree[l] = 0. if zeta == 1 if state[l] > mu #az[l][1] = nu[1] apre1[l] = nu[1] else #az[l][1] = 0 apre1[l] = 0. end else az[l][zeta] = float(z[l][zeta-1])*nu[zeta] apremid[l] = sum(az[l][2:zeta]) end amrna[l] = apre1[l] + apremid[l] + afree[l] elseif r > apremid[l] # increase first pre-mRNA state z[l][1] = 1 #az[l][1] = 0 apre1[l] = 0. if zeta == 1 #az[l][2] = nu[2] afree[l] = nu[2] else az[l][2] = float(1-z[l][2])*nu[2] apremid[l] = sum(az[l][2:zeta]) end amrna[l] = apre1[l] + apremid[l] + afree[l] else # update mid pre-mRNA state azsum = az[l][2] k = 1 while r > azsum azsum += az[l][2+k] k += 1 end i = k + 1 z[l][i] = 1 z[l][i-1] = 0 az[l][i] = 0. if i == zeta #az[l][i+1] = nu[i+1] afree[l] = nu[i+1] else az[l][i+1] = float(1-z[l][i+1])*nu[i+1] end if i == 2 if state[l] > mu #az[l][1] = nu[1] apre1[l] = nu[1] else az[l][1] = 0. apre1[l] = 0. end else az[l][i-1] = float(z[l][i-2])*nu[i-1] end apremid[l] = sum(az[l][2:zeta]) amrna[l] = apre1[l] + apremid[l] + afree[l] end # if r > apremid[l] + apre1[l] end # if r > amrna[l] end #if r > sum(amrna + adecay) end #if asum > 0 end # for steps = 1:total println(Gss) println(Rss,",",t) Gss /= t*nalleles Rss /= t*nalleles Rssc /= t*nalleles eff = Rss/Gss[n+1] effc = Rssc/Gss[n+1] println(sum(Gss)) return Gss, eff, effc end # Compute mean dwell times function telegraphmdt(range::Array,n::Int,zeta::Int,rin::Vector,total::Int,nbursts::Int,nalleles::Int) # decay reaction index reactiondecay = 2*n + zeta + 2 # dwell time arrays ndt = length(range) dt = range[2]-range[1] histofftdd = zeros(Int,ndt) histontdd = zeros(Int,ndt) # time t=0. # tIA and TAI are times when gene state transitions between active and inactive states # they are used to compute dwell times tIA = zeros(Float64,nalleles) tAI = zeros(Float64,nalleles) ONtimes = Array{Float64}(undef,0) #Initialize output arrays # mRNA = Array{Int,1}(total) # times = Array{Float64,1}(total) # active start site mu = n #print(n," ",mu," ",zeta,'\n') # Initialize rates gammaf = zeros(n+1) gammab = zeros(n+1) nu = Array{Float64,1}(undef,zeta+1) # assign gene rates for i = 1:n gammaf[i] = rin[2*(i-1)+1] gammab[i+1] = rin[2*i] end # assign pre-mRNA rates for i = 1:zeta+1 nu[i] = rin[2*n + i] end # assign decay rate delta = rin[reactiondecay] # assign correlation rate if length(rin) > reactiondecay rcorr = rin[reactiondecay+1] else rcorr = 0. end #initialize mRNA number to 0 m = 0 # Initialize gene states state = ones(Int,nalleles) #state[1] = mu + 1 state[1] = 2 # nindex = n + 1 # pre-mRNA states z = Array{Array{Int,1},1}(undef,nalleles) # initialize propensities af = Array{Float64,1}(undef,nalleles) ab = Array{Float64,1}(undef,nalleles) apre1 = Array{Float64,1}(undef,nalleles) az = Array{Array{Float64,1},1}(undef,nalleles) apremid = zeros(nalleles) # sum(az[2:zeta]) middle pre-mRNAstep afree = zeros(nalleles) # az[zeta+1] create free mRNA for i = 1:nalleles z[i] = zeros(Int,zeta) # Intialize pre-mRNA state to all 0 af[i] = gammaf[state[i]] ab[i] = gammab[state[i]] az[i] = zeros(zeta+1) # apre1[i] = float(1-z[i][1])*nu[1]*float(state[i]==n+1) #first pre-mRNA step apre1[i] = 0. #first pre-mRNA step end astate = af + ab adecay = 0. #m*delta amrna = apre1 + apremid + afree bursts = 0 steps = 0 # for steps = 1:total while bursts < nbursts && steps < total steps += 1 asum = sum(amrna) + sum(astate) + adecay if asum > 0. # choose which state to update and time of update r = asum*rand() tau = -log(rand())/asum # update time t += tau #print(tau,' ',asum,' ',state,'\n') # times[steps] = tau # mRNA[steps] = m if r > sum(amrna + astate) # mRNA decay m -= 1 adecay = m*delta else agenecs = amrna[1] + astate[1] agene0 = 0. l = 1 while r > agenecs agene0 = agenecs agenecs += amrna[1+l] + astate[l+1] l += 1 end if l > 1 r -= agene0 end if r > amrna[l] # state update if r > ab[l] + amrna[l] # update forward reaction state[l] += 1 else # update backward reaction state[l] -= 1 end # update propensities af[l] = gammaf[state[l]] ab[l] = gammab[state[l]] astate[l] = af[l] + ab[l] # Activate coupling if any alleles are in state mu + 1 if rcorr > 0. ba = false for k = 1:nalleles ba |= state[k] > mu end if ba for k = 1:nalleles if state[k] == mu af[k] = gammaf[state[k]] + rcorr astate[k] = af[k] + ab[k] end end else for k = 1:nalleles if state[k] == mu af[k] = gammaf[state[k]] astate[k] = af[k] + ab[k] end end end end if state[l] > mu apre1[l] = float(1-z[l][1])*nu[1] # apre1 = az[l][1] else apre1[l] = 0. end amrna[l] = apremid[l] + apre1[l] + afree[l] else # premRNA update if r > apremid[l] + apre1[l] # increase free mRNA m += 1 adecay = m*delta z[l][zeta] = 0 #az[l][zeta+1] = 0 afree[l] = 0. if sum(z[l]) == 0 #&& nhist == 0 tAI[l] = t tactive = ceil(Int,(tAI[l] - tIA[l])/dt) push!(ONtimes,tAI[l] - tIA[l]) if tactive <= ndt && tactive > 0 histontdd[tactive] += 1 end end if zeta == 1 if state[l] > mu #az[l][1] = nu[1] apre1[l] = nu[1] else #az[l][1] = 0 apre1[l] = 0. end else az[l][zeta] = float(z[l][zeta-1])*nu[zeta] apremid[l] = sum(az[l][2:zeta]) end amrna[l] = apre1[l] + apremid[l] + afree[l] elseif r > apremid[l] # increase first pre-mRNA state if sum(z[l]) == 0 #&& nhist == 0 tIA[l] = t tinactive = ceil(Int,(tIA[l] - tAI[l])/dt) if tinactive <= ndt && tinactive > 0 histofftdd[tinactive] += 1 bursts += 1 end end z[l][1] = 1 #az[l][1] = 0 apre1[l] = 0. if zeta == 1 #az[l][2] = nu[2] afree[l] = nu[2] else az[l][2] = float(1-z[l][2])*nu[2] apremid[l] = sum(az[l][2:zeta]) end amrna[l] = apre1[l] + apremid[l] + afree[l] else # update mid pre-mRNA state azsum = az[l][2] k = 1 while r > azsum azsum += az[l][2+k] k += 1 end i = k + 1 z[l][i] = 1 z[l][i-1] = 0 az[l][i] = 0. if i == zeta #az[l][i+1] = nu[i+1] afree[l] = nu[i+1] else az[l][i+1] = float(1-z[l][i+1])*nu[i+1] end if i == 2 if state[l] > mu #az[l][1] = nu[1] apre1[l] = nu[1] else az[l][1] = 0. apre1[l] = 0. end else az[l][i-1] = float(z[l][i-2])*nu[i-1] end apremid[l] = sum(az[l][2:zeta]) amrna[l] = apre1[l] + apremid[l] + afree[l] end # if r > apremid[l] + apre1[l] end # if r > amrna[l] end #if r > sum(amrna + adecay) end #if asum > 0 end # for steps = 1:total return mean(ONtimes), std(ONtimes)/sqrt(length(ONtimes)), ONtimes end
StochasticGene
https://github.com/nih-niddk-mbs/StochasticGene.jl.git
[ "MIT" ]
1.2.5
fc1bcee6037ea393ce28426929eff65c76a86779
code
2842
module StochasticGene using Distributions using StatsBase using Statistics using DelimitedFiles using Dates using Distributed using LinearAlgebra using Plots using SparseArrays using OrdinaryDiffEq using DataFrames using FFTW using Downloads using CSV using MultivariateStats using Optim export rna_setup, folder_setup, makeswarm, RNAData, RNAOnOffData, RNADwellTimeData, TraceData, TraceNascentData, TraceRNAData, GMmodel, GMfixedeffectsmodel, GRSMmodel, GRSMfixedeffectsmodel, fit, run_mh, metropolis_hastings, prob_Gaussian, prob_GaussianMixture, prob_GaussianMixture_6, make_dataframes, write_dataframes, write_dataframes_only, write_winners, write_augmented, fix_filenames, fix, large_deviance, large_rhat, assemble_all, assemble_measures_model, write_histograms, make_ONOFFhistograms, plot_histogram, make_traces, make_traces_dataframe, write_traces, plot, plot!, simulator, simulate_trace, simulate_trace_vector, simulate_trace_data, on_states, num_rates, load_data, load_model, make_components_MTD, make_components_MTAI, make_components_MT, make_components_M, make_components_T, make_components_TAI, likelihoodarray, likelihoodfn, datapdf, normalize_histogram, norm, make_array, folder_path, get_rates, new_FISHfolder, ModelArgs ### Source files # Type system and common functions include("common.jl") # Transition rate matrices of stochastic models defining master equations include("transition_rate_matrices.jl") # Metropolis Hastings MCMC for computing posterior distributions of model parameters include("metropolis_hastings.jl") # Input output functions include("io.jl") # Chemical master equation solutions of stochastic models for likelihood functions in fitting algorithms include("chemical_master.jl") # commonly used functions include("utilities.jl") # Probability distributions by direct simulation of stochastic models using Gillespie and Gibson-Bruck algorithms include("simulator.jl") include("telegraphsplice.jl") # functions for fitting models to data include("fit.jl") # functions for post fit analysis and plots include("analysis.jl") # functions for use on NIH cluster Biowulf include("biowulf.jl") # functions for hidden markov models include("hmm.jl") # # functions for fitting time series traces # include("trace.jl") # # functions specific for Gene Trap experiments of Wan et al. # include("genetrap.jl") # # functions for scRNA and FISH experiments of Trzaskoma et al. # include("rna.jl") """ A Julia module for simulation and Bayesian inference of parameters of stochastic models of gene transcription. API Overview: """ end #Module
StochasticGene
https://github.com/nih-niddk-mbs/StochasticGene.jl.git
[ "MIT" ]
1.2.5
fc1bcee6037ea393ce28426929eff65c76a86779
code
43661
# This file is part of StochasticGene.jl # analysis.jl """ make_dataframes(resultfolder::String,datapath::String) """ function make_dataframes(resultfolder::String, datapath::String, assemble=true, fittedparams=Int[]) if assemble assemble_all(resultfolder, fittedparams=fittedparams) end files = get_ratesummaryfiles(resultfolder) parts = fields.(files) models = get_models(parts) labels = get_labels(parts) df = Vector{Vector}(undef, 0) for label in labels lfiles = files[label.==get_label.(files)] dfl = Vector{Tuple}(undef, 0) for model in models if length(parse_model(model)) > 1 println("Not G model") else mfiles = lfiles[model.==get_model.(lfiles)] dfm = Vector{DataFrame}(undef, 0) for i in eachindex(mfiles) push!(dfm, make_dataframe(joinpath(resultfolder, mfiles[i]), datapath)) end push!(dfl, ("Summary_$(label)_$(model).csv", stack_dataframe(dfm))) end end push!(df, dfl) end return df end """ statfile_from_ratefile(ratefile) TBW """ statfile_from_ratefile(ratefile) = replace(ratefile, "rates_" => "stats_") """ make_dataframe(ratefile::String, datapath::String) TBW """ function make_dataframe(ratefile::String, datapath::String) df = read_dataframe(ratefile) df2 = read_dataframe(statfile_from_ratefile(ratefile)) df = leftjoin(df, df2, on=:Gene, makeunique=true) filename = splitpath(ratefile)[end] parts = fields(filename) model = parse_model(parts.model) if length(model) > 1 println("Not G model") else G = parse(Int, parts.model) insertcols!(df, :Model => fill(G, size(df, 1))) df = stack_dataframe(df, G, parts.cond) add_moments!(df, datapath) end end """ parse_model(name::String) TBW """ function parse_model(name::String) d = parse(Int, name) d > 9 && (d = digits(d)) d end """ augment_dataframe(df, resultfolder) TBW """ function augment_dataframe(df, resultfolder) dfc = copy(df) G = dfc[1, :Model] if G > 1 dfc = add_burstsize(dfc, resultfolder) end if G == 2 add_modelmoments!(dfc) end dfc = add_measures(dfc, resultfolder, string(G)) add_residenceprob!(dfc) dfc end """ make_measure_df(resultfolder::String, G::String) TBW """ function make_measure_df(resultfolder::String, G::String) files = get_measuresummaryfiles(resultfolder) df = Vector{DataFrame}(undef, 0) for file in files parts = fields(file) if parts.model == G df0 = read_dataframe(joinpath(resultfolder, file)) if ~isempty(parts.cond) insertcols!(df0, :Condition => parts.cond) end push!(df, df0) end end stack_dataframe(df) end """ join_cols(d) TBW """ function join_cols(d) if ismissing(d.Condition[1]) return [:Gene] else return [:Gene, :Condition] end end """ add_measures(df, resultfolder::String, G) TBW """ function add_measures(df, resultfolder::String, G) dm = make_measure_df(resultfolder, G) leftjoin(df, dm, on=join_cols(df)) end """ add_mean!(df::DataFrame, datapath) TBW """ function add_mean!(df::DataFrame, datapath) # root = string(split(abspath(datapath),"data")[1]) m = Vector{Float64}(undef, length(df.Gene)) i = 1 for gene in df.Gene m[i] = mean_histogram(get_histogram_rna(string(gene), df[i, :Condition], datapath)) i += 1 end insertcols!(df, :Expression => m) end """ add_moments!(df::DataFrame, datapath) TBW """ function add_moments!(df::DataFrame, datapath) m = Vector{Float64}(undef, length(df.Gene)) v = similar(m) t = similar(m) i = 1 for gene in df.Gene _, h = read_rna(gene, df[i, :Condition], datapath) m[i] = mean_histogram(h) v[i] = var_histogram(h) t[i] = moment_histogram(h, 3) i += 1 end insertcols!(df, :Expression => m, :Variance => v, :ThirdMoment => t) end """ add_modelmoments!(df::DataFrame) TBW """ function add_modelmoments!(df::DataFrame) m = Vector{Float64}(undef, length(df.Gene)) v = similar(m) i = 1 for gene in df.Gene m[i] = model2_mean(df.Rate01[i], df.Rate10[i], df.Eject[i], df.Decay[i], df.Nalleles[i]) v[i] = model2_variance(df.Rate01[i], df.Rate10[i], df.Eject[i], df.Decay[i], df.Nalleles[i]) i += 1 end insertcols!(df, :Model_Expression => m, :Model_Variance => v) end """ add_residenceprob!(df::DataFrame) TBW """ function add_residenceprob!(df::DataFrame) n = df.Model[1] - 1 N = length(df.Gene) g = Matrix{Float64}(undef, N, n + 1) r = Vector{Float64}(undef, 2 * n) for i in 1:N for j in 1:n Symbol("Rate$j$(j-1)") Symbol("Rate$(j-1)$j") r[2*j-1] = df[i, Symbol("Rate$j$(j-1)")] r[2*j] = df[i, Symbol("Rate$(j-1)$j")] g[i, :] = residenceprob_G(r, n) end end for j in 1:n+1 insertcols!(df, Symbol("ProbG$(j-1)") => g[:, j]) end end """ add_burstsize(df, resultfolder::String, cols::Vector{Symbol}=join_cols(df)) TBW """ add_burstsize(df, resultfolder::String, cols::Vector{Symbol}=join_cols(df)) = add_burstsize(df, make_burst_df(resultfolder), cols) """ add_burstsize(df, db, cols) TBW """ function add_burstsize(df, db, cols) if ismissing(df[1, :Condition]) leftjoin(df, db[:, [:BurstMean, :BurstSD, :BurstMedian, :BurstMAD, :Gene]], on=cols) else leftjoin(df, db[:, [:BurstMean, :BurstSD, :BurstMedian, :BurstMAD, :Gene, :Condition]], on=cols) end end """ make_burst_df(resultfolder::String) TBW """ function make_burst_df(resultfolder::String) files = get_burstsummaryfiles(resultfolder) df = Vector{DataFrame}(undef, 0) for file in files parts = fields(file) df0 = read_dataframe(joinpath(resultfolder, file)) if ~isempty(parts.cond) insertcols!(df0, :Condition => parts.cond) end push!(df, df0) end stack_dataframe(df) end # add_time(csvfile::String,timestamp) = CSV.write(csvfile,add_time!(read_dataframe(csvfile),timestamp)) """ add_time!(df::DataFrame, timestamp) TBW """ add_time!(df::DataFrame, timestamp) = insertcols!(df, :Time => timestamp) """ stack_dataframe(df,G,cond) stack_dataframe(df2::Vector{DataFrame}) """ stack_dataframe(df, G, cond) = stack_dataframe(separate_dataframe(df, G, cond)) function stack_dataframe(df2::Vector{DataFrame}) df = df2[1] for i in 2:length(df2) df = vcat(df, df2[i]) end return df end """ separate_dataframe(df, G, cond) TBW """ function separate_dataframe(df, G, cond) conds = split(cond, "-") nsets = length(conds) df2 = Vector{DataFrame}(undef, nsets) for i in 1:nsets df2[i] = df[:, [1; 2*G*(i-1)+2:2*G*i+1; 2*G*nsets+2:end]] rename!(x -> split(x, "_")[1], df2[i]) insertcols!(df2[i], :Condition => fill(string(conds[i]), size(df, 1))) end return df2 end # function residuals(df) # R01 = lm(@formula(log(Rate01) ~ Time*log(Decay)+PC1+PC2+PC3+PC4+PC5),df[(df.Winner .> 1) .& (df.Expression .> 0.),:]) # # end """ make_Zscore_dataframe(df, conditions::Vector) TBW """ function make_Zscore_dataframe(df, conditions::Vector) dfc = Array{DataFrame}(undef, length(conditions)) for i in eachindex(dfc) dfc[i] = df[df.Condition.==conditions[i], :] end df = leftjoin(dfc[1], dfc[2], on=[:Gene, :Time], makeunique=true) add_Zscore!(df) add_MomentChange!(df) df[:, [:Gene, :Time, :ZRate01, :ZRate10, :ZEject, :dExpression, :dVariance, :dThirdMoment, :Winner]] end """ add_MomentChange!(df) TBW """ function add_MomentChange!(df) insertcols!(df, :dExpression => df.Expression_1 .- df.Expression) insertcols!(df, :dVariance => df.Variance_1 .- df.Variance) insertcols!(df, :dThirdMoment => df.ThirdMoment_1 .- df.ThirdMoment) end """ add_Zscore!(df) TBW """ function add_Zscore!(df) insertcols!(df, :ZRate01 => Difference_Zscore.(df.Rate01_1, df.Rate01, df.Rate01SD_1, df.Rate01SD)) insertcols!(df, :ZRate10 => Difference_Zscore.(df.Rate10_1, df.Rate10, df.Rate10SD_1, df.Rate10SD)) insertcols!(df, :ZEject => Difference_Zscore.(df.Eject_1, df.Eject, df.EjectSD, df.EjectSD_1)) end function add_Zscore_class!(df, threshold=2.0) insertcols!(df, :On => classify_Zscore.(df.ZRate01, threshold)) insertcols!(df, :Off => classify_Zscore.(df.ZRate10, threshold)) insertcols!(df, :Eject => classify_Zscore.(df.ZEject, threshold)) insertcols!(df, :OnOffEject => df.On .* df.Off .* df.Eject) end function classify_Zscore(Z, threshold) if Z .> threshold return "Up" elseif Z .< -threshold return "Down" else return "Null" end end """ best_AIC(folder::String) TBW """ best_AIC(folder::String) = best_measure(folder, :AIC) """ best_WAIC(folder::String) TBW """ best_WAIC(folder::String) = best_measure(folder, :WAIC) """ best_measure(folder::String, measure::Symbol) TBW """ function best_measure(folder::String, measure::Symbol) files = get_measuresummaryfiles(folder) parts = fields.(files) labels = get_labels(parts) conds = get_conds(parts) df = Vector{Tuple{String,DataFrame}}(undef, 0) for label in labels for cond in conds lfiles = files[(label.==get_label.(files)).&(cond.==get_cond.(files))] dm = Vector{DataFrame}(undef, length(lfiles)) for i in eachindex(lfiles) if isfile(joinpath(folder, lfiles[i])) dm[i] = read_dataframe(joinpath(folder, lfiles[i])) insertcols!(dm[i], :Model => fill(get_model(lfiles[i]), size(dm[i], 1))) end end # println(best_measure(dm,measure)) bm = best_measure(dm, measure) ~isempty(bm) && push!(df, ("Winners_$(label)_$(cond)_$(string(measure)).csv", bm)) end end return df end function best_measure(dfs::Vector, measure::Symbol) df = DataFrame(:Gene => [], :Winner => [], measure => []) ngenes = Int[] for d in dfs ngenes = push!(ngenes, length(d[:, :Gene])) end if ~isempty(ngenes) others = setdiff(eachindex(dfs), argmax(ngenes)) for d in eachrow(dfs[argmax(ngenes)]) l = d[measure] model = d[:Model] for k in others dc = dfs[k][dfs[k].Gene.==d.Gene, :] if ~isempty(dc) if dc[1, measure] < l l = dc[1, measure] model = dc[1, :Model] end end end push!(df, Dict(:Gene => d.Gene, :Winner => model, measure => l)) end end return df end """ add_pca(df::DataFrame,files::Vector,npcs::Int,conds::Vector) make PCAs from files and add to dataframe df """ add_pca(df::DataFrame, files::Vector, npcs::Int, conds::Vector) = add_pca(df, make_pca(files, npcs, conds), makeunique=true) add_pca(df::DataFrame, dpc::DataFrame) = leftjoin(df, dpc, on=[:Condition, :Gene, :Time], makeunique=true) """ make_pca(files::Vector,npcs::Int) Compute PCA """ function make_pca(files::Vector, npcs::Int, conds::Vector, times::Vector) pca = make_pca(files[1], npcs, conds[1], times[1]) for i in 2:length(files) pca = [pca; make_pca(files[i], npcs, conds[i], times[i])] end return pca end function make_pca(files::Vector, npcs::Int, conds::Vector) pca = make_pca(files[1], npcs, conds[1]) for i in 2:length(files) pca = [pca; make_pca(files[i], npcs, conds[i])] end return pca end function make_pca(file::String, npcs::Int, cond) r, h = readdlm(file, header=true) df = make_pca(r, npcs) insertcols!(df, :Condition => cond) end function make_pca(file::String, npcs::Int, cond, time) r, h = readdlm(file, header=true) df = make_pca(r, npcs) insertcols!(df, :Condition => cond, :Time => time) end function make_pca(m::Matrix, npcs::Int) M = fit(PCA, float.(m[:, 2:end]), maxoutdim=npcs) make_pca(M, m[:, 1]) end function make_pca(M::PCA, genes) P = projection(M) df = DataFrame(Gene=genes) i = 1 for p in eachcol(P) insertcols!(df, Symbol("PC$i") => p) i += 1 end return df end function make_combinedpca(files::Vector, npcs::Int) m, h = readdlm(files[1], header=true) for i in 2:length(files) r, h = readdlm(files[i], header=true) m = [m r[:, 2:end]] end make_pca(m, npcs) end function make_dataframe_transient(folder::String, winners::String="") rs = Array{Any,2}(undef, 0, 8) files = readdir(folder) n = 0 for file in files if occursin("rate", file) t = parse(Float64, split(split(file, "T")[2], "_")[1]) r, head = readdlm(joinpath(folder, file), ',', header=true) r = [vcat(r[:, [1, 2, 3, 4, 5, 10]], r[:, [1, 6, 7, 8, 9, 10]]) [zeros(size(r)[1]); ones(size(r)[1])] t * ones(2 * size(r)[1]) / 60.0] rs = vcat(rs, r) n += 1 end end if winners != "" w = get_winners(winners, 2 * n) return DataFrame(Gene=rs[:, 1], on=float.(rs[:, 2]), off=float.(rs[:, 3]), eject=float.(rs[:, 4]), decay=float.(rs[:, 5]), yield=float.(rs[:, 6]), cond=Int.(rs[:, 7]), time=float.(rs[:, 8]), winner=w) else return DataFrame(Gene=rs[:, 1], on=float.(rs[:, 2]), off=float.(rs[:, 3]), eject=float.(rs[:, 4]), decay=float.(rs[:, 5]), yield=float.(rs[:, 6]), cond=Int.(rs[:, 7]), time=float.(rs[:, 8])) end end function filter_gene(measurefile, measure, threshold) genes = Vector{String}(undef, 0) measures, header = readdlm(measurefile, ',', header=true) println(length(measures[:, 1])) col = findfirst(header[1, :] .== measure) for d in eachrow(measures) if d[col] > threshold || isnan(d[col]) push!(genes, d[1]) end end println(length(genes)) return genes end function filter_gene_nan(measurefile, measure) genes = Vector{String}(undef, 0) measures, header = readdlm(measurefile, ',', header=true) println(length(measures[:, 1])) col = findfirst(header[1, :] .== measure) for d in eachrow(measures) if isnan(d[col]) push!(genes, d[1]) end end println(length(genes)) return genes end """ large_rhat(measureile,threshold) """ large_rhat(measurefile, threshold) = filter_gene(measurefile, "Rhat", threshold) """ large_deviance(measurefile,threshold) returns list of genes that have deviance greater than `threshold' in 'measurefile' """ large_deviance(measurefile, threshold) = filter_gene(measurefile, "Deviance", threshold) function deviance(r, cond, n, datapath, root) h, hd = histograms(r, cell, cond, n, datapath, root) deviance(h, hd) end function compute_deviance(outfile, ratefile::String, cond, n, datapath, root) f = open(outfile, "w") rates, head = readdlm(ratefile, ',', header=true) for r in eachrow(rates) d = deviance(r, cond, n, datapath, root) writedlm(f, [gene d], ',') end close(f) end """ deviance(fits, data, model) return deviance """ deviance(fits, data, model) = -1.0 function deviance(fits, data::AbstractHistogramData, model) predictions = likelihoodfn(fits.parml, data, model) deviance(log.(max.(predictions, eps())), datapdf(data)) end """ deviance(fits, data::AbstractTraceData, model) return max ll normalized by number of trace frames """ function deviance(fits, data::AbstractTraceData, model) fits.llml / sum(sum.(data.trace[1])) end """ deviance(data::AbstractHistogramData, model::AbstractGmodel) """ function deviance(data::AbstractHistogramData, model::AbstractGmodel) h = likelihoodfn(model.rates[model.fittedparam], data, model) println(h) deviance(h, datapdf(data)) end """ deviance(logpredictions::Array,data::AbstractHistogramData) return deviance use log of data histogram as loglikelihood of overfit model """ deviance(logpredictions::Array, data::AbstractHistogramData) = deviance(logpredictions, datapdf(data)) deviance(logpredictions::Array, hist::Array) = 2 * hist' * (log.(max.(hist, eps())) - logpredictions) """ frequency(ron, sd, rdecay) return on rate / decay rate, sd """ frequency(ron, sd, rdecay) = (ron / rdecay, sd / rdecay) """ burstsize(reject::Float64, roff, covee, covoo, coveo::Float64) return eject rate / off rate, sd """ function burstsize(reject::Float64, roff, covee, covoo, coveo::Float64) v = var_ratio(reject, roff, covee, covoo, coveo) return reject / roff, sqrt(v) end function ratestats(gene, G, folder, cond) filestats = joinpath(folder, getfile("param-stats", gene, G, folder, cond)[1]) filerates = joinpath(folder, getratefile(gene, G, folder, cond)[1]) rates = readrates(filerates) cov = read_covparam(filestats) # mu = readmean(filestats) # sd = readsd(filestats) return rates, cov end meanofftime(gene::String, infile, n, method, root) = sum(1 .- offtime(gene, infile, n, method, root)) function meanofftime(r::Vector, n::Int, method::Int) if n == 1 return 1 / r[1] else return sum(1 .- offtime(r, n, method)) end end function offtime(r::Vector, n::Int, method::Int) _, _, TI = mat_G_DT(r, n) vals, _ = eig_decompose(TI) minval = min(minimum(abs.(vals[vals.!=0])), 0.2) offtimeCDF(collect(1.0:5/minval), r, n, TI, method) end function offtime(gene::String, infile, n, method, root) contents, head = readdlm(infile, ',', header=true) r = float.(contents[gene.==contents[:, 1], 2:end-1])[1, :] offtime(r, n, method) end function join_files(file1::String, file2::String, outfile::String, addlabel::Bool=true) contents1, head1 = readdlm(file1, ',', header=true) # model G=2 contents2, head2 = readdlm(file2, ',', header=true) # model G=3 f = open(outfile, "w") if addlabel header = vcat(String.(head1[2:end]) .* "_G2", String.(head2[2:end]) .* "_G3") else header = vcat(String.(head1[2:end]), String.(head2[2:end])) end header = reshape(permutedims(header), (1, length(head1) + length(head2) - 2)) header = hcat(head1[1], header) println(header) writedlm(f, header, ',') for row in 1:size(contents1, 1) if contents1[row, 1] == contents2[row, 1] contents = hcat(contents1[row:row, 2:end], contents2[row:row, 2:end]) contents = reshape(permutedims(contents), (1, size(contents1, 2) + size(contents2, 2) - 2)) contents = hcat(contents1[row, 1], contents) writedlm(f, contents, ',') end end close(f) end function join_files(models::Array, files::Array, outfile::String, addlabel::Bool=true) m = length(files) contents = Array{Array,1}(undef, m) headers = Array{Array,1}(undef, m) len = 0 for i in 1:m contents[i], headers[i] = readdlm(files[i], ',', header=true) len += length(headers[i][2:end]) end f = open(outfile, "w") header = Array{String,1}(undef, 0) for i in 1:m if addlabel header = vcat(header, String.(headers[i][2:end]) .* "_G$(models[i])") else header = vcat(header, String.(headers[i][2:end])) end end header = reshape(permutedims(header), (1, len)) header = hcat(headers[1][1], header) println(header) writedlm(f, header, ',') for row in 1:size(contents[1], 1) content = contents[1][row:row, 2:end] for i in 1:m-1 if contents[i][row, 1] == contents[i+1][row, 1] content = hcat(content, contents[i+1][row:row, 2:end]) # content = reshape(permutedims(content),(1,len)) end end content = hcat(contents[1][row:row, 1], content) writedlm(f, [content], ',') end close(f) end function sample_non1_genes(infile, n) contents, head = readdlm(infile, ',', header=true) list = Array{String,1}(undef, 0) for c in eachrow(contents) if c[5] != 1 push!(list, c[1]) end end a = StatsBase.sample(list, n, replace=false) end function add_best_burst(filein, fileout, filemodel2, filemodel3) contents, head = readdlm(filein, ',', header=true) burst2, head2 = readdlm(filemodel2, ',', header=true) burst3, head3 = readdlm(filemodel3, ',', header=true) f = open(fileout, "w") head = hcat(head, ["mean off period" "bust size"]) writedlm(f, head, ',') for row in eachrow(contents) if Int(row[end]) == 2 writedlm(f, hcat(permutedims(row), permutedims(burst2[findfirst(burst2[:, 1] .== row[1]), 2:3])), ',') else writedlm(f, hcat(permutedims(row), permutedims(burst3[findfirst(burst3[:, 1] .== row[1]), 2:3])), ',') end end close(f) end function add_best_occupancy(filein, fileout, filemodel2, filemodel3) contents, head = readdlm(filein, ',', header=true) occupancy2, head2 = readdlm(filemodel2, ',', header=true) occupancy3, head3 = readdlm(filemodel3, ',', header=true) f = open(fileout, "w") head = hcat(head, ["Off -2" "Off -1" "On State"]) writedlm(f, head, ',') for row in eachrow(contents) if Int(row[end-2]) == 2 writedlm(f, hcat(permutedims(row), hcat("NA", permutedims(occupancy2[findfirst(occupancy2[:, 1] .== row[1]), 2:end]))), ',') else writedlm(f, hcat(permutedims(row), permutedims(occupancy3[findfirst(occupancy3[:, 1] .== row[1]), 2:end])), ',') end end close(f) end function prune_file(list, file, outfile, header=true) contents, head = readdlm(file, ',', header=header) f = open(outfile, "w") for c in eachrow(contents) if c[1] in list writedlm(f, [c], ',') end end close(f) end function replace_yield(G, folder1, folder2, cond1, cond2, outfolder) if typeof(G) <: Number G = string(G) end if ~isdir(outfolder) mkpath(outfolder) end files1 = getratefile(folder1, G, cond1) files2 = getratefile(folder2, G, cond2) for file1 in files1 gene = get_gene(file1) file2 = getratefile(files2, gene) outfile = joinpath(outfolder, file2) r1 = readrates(joinpath(folder1, file1)) r2 = readrates(joinpath(folder2, file2)) r2[end] = r1[end] f = open(outfile, "w") writedlm(f, [r2], ',') close(f) end end """ assemble_r(G,folder1,folder2,cond1,cond2,outfolder) Combine rates from two separate fits into a single rate vector """ function assemble_r(G, folder1, folder2, cond1, cond2, outfolder) if typeof(G) <: Number G = string(G) end if ~isdir(outfolder) mkpath(outfolder) end files1 = getratefile(folder1, G, cond1) files2 = getratefile(folder2, G, cond2) for file1 in files1 gene = get_gene(file1) file2 = getratefile(files2, gene) if file2 != 0 file2 = joinpath(folder2, file2) else file2 = joinpath(folder1, file1) end name = replace(file1, cond1 => cond1 * "-" * cond2) outfile = joinpath(outfolder, name) assemble_r(joinpath(folder1, file1), file2, outfile) end end function assemble_r(ratefile1, ratefile2, outfile) r1 = readrates(ratefile1, 2) r2 = readrates(ratefile2, 2) r1[end] = clamp(r1[end], eps(Float64), 1 - eps(Float64)) r = vcat(r1[1:end-1], r2[1:end-1], r1[end]) f = open(outfile, "w") writedlm(f, [r], ',') writedlm(f, [r], ',') writedlm(f, [r], ',') writedlm(f, [r], ',') close(f) end function assemble_r(gene, G, folder1, folder2, cond1, cond2, outfolder) file1 = getratefile(gene, G, folder1, cond1)[1] file2 = getratefile(gene, G, folder2, cond2)[1] name = replace(file1, cond1 => cond1 * "-" * cond2) println(name) outfile = joinpath(outfolder, name) println(outfile) assemble_r(joinpath(folder1, file1), joinpath(folder2, file2), outfile) end function getratefile(files, gene) files = files[occursin.("_" * gene * "_", files)] if length(files) > 0 return files[1] else # println(gene) return 0 end end function getratefile(folder, G, cond) files = readdir(folder) files = files[occursin.("rates_", files)] files = files[occursin.("_" * cond * "_", files)] files[occursin.("_" * G * "_", files)] end getratefile(gene, G, folder, cond) = getfile("rate", gene, G, folder, cond) function getfile(type, gene::String, G::String, folder, cond) files = readdir(folder) files = files[occursin.(type, files)] files = files[occursin.("_" * gene * "_", files)] files = files[occursin.("_" * G * "_", files)] files[occursin.("_" * cond * "_", files)] end function change_name(folder, oldname, newname) files = readdir(folder) files = files[occursin.(oldname, files)] for file in files newfile = replace(file, oldname => newname) mv(joinpath(folder, file), joinpath(folder, newfile), force=true) end end function make_halflife(infile, outfile, col=4) f = open(outfile, "w") writedlm(f, ["Gene" "Halflife"], ',') contents, rows = readdlm(infile, ',', header=true) for row = eachrow(contents) gene = string(row[1]) gene = strip(gene, '*') h1 = float(row[col]) h2 = float(row[col+1]) if h1 > 0 || h2 > 0 h = (h1 + h2) / (float(h1 > 0) + float(h2 > 0)) writedlm(f, [gene h], ',') end end nothing end function make_datafiles(infolder, outfolder, label) histograms = readdir(infolder) if ~isdir(outfolder) mkpath(outfolder) end for file in histograms newfile = replace(file, label => "") cp(joinpath(infolder, file), joinpath(outfolder, newfile)) end end """ histograms(r,cell,cond,n::Int,datapath,root) """ function histograms(rin, cell, cond, G::Int, datapath, root) fish = false gene = string(rin[1]) r = float.(rin[2:end]) data = data_rna(gene, cond, datapath, fish, "label", root) nalleles = alleles(gene, cell, root) model = model_rna(r, [], G, nalleles, 0.01, [], (), fish) likelihoodarray(r, data, model) end function get_histogram_rna(gene, datacond, datapath) _, h = read_rna(gene, datacond, datapath) normalize_histogram(h) end # function get_histogram_rna(gene, cond, datapath, root) # fish = false # if fish # datapath = FISHpath(gene, cond, datapath, root) # h = read_fish(datapath, cond, 0.98) # else # datapath = scRNApath(gene, cond, datapath, root) # h = read_scrna(datapath, 0.99) # end # normalize_histogram(h) # end # function get_histogram_rna(gene, cond, datapath) # if fish # datapath = FISHpath(gene, cond, datapath) # h = read_fish(datapath, cond, 0.98) # else # datapath = scRNApath(gene, cond, datapath) # h = read_scrna(datapath, 0.99) # end # normalize_histogram(h) # end function make_ONOFFhistograms(folder::String, bins=collect(1.0:200.0)) files = get_resultfiles(folder) for (root, dirs, files) in walkdir(folder) for f in files if occursin("rates", f) parts = fields(f) G, R, S, insertstep = decompose_model(parts.model) r = readrates(joinpath(root, f)) out = joinpath(root, replace(f, "rates" => "ONOFF", ".txt" => ".csv")) transitions = get_transitions(G, parts.label) make_ONOFFhistograms(r, transitions, G, R, S, insertstep, bins, outfile=out) end end end end """ make_ONOFFhistograms(r, transitions, G, R, S, insertstep, bins; outfile::String="") simulations and master equation solutions of dwell time histograms """ function make_ONOFFhistograms(r, transitions, G, R, S, insertstep, bins; outfile::String="", simulate=false) onstates = on_states(G, R, S, insertstep) components = make_components_TAI(transitions, G, R, S, insertstep, onstates, "") T = make_mat_T(components, r) TA = make_mat_TA(components, r) TI = make_mat_TI(components, r) OFF, ON = offonPDF(bins, r, T, TA, TI, components.nT, components.elementsT, onstates) if simulate hs = simulator(r, transitions, G, R, S, insertstep, bins=bins) df = DataFrame(time=bins, ON=ON, OFF=OFF, SimON=hs[2] / sum(hs[2]), SimOFF=hs[3] / sum(hs[3])) else df = DataFrame(time=bins, ON=ON, OFF=OFF) end if ~isempty(outfile) CSV.write(outfile, df) end return df end """ tcomponent(model) return tcomponent of model """ tcomponent(model) = typeof(model.components) == TComponents ? model.components : model.components.tcomponents """ write_traces_folder(folder, datafolder, datacond, interval, ratetype::String="median", start=1, stop=-1, probfn=prob_Gaussian, noiseparams=4, weightind=0, splicetype="") TBW """ function write_traces_folder(folder, datafolder, datacond, interval, ratetype::String="median", start=1, stop=-1, probfn=prob_Gaussian, noiseparams=4, weightind=0, splicetype=""; state=false) datafolders = readdir(datafolder) for d in datafolders if ~occursin(".DS_Store", d) for (root, dirs, files) in walkdir(folder) if occursin(d, root) println(d) for f in files if occursin("rates", f) && occursin(datacond, f) parts = fields(f) G, R, S, insertstep = decompose_model(parts.model) r = readrates(joinpath(root, f), get_row(ratetype)) out = joinpath(root, replace(f, "rates" => "predictedtraces", ".txt" => ".csv")) transitions = get_transitions(G, parts.label) datapath = joinpath(datafolder,) # make_traces(r, datapath, datacond, transitions, G, R, S, insertstep, traceinfo, splicetype, probfn, noiseparams, weightind, outfile=out) write_traces(out, datapath, datacond, interval, r, transitions, G, R, S, insertstep, start, stop, probfn, noiseparams, weightind, splicetype, state=state) end end end end end end end """ write_traces(folder, datapath, datacond, interval, ratetype::String="median", start=1, stop=-1, probfn=prob_Gaussian, noiseparams=4, weightind=0, splicetype=""; state=false) """ function write_traces(folder, datapath, datacond, interval, ratetype::String="median", start=1, stop=-1, probfn=prob_Gaussian, noiseparams=4, weightind=0, splicetype=""; state=false, hierarchical=false) for (root, dirs, files) in walkdir(folder) for f in files if occursin("rates", f) && occursin(datacond, f) parts = fields(f) G, R, S, insertstep = decompose_model(parts.model) r = readrates(joinpath(root, f), get_row(ratetype)) out = joinpath(root, replace(f, "rates" => "predictedtraces", ".txt" => ".csv")) transitions = get_transitions(G, parts.label) # make_traces(r, datapath, datacond, transitions, G, R, S, insertstep, traceinfo, splicetype, probfn, noiseparams, weightind, outfile=out) write_traces(out, datapath, datacond, interval, r, transitions, G, R, S, insertstep, start, stop, probfn, noiseparams, weightind, splicetype, state=state, hierarchical=hierarchical) end end end end """ write_traces(outfile,datapath, datacond, interval::Float64, r::Vector, transitions, G::Int, R::Int, S::Int, insertstep::Int, start::Int=1, stop=-1, probfn=prob_Gaussian, noiseparams=4, weightind=0, splicetype="";state =false) """ function write_traces(outfile, datapath, datacond, interval::Float64, r::Vector, transitions, G::Int, R::Int, S::Int, insertstep::Int, start::Int=1, stop=-1, probfn=prob_Gaussian, noiseparams=4, weightind=0, splicetype=""; state=false, hierarchical=false) df = make_traces_dataframe(datapath, datacond, interval, r, transitions, G, R, S, insertstep, start, stop, probfn, noiseparams, weightind, splicetype, state, hierarchical) CSV.write(outfile, df) end function make_traces_dataframe(datapath, datacond, interval, r, transitions, G, R, S, insertstep, start=1, stop=-1, probfn=prob_Gaussian, noiseparams=4, weightind=0, splicetype="", state=false, hierarchical=false) tp, ts, traces = make_traces(datapath, datacond, interval, r, transitions, G, R, S, insertstep, start, stop, probfn, noiseparams, weightind, splicetype, hierarchical) l = maximum(length.(tp)) data = ["data$i" => [traces[i]; fill(missing, l - length(traces[i]))] for i in eachindex(traces)] pred = ["model$i" => [tp[i]; fill(missing, l - length(tp[i]))] for i in eachindex(tp)] if state g, z, zdigits, r = inverse_state(ts,G,R,S,insertstep) gs = ["Gstate$i" => [g[i]; fill(missing, l - length(g[i]))] for i in eachindex(g)] # tss = ["State$i" => [ts[i]; fill(missing, l - length(g[i]))] for i in eachindex(g)] s = ["Rstate$i" => [zdigits[i]; fill(missing, l - length(g[i]))] for i in eachindex(g)] # ss = ["Z$i" => [z[i]; fill(missing, l - length(g[i]))] for i in eachindex(g)] zs = ["Reporters$i" => [r[i]; fill(missing, l - length(g[i]))] for i in eachindex(g)] v = [data pred gs s zs] else v = [data pred] end # v = state ? [data pred ["state$i" => [mod.(ts[i] .- 1, G) .+ 1; fill(missing, l - length(ts[i]))] for i in eachindex(ts)]] : [data pred] # df = DataFrame(["trace$i" => [tp[i]; fill(missing, l - length(tp[i]))] for i in eachindex(tp)]) DataFrame(permutedims(v, (2, 1))[:]) end """ make_traces(datapath, datacond, interval, r, transitions, G, R, S, insertstep, start=1.0, stop=-1, probfn=prob_Gaussian, noiseparams=4, weightind=0, splicetype="") """ function make_traces(datapath, datacond, interval, rin::Vector, transitions, G, R, S, insertstep, start=1, stop=-1, probfn=prob_Gaussian, noiseparams=4, weightind=0, splicetype="", hierarchical=false) traces = read_tracefiles(datapath, datacond, start, stop) nrates = num_rates(transitions, R, S, insertstep) + noiseparams hierarchical && (rin = reshape(rin[2*nrates+1:end], nrates, length(traces))) tp = Vector{Float64}[] ts = Vector{Int}[] tcomponents = make_components_T(transitions, G, R, S, insertstep, splicetype) reporter = HMMReporter(noiseparams, num_reporters_per_state(G, R, S, insertstep), probfn, weightind, off_states(G, R, S, insertstep)) for (i, t) in enumerate(traces) r = hierarchical ? rin[:, i] : rin a, b = make_trace(t, interval, r, tcomponents, reporter) push!(tp, a) push!(ts, b) end return tp, ts, traces end """ make_trace(trace, interval, r, transitions, G, R, S, insertstep, probfn=prob_Gaussian, noiseparams=4, weightind=0, splicetype="") """ function make_trace(trace, interval, r::Vector, transitions, G, R, S, insertstep, probfn=prob_Gaussian, noiseparams=4, weightind=0, splicetype="") tcomponents = make_components_T(transitions, G, R, S, insertstep, splicetype) reporter = HMMReporter(noiseparams, num_reporters_per_state(G, R, S, insertstep), probfn, weightind) make_trace(trace, interval, r::Vector, tcomponents, reporter) end """ make_trace(trace, interval, r::Vector, tcomponents, probfn=prob_Gaussian, noiseparams=4, weightind=0) TBW """ function make_trace(trace, interval, r::Vector, tcomponents, reporter) d = reporter.probfn(r[end-reporter.n+1:end], reporter.per_state, tcomponents.nT) predicted_trace_state(trace, interval, r, tcomponents, reporter, d) end function make_correlation(interval, r::Vector, transitions, G, R, S, insertstep, probfn=prob_Gaussian, noiseparams=4, weightind=0, splicetype="") reporter = HMMReporter(noiseparams, num_reporters_per_state(G, R, S, insertstep), probfn, weightind) tcomponents = make_components_T(transitions, G, R, S, insertstep, splicetype) Qtr = make_mat(tcomponents.elementsT, r, N) ## transpose of the Markov process transition rate matrix Q kolmogorov_forward(sparse(Qtr'), interval, true) end function make_trace_histogram(datapath, datacond, start=1, stop=-1) traces = read_tracefiles(datapath, datacond, start, stop) ft = reduce(vcat, traces) h = histogram(ft, normalize=true) return ft, h end function plot_traces(datapath, datacond, interval, r, transitions, G, R, S, insertstep, start=1.0, stop=-1, probfn=prob_Gaussian, noiseparams=4, weightind=0, splicetype="") tp, ts, traces = make_traces(datapath, datacond, interval, r::Vector, transitions, G, R, S, insertstep, start, stop, probfn, noiseparams, weightind, splicetype) end """ plot_traces(fits, stats, data, model, ratetype="median") """ function plot_trace(trace, interval, r, transitions, G, R, S, insertstep, probfn=prob_Gaussian, noiseparams=4, weightind=0, splicetype="") tp, ts = make_trace(trace, interval, r, transitions, G, R, S, insertstep, probfn, noiseparams, weightind, splicetype) plt = plot(trace) plt = plot!(tp) display(plt) return tp, ts end function plot_traces(fits, stats, data, model, index=1, ratetype="median") r = get_rates(fits, stats, model, ratetype) plot_traces(r, data, model, index) end function plot_traces(data::AbstractTraceData, model::AbstractGRSMmodel, index=1) tp, ts = predicted_traces(data, model) # M = make_mat_M(model.components.mcomponents, r[1:num_rates(model)]) # hist = steady_state(M, model.components.mcomponents.nT, model.nalleles, data.nRNA) # plt = Plots.Plot[] # for t in data.trace[1] # push!(plt, plot(collect(1:length(t)),t)) # end # push!(plt, scatter(collect(1:length(data.nRNA),data.histRNA / data.nRNA)) # push!(plt, plot(hist)) plt1 = scatter(data.trace[1][index]) plt1 = plot!(tp[index]) # plt2 = scatter(data.trace[1][10]) # plt2 = plot!(tp[10]) # plt3 = scatter(data.trace[1][20]) # plt3 = plot!(tp[20]) # plt4 = scatter(data.histRNA/data.nRNA) # plt4 = plot!(hist) # x = collect(1:length(tp[2])) # plt2 = plot(x, tp[1:2], layout=(2, 1), legend=false) display(plt1) return tp, ts end """ plot_histogram(ratefile::String, datapath; root=".", row=2) plot_histogram() plot_histogram(ratefile::String,datapath;fish=false,root=".",row=2) functions to plot data and model predicted histograms """ function plot_histogram(ratefile::String, datapath; root=".", row=2) fish = false r = readrow(ratefile, row) println(r) parts = fields(ratefile) label = parts.label cond = parts.cond G = parts.model data = data_rna(parts.gene, parts.cond, datapath, fish, parts.label, root) model = model_rna(r, r, parse(Int, parts.model), parse(Int, parts.nalleles), 0.01, [], (), 0) # model_rna(r,[rateprior[i]],G,nalleles,cv,[fittedparam[i]],fixedeffects,0) plot_histogram(data, model) return data, model end function test_sim(r, transitions, G, R, S, insertstep, nhist, nalleles, onstates, bins, total, tol) simulator(r, transitions, G, R, S, insertstep, nhist=nhist, nalleles=nalleles, onstates=onstates, bins=bins, totalsteps=total, tol=tol) end function plot_histogram(gene::String, cell::String, G::Int, cond::String, ratefile::String, datapath::String, root::String=".") fish = false rates = readdlm(ratefile, ',', header=true) r = rates[1][findfirst(rates[1][:, 1] .== gene)[1], 2:end] data = data_rna(gene, cond, datapath, fish, "label", root) nalleles = alleles(gene, cell, root) model = model_rna(r, [], G, nalleles, 0.01, [], (), 0) println(typeof(model)) println(typeof(data)) m = plot_histogram(data, model) return m, data, model end function plot_histogram(gene::String, cell::String, G::String, cond::String, label::String, ratefolder::String, datapath::String, nsets::Int, root::String, fittedparam=[1], verbose=false) fish = false data = data_rna(gene, cond, datapath, fish, label, root) model = model_rna(gene, cell, G, fish, 0.01, fittedparam, (), label, ratefolder, nsets, root, data, verbose) m = plot_histogram(data, model) return m, data, model end function plot_histogram(data::AbstractRNAData{Array{Array,1}}, model) h = likelihoodarray(model.rates, data, model) figure(data.gene) for i in eachindex(h) plot(h[i]) plot(normalize_histogram(data.histRNA[i])) savefig(string(i)) end return h end function plot_histogram(data::AbstractRNAData{Array{Float64,1}}, model) h = likelihoodfn(get_param(model), data, model) plt = plot(h) plot!(plt, normalize_histogram(data.histRNA)) display(plt) return h end function plot_histogram(data::RNAOnOffData, model::AbstractGmodel, filename="") h = likelihoodarray(model.rates, data, model) plt1 = plot(data.bins, h[1]) plot!(plt1, data.bins, normalize_histogram(data.OFF)) plt2 = plot(data.bins, h[2]) plot!(plt2, data.bins, normalize_histogram(data.ON)) plt3 = plot(h[3]) plot!(plt3, normalize_histogram(data.histRNA)) plt = plot(plt1, plt2, plt3, layout=(3, 1)) display(plt) if ~isempty(filename) savefig(filename) end return h end function plot_histogram(data::TraceRNAData, model::AbstractGmodel, filename="") M = make_mat_M(model.components.mcomponents, model.rates) h = steady_state(M, model.components.mcomponents.nT, model.nalleles, data.nRNA) plt = plot(h) plot!(plt, normalize_histogram(data.histRNA)) display(plt) if ~isempty(filename) savefig(filename) end return h end # function plot_histogram(data::TransientRNAData,model::AbstractGMmodel) # h=likelihoodarray(model.rates,data,model) # for i in eachindex(h) # figure(data.gene *":T" * "$(data.time[i])") # plot(h[i]) # plot(normalize_histogram(data.histRNA[i])) # end # return h # end function plot_histogram(data::RNAData{T1,T2}, model::AbstractGMmodel, save=false) where {T1<:Array,T2<:Array} m = likelihoodarray(model.rates, data, model) println("*") for i in eachindex(m) plt = plot(m[i]) plot!(normalize_histogram(data.histRNA[i]), show=true) if save savefig() else display(plt) end end println(deviance(data, model)) println(loglikelihood(get_param(model), data, model)[1]) return m end function plot_histogram(data::RNAData, model::AbstractGMmodel) h = likelihoodfn(get_param(model), data, model) plt = plot(h) plot!(normalize_histogram(data.histRNA)) display(plt) return h end # function plot_model(r,n,nhist,nalleles,yield) # h= steady_state(r[1:2*n+2],yield,n,nhist,nalleles) # plt = plot(h) # display(plt) # return h # end # function plot_model(r,n,nhist,nalleles) # h= steady_state(r[1:2*n+2],n,nhist,nalleles) # plt = plot(h) # display(plt) # return h # end
StochasticGene
https://github.com/nih-niddk-mbs/StochasticGene.jl.git
[ "MIT" ]
1.2.5
fc1bcee6037ea393ce28426929eff65c76a86779
code
29332
# This file is part of StochasticGene.jl # biowulf.jl # functions for use on the NIH Biowulf super computer """ struct ModelArgs For passing model information to fit function from swarmfile (limited to numbers and strings (i.e. no vectors or tuples)) #Fields `inlabel::String` `label::String` `G::Int` `R::Int` `S::Int` `insertstep::Int` `Gfamily::String`: type of model, e.g. "nstate", "KP", "cyclic" `fixedeffects::String`: two numbers separated by a hyphen, e.g. "3-4", indicating parameters 3 and 4 are fixed to each other """ struct ModelArgs inlabel::String label::String G::Int R::Int S::Int insertstep::Int Gfamily::String fixedeffects::String end """ makeswarm(;<keyword arguments>) write swarm and fit files used on biowulf #Arguments - 'nthreads::Int=1`: number of Julia threads per processesor, default = 1 - `swarmfile::String="fit"`: name of swarmfile to be executed by swarm - `juliafile::String="fitscript`: name of file to be called by julia in swarmfile - `src=""`: path to folder containing StochasticGene.jl/src (only necessary if StochasticGene not installed) and all keyword arguments of function fit(; <keyword arguments> ) see fit """ function makeswarm(; gene::String="", nchains::Int=2, nthreads::Int=1, swarmfile::String="fit", juliafile::String="fitscript", datatype::String="", dttype=String[], datapath="", cell::String="", datacond="", traceinfo=(1.0, 1.0, -1, 0.65), nascent=(1, 2), infolder::String="", resultfolder::String="test", inlabel::String="", label::String="", fittedparam::Vector=Int[], fixedeffects=tuple(), transitions::Tuple=([1, 2], [2, 1]), G::Int=2, R::Int=0, S::Int=0, insertstep::Int=1, Gfamily="", root=".", priormean=Float64[], nalleles=2, priorcv=10.0, onstates=Int[], decayrate=-1.0, splicetype="", probfn=prob_Gaussian, noisepriors=[], hierarchical=tuple(), ratetype="median", propcv=0.01, maxtime::Float64=60.0, samplesteps::Int=1000000, warmupsteps=0, annealsteps=0, temp=1.0, tempanneal=100.0, temprna=1.0, burst=false, optimize=false, writesamples=false, method=1, src="") modelstring = create_modelstring(G, R, S, insertstep) label, inlabel = create_label(label, inlabel, datatype, datacond, cell, Gfamily) juliafile = juliafile * "_" * label * "_" * "$modelstring" * ".jl" sfile = swarmfile * "_" * label * "_" * "$modelstring" * ".swarm" write_swarmfile(joinpath(root, sfile), nchains, nthreads, juliafile) write_fitfile(joinpath(root, juliafile), nchains, datatype, dttype, datapath, gene, cell, datacond, traceinfo, nascent, infolder, resultfolder, inlabel, label, fittedparam, fixedeffects, transitions, G, R, S, insertstep, root, maxtime, priormean, nalleles, priorcv, onstates, decayrate, splicetype, probfn, noisepriors, hierarchical, ratetype, propcv, samplesteps, warmupsteps, annealsteps, temp, tempanneal, temprna, burst, optimize, writesamples, method, src) end """ makeswarm_genes(genes::Vector{String}; <keyword arguments> ) write a swarmfile and fit files to run all each gene in vector genes # Arguments - `genes`: vector of genes - `batchsize=1000`: number of jobs per swarmfile, default = 1000 and all arguments in makeswarm(;<keyword arguments>) Examples julia> genes = ["MYC","SOX9"] julia> makeswarm(genes,cell="HBEC") """ function makeswarm(genes::Vector{String}; nchains::Int=2, nthreads::Int=1, swarmfile::String="fit", batchsize=1000, juliafile::String="fitscript", datatype::String="", dttype=String[], datapath="", cell::String="", datacond="", traceinfo=(1.0, 1.0, -1, 0.65), nascent=(1, 2), infolder::String="", resultfolder::String="test", inlabel::String="", label::String="", fittedparam::Vector=Int[], fixedeffects=tuple(), transitions::Tuple=([1, 2], [2, 1]), G::Int=2, R::Int=0, S::Int=0, insertstep::Int=1, Gfamily="", root=".", priormean=Float64[], nalleles=2, priorcv=10.0, onstates=Int[], decayrate=-1.0, splicetype="", probfn=prob_Gaussian, noisepriors=[], hierarchical=tuple(), ratetype="median", propcv=0.01, maxtime::Float64=60.0, samplesteps::Int=1000000, warmupsteps=0, annealsteps=0, temp=1.0, tempanneal=100.0, temprna=1.0, burst=false, optimize=false, writesamples=false, method=1, src="") modelstring = create_modelstring(G, R, S, insertstep) label, inlabel = create_label(label, inlabel, datatype, datacond, cell, Gfamily) ngenes = length(genes) println("number of genes: ", ngenes) juliafile = juliafile * "_" * label * "_" * "$modelstring" * ".jl" if ngenes > batchsize batches = getbatches(genes, ngenes, batchsize) for batch in eachindex(batches) sfile = swarmfile * "_" * label * "_" * "$modelstring" * "_" * "$batch" * ".swarm" write_swarmfile(sfile, nchains, nthreads, juliafile, batches[batch]) end else sfile = swarmfile * "_" * label * "_" * "$modelstring" * ".swarm" write_swarmfile(joinpath(root, sfile), nchains, nthreads, juliafile, genes) end write_fitfile(joinpath(root, juliafile), nchains, datatype, dttype, datapath, cell, datacond, traceinfo, nascent, infolder, resultfolder, inlabel, label, fittedparam, fixedeffects, transitions, G, R, S, insertstep, root, maxtime, priormean, nalleles, priorcv, onstates, decayrate, splicetype, probfn, noisepriors, hierarchical, ratetype, propcv, samplesteps, warmupsteps, annealsteps, temp, tempanneal, temprna, burst, optimize, writesamples, method, src) end """ makeswarm_genes(;<keyword arguments> ) @JuliaRegistrator register() #Arguments - `thresholdlow::Float=0`: lower threshold for halflife for genes to be fit - `threhsoldhigh::=Inf`: upper threshold and all keyword arguments in makeswarm(;<keyword arguments>) """ function makeswarm_genes(; nchains::Int=2, nthreads::Int=1, swarmfile::String="fit", batchsize::Int=1000, juliafile::String="fitscript", thresholdlow::Float64=0.0, thresholdhigh::Float64=Inf, datatype::String="", dttype::Vector=String[], datapath="", cell::String="HBEC", datacond="", traceinfo=(1.0, 1.0, 0.65), nascent=(1, 2), infolder::String="", resultfolder::String="test", inlabel::String="", label::String="", fittedparam::Vector=Int[], fixedeffects::Tuple=tuple(), transitions::Tuple=([1, 2], [2, 1]), G::Int=2, R::Int=0, S::Int=0, insertstep::Int=1, Gfamily="", root=".", priormean=Float64[], priorcv::Float64=10.0, nalleles=2, onstates=Int[], decayrate=-1.0, splicetype="", probfn=prob_Gaussian, noisepriors=[], hierarchical=tuple(), ratetype="median", propcv=0.01, maxtime::Float64=60.0, samplesteps::Int=1000000, warmupsteps=0, annealsteps=0, temp=1.0, tempanneal=100.0, temprna=1.0, burst=false, optimize=false, writesamples=false, method=1, src="") makeswarm(checkgenes(root, datacond, datapath, cell, thresholdlow, thresholdhigh), nchains=nchains, nthreads=nthreads, swarmfile=swarmfile, batchsize=batchsize, juliafile=juliafile, datatype=datatype, dttype=dttype, datapath=datapath, cell=cell, datacond=datacond, traceinfo=traceinfo, nascent=nascent, infolder=infolder, resultfolder=resultfolder, inlabel=inlabel, label=label, fittedparam=fittedparam, fixedeffects=fixedeffects, transitions=transitions, G=G, R=R, S=S, insertstep=insertstep, Gfamily=Gfamily, root=root, priormean=priormean, nalleles=nalleles, priorcv=priorcv, onstates=onstates, decayrate=decayrate, splicetype=splicetype, probfn=probfn, noisepriors=noisepriors, hierarchical=hierarchical, ratetype=ratetype, propcv=propcv, maxtime=maxtime, samplesteps=samplesteps, warmupsteps=warmupsteps, annealsteps=annealsteps, temp=temp, tempanneal=tempanneal, temprna=temprna, burst=burst, optimize=optimize, writesamples=writesamples, method=method, src=src) end """ makeswarm(models::Vector{ModelArgs}; <keyword arguments> ) creates a run for each model #Arguments - `models::Vector{ModelArgs}`: Vector of ModelArgs structures and all keyword arguments in makeswarm(;<keyword arguments>) """ function makeswarm(models::Vector{ModelArgs}; gene="", nchains::Int=2, nthreads::Int=1, swarmfile::String="fit", juliafile::String="fitscript", datatype::String="", dttype=String[], datapath="", cell::String="", datacond="", traceinfo=(1.0, 1.0, -1, 0.65), nascent=(1, 2), infolder::String="", resultfolder::String="test", root=".", priormean=Float64[], nalleles=2, priorcv=10.0, onstates=Int[], decayrate=-1.0, splicetype="", probfn=prob_Gaussian, noisepriors=[], hierarchical=tuple(), ratetype="median", propcv=0.01, maxtime::Float64=60.0, samplesteps::Int=1000000, warmupsteps=0, annealsteps=0, temp=1.0, tempanneal=100.0, temprna=1.0, burst=false, optimize=false, writesamples=false, method=1, src="") juliafile = juliafile * "_" * gene * "_" * datacond * ".jl" sfile = swarmfile * "_" * gene * "_" * datacond * ".swarm" write_swarmfile(joinpath(root, sfile), nchains, nthreads, juliafile, datatype, datacond, cell, models) write_fitfile(joinpath(root, juliafile), nchains, datatype, dttype, datapath, gene, cell, datacond, traceinfo, nascent, infolder, resultfolder, root, maxtime, priormean, nalleles, priorcv, onstates, decayrate, splicetype, probfn, noisepriors, hierarchical, ratetype, propcv, samplesteps, warmupsteps, annealsteps, temp, tempanneal, temprna, burst, optimize, writesamples, method, src) end """ write_swarmfile(sfile, nchains, nthreads, juliafile::String, project="") """ function write_swarmfile(sfile, nchains, nthreads, juliafile::String, project="") f = open(sfile, "w") if isempty(project) writedlm(f, ["julia -t $nthreads -p" nchains juliafile]) else writedlm(f, ["julia --project=$project -t $nthreads -p" nchains juliafile]) end close(f) end """ write_swarmfile(sfile, nchains, nthreads, juliafile, genes::Vector) write swarmfile for vector of genes """ function write_swarmfile(sfile, nchains, nthreads, juliafile::String, genes::Vector{String}, project="") f = open(sfile, "w") for gene in genes gene = check_genename(gene, "(") if isempty(project) writedlm(f, ["julia -t $nthreads -p" nchains juliafile gene]) else writedlm(f, ["julia --project=$project -t $nthreads -p" nchains juliafile gene]) end end close(f) end """ write_swarmfile(sfile, nchains, nthreads, juliafile, datatype, datacond, cell, models::Vector{ModelArgs}) write swarmfile for vector of models """ function write_swarmfile(sfile, nchains, nthreads, juliafile, datatype, datacond, cell, models::Vector{ModelArgs}, project="") f = open(sfile, "w") for model in models label, inlabel = create_label(model.label, model.inlabel, datatype, datacond, cell, model.Gfamily) if isempty(model.fixedeffects) fixedeffects = "1" else fixedeffects = model.fixedeffects end if isempty(project) writedlm(f, ["julia -t $nthreads -p" nchains juliafile inlabel label model.G model.R model.S model.insertstep model.Gfamily fixedeffects]) else writedlm(f, ["julia --project=$project -t $nthreads -p" nchains juliafile inlabel label model.G model.R model.S model.insertstep model.Gfamily fixedeffects]) end end close(f) end """ write_fitfile(fitfile, nchains, datatype, dttype, datapath, gene, cell, datacond, traceinfo, nascent, infolder, resultfolder, inlabel, label, fittedparam, fixedeffects, transitions, G, R, S, insertstep, root, maxtime, priormean, nalleles, priorcv, onstates, decayrate, splicetype, probfn, noisepriors, hierarchical, ratetype, propcv, samplesteps, warmupsteps, annealsteps, temp, tempanneal, temprna, burst, optimize, writesamples, method, src) """ function write_fitfile(fitfile, nchains, datatype, dttype, datapath, gene, cell, datacond, traceinfo, nascent, infolder, resultfolder, inlabel, label, fittedparam, fixedeffects, transitions, G, R, S, insertstep, root, maxtime, priormean, nalleles, priorcv, onstates, decayrate, splicetype, probfn, noisepriors, hierarchical, ratetype, propcv, samplesteps, warmupsteps, annealsteps, temp, tempanneal, temprna, burst, optimize, writesamples, method, src) s = '"' f = open(fitfile, "w") write_prolog(f, src) typeof(datapath) <: AbstractString && (datapath = "$s$datapath$s") typeof(datacond) <: AbstractString && (datacond = "$s$datacond$s") write(f, "@time fit($nchains, $s$datatype$s, $dttype, $datapath, $s$gene$s, $s$cell$s, $datacond, $traceinfo, $nascent, $s$infolder$s, $s$resultfolder$s, $s$inlabel$s, $s$label$s,$fittedparam, $fixedeffects, $transitions, $G, $R, $S, $insertstep, $s$root$s, $maxtime, $priormean, $priorcv, $nalleles, $onstates, $decayrate, $s$splicetype$s, $probfn, $noisepriors, $hierarchical, $s$ratetype$s,$propcv, $samplesteps, $warmupsteps, $annealsteps, $temp, $tempanneal, $temprna, $burst, $optimize, $writesamples, $method)") close(f) end """ write_fitfile(fitfile, nchains, datatype, dttype, datapath, cell, datacond, traceinfo, nascent, infolder, resultfolder, inlabel, label, fittedparam, fixedeffects, transitions, G, R, S, insertstep, root, maxtime, priormean, nalleles, priorcv, onstates, decayrate, splicetype, probfn, noisepriors, hierarchical, ratetype, propcv, samplesteps, warmupsteps, annealsteps, temp, tempanneal, temprna, burst, optimize, writesamples, src) write fitfile for genes """ function write_fitfile(fitfile, nchains, datatype, dttype, datapath, cell, datacond, traceinfo, nascent, infolder, resultfolder, inlabel, label, fittedparam, fixedeffects, transitions, G, R, S, insertstep, root, maxtime, priormean, nalleles, priorcv, onstates, decayrate, splicetype, probfn, noisepriors, hierarchical, ratetype, propcv, samplesteps, warmupsteps, annealsteps, temp, tempanneal, temprna, burst, optimize, writesamples, method, src) s = '"' # s3 = s * s * s f = open(fitfile, "w") if isempty(src) write(f, "@everywhere using StochasticGene\n") else write(f, "@everywhere include($s$src$s)\n") write(f, "@everywhere using .StochasticGene\n") end typeof(datapath) <: AbstractString && (datapath = "$s$datapath$s") typeof(datacond) <: AbstractString && (datacond = "$s$datacond$s") write(f, "@time fit($nchains, $s$datatype$s, $dttype, $datapath, ARGS[1], $s$cell$s, $datacond, $traceinfo, $nascent, $s$infolder$s, $s$resultfolder$s, $s$inlabel$s, $s$label$s,$fittedparam, $fixedeffects, $transitions, $G, $R, $S, $insertstep, $s$root$s, $maxtime, $priormean, $priorcv, $nalleles, $onstates, $decayrate, $s$splicetype$s, $probfn, $noisepriors, $hierarchical, $s$ratetype$s,$propcv, $samplesteps, $warmupsteps, $annealsteps, $temp, $tempanneal, $temprna, $burst, $optimize, $writesamples, $method)") close(f) end """ write_fitfile(fitfile, nchains, datatype, dttype, datapath, gene, cell, datacond, traceinfo, nascent, infolder, resultfolder, root, maxtime, priormean, nalleles, priorcv, onstates, decayrate, splicetype, probfn, noisepriors, hierarchical, ratetype, propcv, samplesteps, warmupsteps, annealsteps, temp, tempanneal, temprna, burst, optimize, writesamples, method, src) write fitfile for models """ function write_fitfile(fitfile, nchains, datatype, dttype, datapath, gene, cell, datacond, traceinfo, nascent, infolder, resultfolder, root, maxtime, priormean, nalleles, priorcv, onstates, decayrate, splicetype, probfn, noisepriors, hierarchical, ratetype, propcv, samplesteps, warmupsteps, annealsteps, temp, tempanneal, temprna, burst, optimize, writesamples, method, src) s = '"' f = open(fitfile, "w") if isempty(src) write(f, "@everywhere using StochasticGene\n") else write(f, "@everywhere include($s$src$s)\n") write(f, "@everywhere using .StochasticGene\n") end typeof(datapath) <: AbstractString && (datapath = "$s$datapath$s") typeof(datacond) <: AbstractString && (datacond = "$s$datacond$s") write(f, "@time fit($nchains, $s$datatype$s, $dttype, $datapath, $s$gene$s, $s$cell$s, $datacond, $traceinfo, $nascent, $s$infolder$s, $s$resultfolder$s, ARGS[1], ARGS[2], ARGS[8], ARGS[3], ARGS[4], ARGS[5], ARGS[6], ARGS[7], $s$root$s, $maxtime, $priormean, $priorcv, $nalleles, $onstates, $decayrate, $s$splicetype$s, $probfn, $noisepriors, $hierarchical, $s$ratetype$s,$propcv, $samplesteps, $warmupsteps, $annealsteps, $temp, $tempanneal, $temprna, $burst, $optimize, $writesamples, $method)") close(f) end """ write_prolog(f,src) if src is empty assume StochasticGene is installed as a Julia package """ function write_prolog(f, src) s = '"' if isempty(src) write(f, "@everywhere using StochasticGene\n") else write(f, "@everywhere include($s$src$s)\n") write(f, "@everywhere using .StochasticGene\n") end end """ create_label(label,inlabel,datacond,cell,Gfamily) """ function create_label(label, inlabel, datatype, datacond, cell, Gfamily) if isempty(label) label = datatype * "-" * cell ~isempty(Gfamily) && (label = label * "-" * Gfamily) typeof(datacond) <: AbstractString && (label = label * "_" * datacond) end isempty(inlabel) && (inlabel = label) return label, inlabel end """ create_modelstring(G,R,S,insertstep) """ function create_modelstring(G, R, S, insertstep) if R > 0 if S > 0 S = R - insertstep + 1 end return "$G$R$S$insertstep" else return "$G" end end """ fix(folder) Finds jobs that failed and writes a swarmfile for those genes """ fix(folder) = writeruns(fixruns(findjobs(folder))) function fix_filenames(folder, old="scRNA-ss-", new="scRNA-ss_") files = readdir(folder) for file in files if occursin(old, file) nfile = replace(file, old => new) mv(joinpath(folder, file), joinpath(folder, nfile), force=true) end end end """ setup(rootfolder = "scRNA") Sets up the folder system prior to use Defaults to "scRNA" """ function rna_setup(root=".") folder_setup(root) alleles = joinpath(data, "alleles") halflives = joinpath(data, "halflives") testdata = joinpath(data, "HCT116_testdata") if ~ispath(alleles) mkpath(alleles) end Downloads.download("https://raw.githubusercontent.com/nih-niddk-mbs/StochasticGene.jl/master/data/alleles/CH12_alleles.csv", "$alleles/CH12_alleles.csv") Downloads.download("https://raw.githubusercontent.com/nih-niddk-mbs/StochasticGene.jl/master/data/alleles/HCT116_alleles.csv", "$alleles/HCT116_alleles.csv") if ~ispath(halflives) mkpath(halflives) end Downloads.download("https://raw.githubusercontent.com/nih-niddk-mbs/StochasticGene.jl/master/data/halflives/ESC_halflife.csv", "$halflives/ESC_halflife.csv") Downloads.download("https://raw.githubusercontent.com/nih-niddk-mbs/StochasticGene.jl/master/data/halflives/CH12_halflife.csv", "$halflives/CH12_halflife.csv") Downloads.download("https://raw.githubusercontent.com/nih-niddk-mbs/StochasticGene.jl/master/data/halflives/HCT116_halflife.csv", "$halflives/HCT116_halflife.csv") Downloads.download("https://raw.githubusercontent.com/nih-niddk-mbs/StochasticGene.jl/master/data/halflives/OcaB_halflife.csv", "$halflives/OcaB_halflife.csv") Downloads.download("https://raw.githubusercontent.com/nih-niddk-mbs/StochasticGene.jl/master/data/halflives/aB_halflife.csv", "$halflives/aB_halflife.csv") Downloads.download("https://raw.githubusercontent.com/nih-niddk-mbs/StochasticGene.jl/master/data/halflives/aB_halflife.csv", "$halflives/CAST_halflife.csv") Downloads.download("https://raw.githubusercontent.com/nih-niddk-mbs/StochasticGene.jl/master/data/halflives/aB_halflife.csv", "$halflives/FIBS_halflife.csv") Downloads.download("https://raw.githubusercontent.com/nih-niddk-mbs/StochasticGene.jl/master/data/halflives/aB_halflife.csv", "$halflives/MAST_halflife.csv") Downloads.download("https://raw.githubusercontent.com/nih-niddk-mbs/StochasticGene.jl/master/data/halflives/aB_halflife.csv", "$halflives/NK_halflife.csv") Downloads.download("https://raw.githubusercontent.com/nih-niddk-mbs/StochasticGene.jl/master/data/halflives/aB_halflife.csv", "$halflives/TEC_halflife.csv") Downloads.download("https://raw.githubusercontent.com/nih-niddk-mbs/StochasticGene.jl/master/data/halflives/aB_halflife.csv", "$halflives/SKIN_halflife.csv") if ~ispath(testdata) mkpath(testdata) end Downloads.download("https://raw.githubusercontent.com/nih-niddk-mbs/StochasticGene.jl/master/data/HCT116_testdata/CENPL_MOCK.txt", "$testdata/CENPL_MOCK.txt") Downloads.download("https://raw.githubusercontent.com/nih-niddk-mbs/StochasticGene.jl/master/data/HCT116_testdata/MYC_MOCK.txt", "$testdata/MYC_MOCK.txt") end """ folder_setup(root=".") creates data and results folders (if they do not already exit) """ function folder_setup(root=".") data = joinpath(root, "data") results = joinpath(root, "results") if ~ispath(data) mkpath(data) end if ~ispath(results) mkpath(results) end end """ getbatches(genes, ngenes, batchsize) """ function getbatches(genes, ngenes, batchsize) nbatches = div(ngenes, batchsize) batches = Vector{Vector{String}}(undef, nbatches + 1) println(batchsize, " ", nbatches + 1) for i in 1:nbatches batches[i] = genes[batchsize*(i-1)+1:batchsize*(i)] end batches[end] = genes[batchsize*nbatches+1:end] return batches end """ checkgenes(root, conds, datapath, celltype::String, thresholdlow::Float64, thresholdhigh::Float64) """ function checkgenes(root, conds, datapath, celltype::String, thresholdlow::Float64, thresholdhigh::Float64) genes = Vector{Vector{String}}(undef, 0) typeof(conds) <: AbstractString && (conds = [conds]) typeof(datapath) <: AbstractString && (datapath = [datapath]) for d in datapath, c in conds push!(genes, checkgenes(root, c, d, celltype, thresholdlow, thresholdhigh)) end geneset = genes[1] for g in genes genesest = intersect(geneset, g) end return geneset end """ checkgenes(root, cond::String, datapath::String, cell::String, thresholdlow::Float64, thresholdhigh::Float64) """ function checkgenes(root, cond::String, datapath::String, cell::String, thresholdlow::Float64, thresholdhigh::Float64) if cell == "HBEC" return genes_hbec() else datapath = folder_path(datapath, root, "data") genes = intersect(get_halflives(root, cell, thresholdlow, thresholdhigh), get_genes(cond, datapath)) alleles = get_alleles(root, cell) if ~isnothing(alleles) return intersect(genes, alleles) else return genes end end end """ folder_path(folder::String, root::String, folderatetype::String=""; make=false) """ function folder_path(folder::String, root::String, folderatetype::String=""; make=false) f = folder if ~ispath(folder) && ~isempty(folder) f = joinpath(root, folder) if ~ispath(f) f = joinpath(root, folderatetype, folder) if ~ispath(f) && ~make println("$folder not found") else mkpath(f) end end end f end """ folder_path(folder::Vector, root, foldertype) TBW """ function folder_path(folder::Vector, root, foldertype) fv = folder for i in eachindex(fv) fv[i] = folder_path(fv[i], root, foldertype) end fv end """ get_halflives(root, cell, thresholdlow::Float64, thresholdhigh::Float64) TBW """ function get_halflives(root, cell, thresholdlow::Float64, thresholdhigh::Float64) path = get_file(root, "data/halflives", cell, "csv") get_halflives(path, thresholdlow, thresholdhigh) end """ get_halflives(hlpath, thresholdlow::Float64, thresholdhigh::Float64) TBW """ function get_halflives(hlpath, thresholdlow::Float64, thresholdhigh::Float64) genes = Vector{String}(undef, 0) halflives = readdlm(hlpath, ',') for row in eachrow(halflives) if typeof(row[2]) <: Number if thresholdlow <= row[2] < thresholdhigh push!(genes, string(row[1])) end end end return genes end """ get_alleles(allelepath) get_alleles(root, cell) = get_alleles(get_file(root, "data/alleles", cell, "csv")) TBW """ function get_alleles(allelepath) if ~isnothing(allelepath) return readdlm(allelepath, ',')[2:end, 1] else return nothing end end get_alleles(root, cell) = get_alleles(get_file(root, "data/alleles", cell, "csv")) get_file(root, folder, filetype, suffix) = get_file(joinpath(root, folder), filetype, suffix) """ get_file(folder, filetype, suffix) get_file(root, folder, filetype, suffix) = get_file(joinpath(root, folder), filetype, suffix) TBW """ function get_file(folder, filetype, suffix) if ispath(folder) files = readdir(folder) for file in files name = split(file, "_")[1] if occursin(suffix, file) && name == filetype path = joinpath(folder, file) return path end end else println("folder $folder does not exist") return nothing end end """ findjobs(folder) TBW """ function findjobs(folder) files = readdir(folder) files = files[occursin.("swarm_", files)] for (i, file) in enumerate(files) files[i] = split(file, "_")[2] end unique(files) end """ fixruns(jobs, message="FAILED") TBW """ function fixruns(jobs, message="FAILED") runlist = Vector{String}(undef, 0) for job in jobs if occursin(message, read(`jobhist $job`, String)) swarmfile = findswarm(job) list = readdlm(swarmfile, ',') runs = chomp(read(pipeline(`jobhist $job`, `grep $message`), String)) runs = split(runs, '\n') println(job) for run in runs linenumber = parse(Int, split(split(run, " ")[1], "_")[2]) + 1 while linenumber < length(list) a = String(list[linenumber]) linenumber += 1000 println(a) push!(runlist, a) end end end end return runlist end """ writeruns(runs, outfile="fitfix.swarm") TBW """ function writeruns(runs, outfile="fitfix.swarm") f = open(outfile, "w") for run in runs writedlm(f, [run], quotes=false) end close(f) end """ findswarm(job) TBW """ function findswarm(job) sc = "Swarm Command" line = read(pipeline(`jobhist $job`, `grep $sc`), String) list = split(line, " ") list[occursin.(".swarm", list)][1] end """ get_missing_genes(datapath::String,folder::String,cell,type,label,cond,model) """ """ get_missing_genes(datapath::String, resultfolder::String, cell, filetype, label, cond, model, root=".") TBW """ function get_missing_genes(datapath::String, resultfolder::String, cell, filetype, label, cond, model, root=".") genes = checkgenes(root, cond, datapath, cell, 0.0, 1e8) get_missing_genes(genes, folder_path(resultfolder, root, "results"), filetype, label, cond, model) end """ get_missing_genes(genes::Vector, resultfolder, filetype, label, cond, model) TBW """ function get_missing_genes(genes::Vector, resultfolder, filetype, label, cond, model) genes1 = get_genes(resultfolder, filetype, label, cond, model) get_missing_genes(genes, genes1) end get_missing_genes(genes, genes1) = union(setdiff(genes1, genes), setdiff(genes, genes1)) """ scan_swarmfiles(jobid, folder=".") TBW """ function scan_swarmfiles(jobid, folder=".") if ~(typeof(jobid) <: String) jobid = string(jobid) end genes = Array{String,1}(undef, 0) files = readdir(folder) files = files[occursin.(jobid, files)] for file in files genes = vcat(genes, scan_swarmfile(file)) end return genes end """ scan_swarmfile(file) TBW """ function scan_swarmfile(file) genes = Array{String,1}(undef, 0) contents = readdlm(file, '\t') lines = contents[occursin.("[\"", string.(contents))] for line in lines push!(genes, split.(string(line), " ")[1]) end return genes end """ scan_fitfile(file, folder=".") TBW """ function scan_fitfile(file, folder=".") genes = Array{String,1}(undef, 0) joinpath(folder, file) file = readdlm(file, '\t') for line in eachrow(file) push!(genes, line[4]) end return genes end """ new_FISHfolder(newroot::String, oldroot::String, rep::String) TBW """ function new_FISHfolder(newroot::String, oldroot::String, rep::String) for (root, dirs, files) in walkdir(oldroot) for dir in dirs if occursin(rep, dir) oldtarget = joinpath(root, dir) newtarget = replace(oldtarget, oldroot => newroot) println(newtarget) if !ispath(newtarget) mkpath(newtarget) end cp(oldtarget, newtarget, force=true) end end end end
StochasticGene
https://github.com/nih-niddk-mbs/StochasticGene.jl.git
[ "MIT" ]
1.2.5
fc1bcee6037ea393ce28426929eff65c76a86779
code
10293
# This file is part of StochasticGene.jl # # chemical_master.jl # # Functions to solve the chemical master equation # operates on the transpose of the Markov process transition rate matrix # Functions to compute steady state mRNA histograms """ steady_state(M,nT,nalleles,nhist) steady_state(M,nT,nalleles) return steady state mRNA histogram for G and GR models computes null space of the truncated full transition matrix. -`M`: Truncated full transition rate matrix including transcription state transitions (GR) and mRNA birth and death -`nT`: dimension of state transitions """ steady_state(M, nT, nalleles, nhist) = steady_state(M, nT, nalleles)[1:nhist] function steady_state(M, nT, nalleles) P = normalized_nullspace(M) mhist = marginalize(P, nT) allele_convolve(mhist, nalleles) end # Functions to compute dwell time distributions """ dwelltimeCDF(tin::Vector, Td::AbstractMatrix, barrier, Sinit::Vector, method::Int=1) return dwell time CDF (cumulative distribution function) to reach barrier states starting from Sinit in live states live U barrier = all states First passage time calculation from live states to barrier states - `tin`: vector of time bins for dwell time distribution - `Td`: dwell time rate matrix (within non barrier states) - `barrier`: set of barrier states - `Sinit`: initial state - `method`: 1 for directly solving ODE otherwise use eigendecomposition """ function dwelltimeCDF(tin::Vector, Td::AbstractMatrix, barrier, Sinit::Vector, method::Int=1) t = [max(2*tin[1]-tin[2],0); tin] S = time_evolve(t, Td, Sinit, method) return vec(sum(S[:, barrier], dims=1)) end """ dwelltimePDF(tin::Vector, Td::AbstractMatrix, barrier, Sinit::Vector, method::Int=1) return dwell time PDF (probability density function) """ dwelltimePDF(tin::Vector, Td::AbstractMatrix, barrier, Sinit::Vector, method::Int=1) = pdf_from_cdf(dwelltimeCDF(tin, Td, barrier, Sinit, method)) ontimePDF(tin::Vector, TA::AbstractMatrix, offstates, SAinit::Vector, method::Int=1) = dwelltimePDF(tin, TA, offstates, SAinit, method) offtimePDF(tin::Vector, TI::AbstractMatrix, onstates, SIinit::Vector, method::Int=1) = dwelltimePDF(tin, TI, onstates, SIinit, method) function offonPDF(t::Vector, r::Vector, T::AbstractMatrix, TA::AbstractMatrix, TI::AbstractMatrix, nT::Int, elementsT::Vector, onstates::Vector) pss = normalized_nullspace(T) nonzeros = nonzero_rows(TI) offtimePDF(t, TI[nonzeros, nonzeros], nonzero_states(onstates, nonzeros), init_SI(r, onstates, elementsT, pss, nonzeros)), ontimePDF(t, TA, off_states(nT, onstates), init_SA(r, onstates, elementsT, pss)) end """ pdf_from_cdf(S) return PDF (derivative (using finite difference) of CDF) - `S`: dwell time CDF """ function pdf_from_cdf(S) P = diff(S) P / sum(P) end """ init_S(r::Vector,livestates::Vector,elements::Vector,pss) return initial distribution for dwell time distribution given by transition probability of entering live states in steady state (probability of barrier state multiplied by transition rate to live state) - `r`: transition rates - `sojourn`: set of sojourn states (e.g. onstates for ON Time distribution) - `elements`: vector of Elements (transition rate matrix element structures) - `pss`: steady state distribution """ function init_S(r::Vector, sojourn::Vector, elements::Vector, pss) Sinit = zeros(length(pss)) for e in elements if e.b != e.a && (e.a ∈ sojourn && e.b βˆ‰ sojourn) Sinit[e.a] += pss[e.b] * r[e.index] end end Sinit / sum(Sinit) end """ init_SA(r::Vector,onstates::Vector,elements::Vector,pss::Vector) return initial distribution for ON time distribution """ init_SA(r::Vector, onstates::Vector, elements::Vector, pss::Vector) = init_S(r, onstates, elements, pss) """ init_SI(r::Vector,onstates::Vector,elements::Vector,pss,nonzeros) return nonzero states of initial distribution for OFF time distribution """ function init_SI(r::Vector, onstates::Vector, elements::Vector, pss, nonzeros) Sinit = zeros(length(pss)) for e in elements if e.b != e.a && (e.b ∈ onstates && e.a βˆ‰ onstates) Sinit[e.a] += pss[e.b] * r[e.index] end end Sinit = Sinit[nonzeros] Sinit / sum(Sinit) end """ marginalize(p::Vector,nT,nhist) marginalize(p::Vector,nT) marginalize(P::Matrix) Marginalize over G states """ function marginalize(p::Vector, nT, nhist) mhist = zeros(nhist) for m in 1:nhist i = (m - 1) * nT mhist[m] = sum(p[i+1:i+nT]) end return mhist end function marginalize(p::Vector, nT) nhist = div(length(p), nT) marginalize(p, nT, nhist) end marginalize(P::Matrix) = sum(P, dims=1) """ unfold(P::Matrix) reshape matrix into a 1D array """ unfold(P::Matrix) = reshape(P, length(P)) """ time_evolve(t,M::Matrix,Sinit::Vector) Eigenvalue solution of Linear ODE with rate matrix T and initial vector Sinit """ function time_evolve(t, Q::AbstractMatrix, S0::Vector, method) if method == 1 return time_evolve_diff(t, Q, S0) else return time_evolve_eig(t, Q, S0) end end """ time_evolve_diff(t,M::Matrix,P0) Solve master equation problem using DifferentialEquations.jl """ function time_evolve_diff(t, Q::SparseMatrixCSC, P0, method=Tsit5()) tspan = (t[1], t[end]) prob = ODEProblem(fevolve!, P0, tspan, Q) sol = solve(prob, method, saveat=t) return sol' end """ fevolve!(du,u::Vector, p, t) in place update of du of ODE system for DifferentialEquations,jl """ function fevolve!(du, u::Vector, p, t) du .= p * u end """ time_evolve_eig(t, M::AbstractMatrix, Sinit::Vector) Solve master equation problem using eigen decomposition """ function time_evolve_eig(t, M::AbstractMatrix, Sinit::Vector) vals, vects = eig_decompose(M) weights = solve_vector(vects, Sinit) time_evolve_eig(t, vals, vects, weights) end """ time_evolve_eig(t::Float64, vals::Vector, vects::Matrix, weights::Vector) """ function time_evolve_eig(t::Float64, vals::Vector, vects::Matrix, weights::Vector) n = length(vals) S = zeros(n) for j = 1:n for i = 1:n S[j] += real(weights[i] * vects[j, i] * exp.(vals[i] * t)) end end return S end """ time_evolve_eig(t::Vector, vals::Vector, vects::Matrix, weights::Vector) """ function time_evolve_eig(t::Vector, vals::Vector, vects::Matrix, weights::Vector) ntime = length(t) n = length(vals) S = Array{Float64,2}(undef, ntime, n) for j = 1:n Sj = zeros(ntime) for i = 1:n Sj += real(weights[i] * vects[j, i] * exp.(vals[i] * t)) end S[:, j] = Sj end return S end """ normalized_nullspace(M::SparseMatrixCSC) Compute the normalized null space of a nxn matrix of rank n-1 using QR decomposition with pivoting """ function normalized_nullspace(M::SparseMatrixCSC) m = size(M, 1) p = zeros(m) F = qr(M) #QR decomposition R = F.R # Back substitution to solve R*p = 0 p[end] = 1.0 for i in 1:m-1 p[m-i] = -R[m-i, m-i+1:end]' * p[m-i+1:end] / R[m-i, m-i] end # Permute elements according to sparse matrix result pp = copy(p) for i in eachindex(p) pp[F.pcol[i]] = p[i] end pp / sum(pp) end """ allele_convolve(mhist,nalleles) Convolve to compute distribution for contributions from multiple alleles """ function allele_convolve(mhist, nalleles) nhist = length(mhist) mhists = Array{Array{Float64,1}}(undef, nalleles) mhists[1] = float.(mhist) for i = 2:nalleles mhists[i] = zeros(nhist) for m = 0:nhist-1 for m2 = 0:min(nhist - 1, m) mhists[i][m+1] += mhists[i-1][m-m2+1] * mhist[m2+1] end end end return mhists[nalleles] end """ allele_deconvolve(mhist,nalleles) Deconvolve to compute distribution of one allele from contributions of multiple alleles """ allele_deconvolve(mhist, nalleles) = irfft((rfft(mhist)) .^ (1 / nalleles), length(mhist)) """ nhist_loss(nhist,yieldfactor) Compute length of pre-loss histogram """ nhist_loss(nhist, yieldfactor) = round(Int, nhist / yieldfactor) """ technical_loss(mhist,yieldfactor) Reduce counts due to technical loss """ function technical_loss!(mhist::Vector, yieldfactor) for i in eachindex(mhist) mhist[i] = technical_loss(mhist[i], yieldfactor, length(mhist[i])) end end """ technical_loss(mhist,yieldfactor,nhist) Reduce counts due to technical loss using Binomial sampling """ function technical_loss(mhist::Vector, yieldfactor, nhist) p = zeros(nhist) for m in eachindex(mhist) d = Binomial(m - 1, clamp(yieldfactor, 0.0, 1.0)) for c in 1:nhist p[c] += mhist[m] * pdf(d, c - 1) end end normalize_histogram(p) end """ technical_loss_poisson(mhist,yieldfactor,nhist) Reduce counts due to technical loss using Poisson sampling """ function technical_loss_poisson(mhist, yieldfactor, nhist) p = zeros(nhist) for m in eachindex(mhist) d = Poisson(yieldfactor * (m - 1)) for c in 1:nhist p[c] += mhist[m] * pdf(d, c - 1) end end normalize_histogram(p) end """ additive_noise(mhist,noise,nhist) Add Poisson noise to histogram """ function additive_noise(mhist, noise, nhist) p = zeros(nhist) d = Poisson(noise) for m in 1:nhist for n in 1:m p[m] += mhist[n] * pdf(d, m - n) end end normalize_histogram(p) end """ threshold_noise(mhist,noise,yieldfactor,nhist) Add Poisson noise to histogram then reduce counts due to technical loss """ function threshold_noise(mhist, noise, yieldfactor, nhist) h = additive_noise(mhist, noise, nhist) technical_loss(h, yieldfactor, nhist) end """ solve_vector(A::Matrix,b::vector) solve A x = b If matrix divide has error higher than tol use SVD and pseudoinverse with threshold """ function solve_vector(A::Matrix, b::Vector, th=1e-16, tol=1e-1) x = A \ b if norm(b - A * x, Inf) > tol M = svd(A) Sv = M.S Sv[abs.(Sv).<th] .= 0.0 Sv[abs.(Sv).>=th] = 1 ./ Sv[abs.(Sv).>=th] x = M.V * diagm(Sv) * M.U' * b end return x[:, 1] # return as vector end
StochasticGene
https://github.com/nih-niddk-mbs/StochasticGene.jl.git
[ "MIT" ]
1.2.5
fc1bcee6037ea393ce28426929eff65c76a86779
code
23095
# This file is part of StochasticGene.jl ### common.jl # Data types """ AbstractExperimentalData abstract type for experimental data """ abstract type AbstractExperimentalData end """ AbstractSampleData abstract type for data in the form of samples """ abstract type AbstractSampleData <: AbstractExperimentalData end """ AbstractHistogramData abstract type for data in the form of a histogram (probability distribution) """ abstract type AbstractHistogramData <: AbstractExperimentalData end """ AbstractTraceData abstract type for intensity time series data """ abstract type AbstractTraceData <: AbstractExperimentalData end """ AbstractRNAData{hType} abstract type for steady state RNA histogram data """ abstract type AbstractRNAData{hType} <: AbstractHistogramData end """ AbstractTraceHistogramData abstract type for intensity time series data with RNA histogram data """ abstract type AbstractTraceHistogramData <: AbstractExperimentalData end # Data structures # # Do not use underscore "_" in label """ Data structures arguments: label: label for the data set gene: gene name (case sensitive) nRNA: length of histogram histRNA: RNA histograms bins: number of live cell recording time bins OFF: OFF time probability density ON:: ON time probability density """ struct RNAData{nType,hType} <: AbstractRNAData{hType} label::String gene::String nRNA::nType histRNA::hType end struct RNAOnOffData <: AbstractHistogramData label::String gene::String nRNA::Int histRNA::Vector bins::Vector ON::Vector OFF::Vector end struct RNADwellTimeData <: AbstractHistogramData label::String gene::String nRNA::Int histRNA::Array bins::Vector{Vector} DwellTimes::Vector{Vector} DTtypes::Vector end struct TraceData{traceType} <: AbstractTraceData label::String gene::String interval::Float64 trace::traceType end struct TraceNascentData{traceType} <: AbstractTraceData label::String gene::String interval::Float64 trace::traceType nascent::Vector{Int} end struct TraceRNAData{traceType,hType} <: AbstractTraceHistogramData label::String gene::String interval::Float64 trace::traceType nRNA::Int histRNA::hType end # Model structures """ Pool structure for hierarchical model - `nhyper::Int`: number of hyper parameter sets - `nparams::Int`: number of fitted hyper params per set = length(fittedparam) - `nrates`::Int`: number of rates (all params) for each individual - `nindividualparams::Int`: number of fitted params per individual - `nindividuals::Int`: number of individuals (traces) """ struct Pool nhyper::Int nrates::Int nparams::Int nindividuals::Int ratestart::Int paramstart::Int hyperindices::Vector{Vector} end """ HMMReporter structure for reporters - `n`: number of noise parameters - `per_state`: number of reporters per state - `probfn`: noise distribution e.g. prob_GaussianMixture - `weightind`: index for mixture model bias parameter (restricted to range [0,1]) """ struct HMMReporter n::Int per_state::Vector{Int} probfn::Function weightind::Int offstates::Vector{Int} end """ Abstract model types """ abstract type AbstractModel end abstract type AbstractGmodel <: AbstractModel end abstract type AbstractGMmodel <: AbstractGmodel end abstract type AbstractGRSMmodel{RateType,ReporterType} <: AbstractGmodel end """ Model structures fields: - `rates`: transition rates - `Gtransitions`: tuple of vectors of G state transitions - `G`: number of G steps - `R`: number of R steps - `S`: indicator for splicing, 0 no splicing, > 1 splicing - `insertstep`: R step where reporter is inserted (first step where reporter is visible) - `nalleles`: number of alleles producing RNA - `splicetype`: choices are "", "offeject", "offdecay" - `rateprior`: prior distribution for rates - `proposal`: MCMC proposal distribution - `fittedparam`: indices of rates to be fitted - `fixedeffects`: indices of rates that are fixed to each other, in the form of a 2 tuple of vectors with index 1 the tied index vector and 2 the corresponding fitted index vector - `fixedeffects`: tuple of vectors of rates that are locked together - `method`: method option, for nonhierarchical models 1 indicates solving Master equation directly, otherwise by eigendecomposition, for hierarchical models, 2-tuple, where 1st component is same as above and 2nd is Bool where true means rates are fixed for all individuals -` reporter`: vector of reporters or sojorn states (onstates) or vectors of vectors depending on model and data """ struct GMmodel{RateType,PriorType,ProposalType,ParamType,MethodType,ComponentType,ReporterType} <: AbstractGMmodel rates::RateType Gtransitions::Tuple G::Int nalleles::Int rateprior::PriorType proposal::ProposalType fittedparam::ParamType fixedeffects::Tuple method::MethodType components::ComponentType reporter::ReporterType end struct GRSMmodel{RateType,PriorType,ProposalType,ParamType,MethodType,ComponentType,ReporterType} <: AbstractGRSMmodel{RateType,ReporterType} rates::RateType Gtransitions::Tuple G::Int R::Int S::Int insertstep::Int nalleles::Int splicetype::String rateprior::PriorType proposal::ProposalType fittedparam::ParamType fixedeffects::Tuple method::MethodType components::ComponentType reporter::ReporterType end struct GRSMhierarchicalmodel{RateType,PriorType,ProposalType,ParamType,MethodType,ComponentType,ReporterType} <: AbstractGRSMmodel{RateType,ReporterType} rates::RateType pool::Pool Gtransitions::Tuple G::Int R::Int S::Int insertstep::Int nalleles::Int splicetype::String rateprior::PriorType proposal::ProposalType fittedparam::ParamType fixedeffects::Tuple method::MethodType components::ComponentType reporter::ReporterType end """ print_model(model::AbstractModel) print all fields of model """ function print_model(model::AbstractModel) for fname in fieldnames(model) println("$fname =", getfield(model, fname)) end end """ Abstract Option types for fitting methods """ abstract type Options end abstract type Results end # Model and Data dependent functions """ datahistogram(data) Return the RNA histogram data as one vector """ # datahistogram(data::RNAData) = data.histRNA function datahistogram(data::AbstractRNAData{Array{Array,1}}) v = data.histRNA[1] for i in 2:length(data.histRNA) v = vcat(v, data.histRNA[i]) end return v end datahistogram(data::AbstractRNAData{Array{Float64,1}}) = data.histRNA datahistogram(data::RNAOnOffData) = [data.OFF; data.ON; data.histRNA] datahistogram(data::AbstractTraceHistogramData) = data.histRNA function datahistogram(data::RNADwellTimeData) v = data.histRNA for d in data.DwellTimes v = vcat(v, d) end return v end datapdf(data::AbstractRNAData{Array{Float64,1}}) = normalize_histogram(data.histRNA) datapdf(data::RNAOnOffData) = [normalize_histogram(data.OFF); normalize_histogram(data.ON); normalize_histogram(data.histRNA)] datapdf(data::AbstractTraceHistogramData) = normalize_histogram(data.histRNA) function datapdf(data::AbstractRNAData{Array{Array,1}}) v = normalize_histogram(data.histRNA[1]) for i in 2:length(data.histRNA) v = vcat(v, normalize_histogram(data.histRNA[i])) end return v end function datapdf(data::RNADwellTimeData) v = normalize_histogram(data.histRNA) for d in data.DwellTimes v = vcat(v, normalize_histogram(d)) end return v end # Model loglikelihoods """ loglikelihood(param,data::AbstractHistogramData,model) returns negative loglikelihood of all data and vector of the prediction histogram negative loglikelihood Calls likelihoodfn and datahistogram provided for each data and model type """ function loglikelihood(param, data::AbstractHistogramData, model::AbstractGmodel) predictions = likelihoodfn(param, data, model) hist = datahistogram(data) logpredictions = log.(max.(predictions, eps())) return crossentropy(logpredictions, hist), -logpredictions end """ loglikelihood(param,data::AbstractTraceData,model::GMmodel) negative loglikelihood of combined time series traces and each trace """ function loglikelihood(param, data::AbstractTraceData, model::AbstractGmodel) ll_hmm(get_rates(param, model), model.components.nT, model.components.elementsT, model.reporter.n, model.reporter.per_state, model.reporter.probfn, model.reporter.offstates, data.interval, data.trace) end """ loglikelihood(param, data::TraceRNAData{Float64}, model::AbstractGmodel) negative loglikelihood of trace data with nascent RNA FISH active fraction (stored in data.histRNA field) """ function loglikelihood(param, data::TraceNascentData, model::AbstractGmodel) ll_hmm(get_rates(param, model), model.components.nT, model.components.elementsT, model.reporter.n, model.reporter.per_state, model.reporter.probfn, data.interval, data.trace, data.nascent) end """ loglikelihood(param, data::TraceRNAData{Vector{Float64}}, model::AbstractGRSMmodel) negative loglikelihood of time series traces and mRNA FISH steady state histogram """ function loglikelihood(param, data::TraceRNAData, model::AbstractGRSMmodel) r = get_rates(param, model) llg, llgp = ll_hmm(r, model.components.tcomponents.nT, model.components.tcomponents.elementsT, model.reporter.n, model.reporter.per_state, model.reporter.probfn, model.reporter.offstates, data.interval, data.trace) M = make_mat_M(model.components.mcomponents, r[1:num_rates(model)]) logpredictions = log.(max.(steady_state(M, model.components.mcomponents.nT, model.nalleles, data.nRNA), eps())) return crossentropy(logpredictions, datahistogram(data)) + llg, vcat(-logpredictions, llgp) # concatenate logpdf of histogram data with loglikelihood of traces end """ loglikelihood(param, data::AbstractTraceData, model::GRSMhierarchicalmodel) """ function loglikelihood(param, data::AbstractTraceData, model::GRSMhierarchicalmodel) r, p, hyper = prepare_params(param, model) if model.method[2] llg, llgp = ll_hmm_hierarchical_rateshared_background(r, model.components.nT, model.components.elementsT, model.reporter.n, model.reporter.per_state, model.reporter.probfn, model.reporter.offstates, data.interval, data.trace) else llg, llgp = ll_hmm_hierarchical(r, model.components.nT, model.components.elementsT, model.reporter.n, model.reporter.per_state, model.reporter.probfn, data.interval, data.trace) end # d = distribution_array(pm, psig) d = hyper_distribution(hyper) lhp = Float64[] for pc in eachcol(p) lhpc = 0 for i in eachindex(pc) lhpc -= logpdf(d[i], pc[i]) end push!(lhp, lhpc) end return llg + sum(lhp), vcat(llgp, lhp) end """ hyper_distribution(p) for hierarchical model """ function hyper_distribution(p) distribution_array(p[1], sigmalognormal(p[2])) end """ prepare_params(param, model) extract and reassemble parameters for use in likelihood """ function prepare_params(param, model::GRSMhierarchicalmodel) # rates reshaped from a vector into a matrix with columns pertaining to hyperparams and individuals # (shared parameters are considered to be hyper parameters without other hyper parameters (e.g. mean without variance)) h = Vector{Int}[] for i in model.pool.hyperindices push!(h, i) end r = reshape(get_rates(param, model)[model.pool.ratestart:end], model.pool.nrates, model.pool.nindividuals) p = reshape(param[model.pool.paramstart:end], model.pool.nparams, model.pool.nindividuals) return r, p, h end # function prepare_params(param, model::GRSMhierarchicalmodel) # # rates reshaped from a vector into a matrix with columns pertaining to hyperparams and individuals # # (shared parameters are considered to be hyper parameters without other hyper parameters (e.g. mean without variance)) # r = reshape(get_rates(param, model), model.pool.nrates, model.pool.nhyper + model.pool.nindividuals) # param = Vector{Int}[] # for i in model.pool.hyperindices # push!(param[i]) # end # pm = param[1:model.pool.nparams] # if model.pool.nhyper == 2 # psig = sigmalognormal(param[model.pool.nrates+1:model.pool.nrates+model.pool.nparams]) # end # p = reshape(param[model.pool.nhyper*model.pool.nparams+1:end],model.pool.nindividualparams,model.pool.nindividuals) # return r[:, model.pool.nhyper+1:end], p, pm, psig # end # Likelihood functions """ likelihoodfn(param,data::RNAData,model::AbstractGMmodel) likelihood for single RNA histogram """ function likelihoodfn(param, data::RNAData, model::AbstractGMmodel) r = get_rates(param, model) M = make_mat_M(model.components, r) steady_state(M, model.G, model.nalleles, data.nRNA) end function likelihoodfn(param, data::RNAData, model::AbstractGRSMmodel) r = get_rates(param, model) M = make_mat_M(components.mcomponents, r) steady_state(M, components.mcomponents.nT, model.nalleles, data.nRNA) end """ likelihoodfn(param,data::AbstractHistogramArrayData,model::AbstractGmodel) likelihood for multiple histograms """ function likelihoodfn(param, data::AbstractHistogramData, model::AbstractGmodel) h = likelihoodarray(get_rates(param, model), data, model) make_array(h) end """ likelihoodarray(r, data::RNAData{T1,T2}, model::AbstractGMmodel) where {T1<:Array,T2<:Array} likelihood for multiple histograms, returns an array of pdfs """ function likelihoodarray(r, data::RNAData{T1,T2}, model::AbstractGMmodel) where {T1<:Array,T2<:Array} h = Array{Array{Float64,1},1}(undef, length(data.nRNA)) for i in eachindex(data.nRNA) M = make_mat_M(model.components[i], r[(i-1)*2*model.G+1:i*2*model.G]) h[i] = steady_state(M, model.G, model.nalleles, data.nRNA[i]) end trim_hist(h, data.nRNA) end """ likelihoodarray(r, data::RNAOnOffData, model::AbstractGmodel) # if model.splicetype == "offdecay" # # r[end-1] *= survival_fraction(nu, eta, model.R) # end """ function likelihoodarray(r, data::RNAOnOffData, model::AbstractGmodel) components = model.components onstates = model.reporter T = make_mat_T(components.tcomponents, r) TA = make_mat_TA(components.tcomponents, r) TI = make_mat_TI(components.tcomponents, r) M = make_mat_M(components.mcomponents, r) histF = steady_state(M, components.mcomponents.nT, model.nalleles, data.nRNA) modelOFF, modelON = offonPDF(data.bins, r, T, TA, TI, components.tcomponents.nT, components.tcomponents.elementsT, onstates) return [modelOFF, modelON, histF] end """ likelihoodarray(rin,data::RNAOnOffData,model::AbstractGRSMmodel) """ # function likelihoodarray(rin, data::RNAOnOffData, model::AbstractGRSMmodel) # r = copy(rin) # if model.splicetype == "offdecay" # r[end-1] *= survival_fraction(nu, eta, model.R) # end # likelihoodarray(r, data, model) # end """ likelihoodarray(r, data::RNADwellTimeData, model::AbstractGmodel) likelihood of an array of dwell time histograms """ function likelihoodarray(r, data::RNADwellTimeData, model::AbstractGmodel) # likelihoodarray(r,model.G,model.components,data.bins,model.reporter,data.DTtypes,model.nalleles,data.nRNA) G = model.G tcomponents = model.components.tcomponents onstates = model.reporter elementsT = tcomponents.elementsT elementsTG = tcomponents.elementsTG T = make_mat(elementsT, r, tcomponents.nT) pss = normalized_nullspace(T) TG = make_mat(elementsTG, r, G) pssG = normalized_nullspace(TG) hists = Vector[] M = make_mat_M(model.components.mcomponents, r) histF = steady_state(M, model.components.mcomponents.nT, model.nalleles, data.nRNA) push!(hists, histF) for (i, Dtype) in enumerate(data.DTtypes) if Dtype == "OFF" TD = make_mat(tcomponents.elementsTD[i], r, tcomponents.nT) nonzeros = nonzero_rows(TD) h = offtimePDF(data.bins[i], TD[nonzeros, nonzeros], nonzero_states(onstates[i], nonzeros), init_SI(r, onstates[i], elementsT, pss, nonzeros)) elseif Dtype == "ON" TD = make_mat(tcomponents.elementsTD[i], r, tcomponents.nT) h = ontimePDF(data.bins[i], TD, off_states(tcomponents.nT, onstates[i]), init_SA(r, onstates[i], elementsT, pss)) elseif Dtype == "OFFG" TD = make_mat(tcomponents.elementsTD[i], r, G) h = offtimePDF(data.bins[i], TD, onstates[i], init_SI(r, onstates[i], elementsTG, pssG, collect(1:G))) elseif Dtype == "ONG" TD = make_mat(tcomponents.elementsTD[i], r, G) h = ontimePDF(data.bins[i], TD, off_states(G, onstates[i]), init_SA(r, onstates[i], elementsTG, pssG)) end push!(hists, h) end return hists end """ likelihoodarray(r,G,components,bins,onstates,dttype,nalleles,nRNA) """ function likelihoodarray(r, G, components, bins, onstates, dttype, nalleles, nRNA) tcomponents = components.tcomponents mcomponents = components.mcomponents elementsT = tcomponents.elementsT T = make_mat(elementsT, r, tcomponents.nT) pss = normalized_nullspace(T) elementsTG = tcomponents.elementsTG TG = make_mat(elementsTG, r, G) pssG = normalized_nullspace(TG) hists = Vector[] M = make_mat_M(mcomponents, r) histF = steady_state(M, mcomponents.nT, nalleles, nRNA) push!(hists, histF) for (i, Dtype) in enumerate(dttype) if Dtype == "OFF" TD = make_mat(tcomponents.elementsTD[i], r, tcomponents.nT) nonzeros = nonzero_rows(TD) h = offtimePDF(bins[i], TD[nonzeros, nonzeros], nonzero_states(onstates[i], nonzeros), init_SI(r, onstates[i], elementsT, pss, nonzeros)) elseif Dtype == "ON" TD = make_mat(tcomponents.elementsTD[i], r, tcomponents.nT) h = ontimePDF(bins[i], TD, off_states(tcomponents.nT, onstates[i]), init_SA(r, onstates[i], elementsT, pss)) elseif Dtype == "OFFG" TD = make_mat(tcomponents.elementsTD[i], r, G) h = offtimePDF(bins[i], TD, onstates[i], init_SI(r, onstates[i], elementsTG, pssG, collect(1:G))) elseif Dtype == "ONG" TD = make_mat(tcomponents.elementsTD[i], r, G) h = ontimePDF(bins[i], TD, off_states(G, onstates[i]), init_SA(r, onstates[i], elementsTG, pssG)) end push!(hists, h) end return hists end """ transform_array(v::Array, index::Int, f1::Function, f2::Function) apply function f1 to actionrray v at indices up to index and f2 after index """ function transform_array(v::Array, index::Int, f1::Function, f2::Function) vcat(f1(v[1:index-1, :]), f2(v[index:end, :])) end """ transform_array(v::Array, index, mask, f1, f2) apply function f1 to array v at indices up to index and f2 after index accounting for application of mask (which changes indexing) """ function transform_array(v::Array, index::Int, mask::Vector, f1::Function, f2::Function) if index > 0 && index ∈ mask n = findfirst(index .== mask) if typeof(v) <: Vector return vcat(f1(v[1:n-1]), f2(v[n]), f1(v[n+1:end])) else return vcat(f1(v[1:n-1, :]), f2(v[n:n, :]), f2(v[n+1:end, :])) end else return f1(v) end end """ transform_rates(r,model::AbstractGmodel) log transform rates to real domain """ transform_rates(r, model::AbstractGmodel) = log.(r) transform_rates(r, model::AbstractGRSMmodel{Vector{Float64},HMMReporter}) = transform_array(r, model.reporter.weightind, model.fittedparam, logv, logit) """ inverse_transform_rates(x,model::AbstractGmodel) inverse transform MH parameters on real domain back to rate domain """ inverse_transform_rates(p, model::AbstractGmodel) = exp.(p) inverse_transform_rates(p, model::AbstractGRSMmodel{Vector{Float64},HMMReporter}) = transform_array(p, model.reporter.weightind, model.fittedparam, expv, invlogit) """ get_param(model) get fitted parameters from model """ get_param(model::AbstractGmodel) = log.(model.rates[model.fittedparam]) get_param(model::AbstractGRSMmodel) = transform_rates(model.rates[model.fittedparam], model) """ get_rates(param,model) replace fitted rates with new values and return """ function get_rates(param, model::AbstractGmodel, inverse=true) r = copy_r(model) if inverse r[model.fittedparam] = inverse_transform_rates(param, model) else r[model.fittedparam] = param end fixed_rates(r, model.fixedeffects) end function get_rates(param::Vector{Vector}, model::AbstractGmodel, inverse=true) rv = copy_r(model) for r in rv if inverse r[model.fittedparam] = inverse_transform_rates(param, model) else r[model.fittedparam] = param end end fixed_rates(r, model.fixedeffects) end function get_rates(fits, stats, model, ratetype) if ratetype == "ml" return get_rates(fits.parml, model) elseif ratetype == "median" return get_rates(stats.medparam, model, false) elseif ratetype == "mean" return get_rates(stats.meanparam, model, false) else println("ratetype unknown") end end """ fixed_rates(r, fixedeffects) TBW """ function fixed_rates(r, fixedeffects) if ~isempty(fixedeffects) for effect in fixedeffects r[effect[2:end]] .= r[effect[1]] end end return r end """ copy_r(model) copy rates from model structure """ copy_r(model) = copy(model.rates) """ setr(r,model) """ function setr(r, model::AbstractGRSMmodel) n = model.G - 1 nr = model.R eta = get_eta(r, n, nr) r[2*n+1+nr+1:2*n+1+nr+nr] = eta r end """ logprior(param,model::AbstractGMmodel) compute log of the prior """ function logprior(param, model::AbstractGmodel) d = model.rateprior p = 0 for i in eachindex(d) p -= logpdf(d[i], param[i]) end return p end """ num_rates(transitions, R, S, insertstep) compute number of transition rates """ function num_rates(transitions, R, S, insertstep) if R > 0 if insertstep > R throw("insertstep>R") end if S == 0 insertstep = 1 else S = R - insertstep + 1 end return length(transitions) + 1 + R + S + 1 else return length(transitions) + 2 end end num_rates(model::AbstractGRSMmodel) = num_rates(model.Gtransitions, model.R, model.S, model.insertstep) """ num_rates(model::String) compute number of transition rates given model string """ function num_rates(model::String) m = digits(parse(Int, model)) if length(m) == 1 return 2 * m[1] else return 2 * (m[4] - 1) + m[3] + m[2] - m[1] + 2 end end
StochasticGene
https://github.com/nih-niddk-mbs/StochasticGene.jl.git
[ "MIT" ]
1.2.5
fc1bcee6037ea393ce28426929eff65c76a86779
code
32762
# This file is part of StochasticGene.jl # fit.jl # # Fit GRS models (generalized telegraph models) to RNA abundance and live cell imaging data # """ HBEC gene information """ genes_hbec() = ["CANX"; "DNAJC5"; "ERRFI1"; "KPNB1"; "MYH9"; "Rab7a"; "RHOA"; "RPAP3"; "Sec16A"; "SLC2A1"] genelength_hbec() = Dict([("Sec16A", 42960); ("SLC2A1", 33802); ("ERRFI1", 14615); ("RHOA", 52948); ("KPNB1", 33730); ("MYH9", 106741); ("DNAJC5", 40930); ("CANX", 32710); ("Rab7a", 88663); ("RPAP3", 44130); ("RAB7A", 88663); ("SEC16A", 42960)]) MS2end_hbec() = Dict([("Sec16A", 5220); ("SLC2A1", 26001); ("ERRFI1", 5324); ("RHOA", 51109); ("KPNB1", 24000); ("MYH9", 71998); ("DNAJC5", 14857); ("CANX", 4861); ("Rab7a", 83257); ("RPAP3", 38610); ("SEC16A", 5220); ("RAB7A", 83257)]) halflife_hbec() = Dict([("CANX", 50.0), ("DNAJC5", 5.0), ("ERRFI1", 1.35), ("KPNB1", 9.0), ("MYH9", 10.0), ("Rab7a", 50.0), ("RHOA", 50.0), ("RPAP3", 7.5), ("Sec16A", 8.0), ("SLC2A1", 5.0), ("RAB7A", 50.0), ("SEC16A", 8.0)]) """ get_transitions(G, Gfamily) Create transitions tuple """ function get_transitions(G, Gfamily) typeof(G) <: AbstractString && (G = parse(Int, G)) if G == 2 return ([1, 2], [2, 1]) elseif G == 3 if occursin("KP", Gfamily) return ([1, 2], [2, 1], [2, 3], [3, 1]) elseif occursin("cyclic", Gfamily) return ([1, 2], [2, 3], [3, 1]) else return ([1, 2], [2, 1], [2, 3], [3, 2]) end elseif G == 4 if occursin("KP", Gfamily) return ([1, 2], [2, 1], [2, 3], [3, 2], [3, 4], [4, 2]) elseif occursin("cyclic", Gfamily) return ([1, 2], [2, 3], [3, 4], [4, 1]) else return ([1, 2], [2, 1], [2, 3], [3, 2], [3, 4], [4, 3]) end else throw("transition type unknown") end end """ fit(; <keyword arguments> ) Fit steady state or transient GM model to RNA data for a single gene, write the result (through function finalize), and return nothing. #Arguments - `nchains::Int=2`: number of MCMC chains = number of processors called by Julia, default = 2 - `datatype::String=""`: String that desecribes data type, choices are "rna", "rnaonoff", "rnadwelltime", "trace", "tracenascent", "tracerna" - `dttype=String[]`: types are "OFF", "ON", for R states and "OFFG", "ONG" for G states - `datapath=""`: path to data file or folder or array of files or folders - `cell::String=""': cell type for halflives and allele numbers - `datacond=""`: string or vector of strings describing data treatment condition, e.g. "WT", "DMSO" or ["DMSO","AUXIN"] - `traceinfo=(1.0, 1., 240., .65)`: 4-tuple of frame interval of intensity traces, starting frame time in minutes, ending frame time (use -1 for last index), and fraction of active traces - `nascent=(1, 2)`: 2-tuple (number of spots, number of locations) (e.g. number of cells times number of alleles/cell) - `infolder::String=""`: result folder used for initial parameters - `resultfolder::String=test`: folder for results of MCMC run - `label::String=""`: label of output files produced - `inlabel::String=""`: label of files used for initial conditions - `fittedparam::Vector=Int[]`: vector of rate indices to be fit, e.g. [1,2,3,5,6,7] (applies to shared rates for hierarchical models) - `fixedeffects::Tuple=tuple()`: tuple of vectors of rates that are fixed where first index is fit and others are fixed to first, e.g. ([3,8],) means index 8 is fixed to index 3 (only first parameter should be included in fittedparam) (applies to shared rates for hierarchical models) - `transitions::Tuple=([1,2],[2,1])`: tuple of vectors that specify state transitions for G states, e.g. ([1,2],[2,1]) for classic 2 state telegraph model and ([1,2],[2,1],[2,3],[3,1]) for 3 state kinetic proof reading model - `G::Int=2`: number of gene states - `R::Int=0`: number of pre-RNA steps (set to 0 for classic telegraph models) - `S::Int=0`: number of splice sites (set to 0 for classic telegraph models and R - insertstep + 1 for GRS models) - `insertstep::Int=1`: R step where reporter is inserted - `Gfamily=""`: String describing type of G transition model, e.g. "3state", "KP" (kinetic proofreading), "cyclicory" - `root="."`: name of root directory for project, e.g. "scRNA" - `priormean=Float64[]`: mean rates of prior distribution - 'priorcv=10.`: (vector or number) coefficient of variation(s) for the rate prior distributions, default is 10. - `nalleles=2`: number of alleles, value in alleles folder will be used if it exists - `onstates::Vector{Int}=Int[]`: vector of on or sojourn states, e.g. [[2,3],Int[]], use empty vector for R states, do not use Int[] for R=0 models - `decayrate=1.0`: decay rate of mRNA, if set to -1, value in halflives folder will be used if it exists - `splicetype=""`: RNA pathway for GRS models, (e.g. "offeject" = spliced intron is not viable) - `probfn=prob_Gaussian`: probability function for hmm observation probability (i.e. noise distribution) - `noisepriors = []`: priors of observation noise (use empty set if not fitting traces), superceded if priormean is set - `hierarchical=tuple()`: empty tuple for nonhierarchical; for hierarchical model use 3 tuple of hierchical model parameters (pool.nhyper::Int,individual fittedparams::Vector,individual fixedeffects::Tuple) - `ratetype="median"`: which rate to use for initial condition, choices are "ml", "mean", "median", or "last" - `propcv=0.01`: coefficient of variation (mean/std) of proposal distribution, if cv <= 0. then cv from previous run will be used - `maxtime=Float64=60.`: maximum wall time for run, default = 60 min - `samplesteps::Int=1000000`: number of MCMC sampling steps - `warmupsteps=0`: number of MCMC warmup steps to find proposal distribution covariance - `annealsteps=0`: number of annealing steps (during annealing temperature is dropped from tempanneal to temp) - `temp=1.0`: MCMC temperature - `tempanneal=100.`: annealing temperature - `temprna=1.`: reduce rna counts by temprna compared to dwell times - `burst=false`: if true then compute burst frequency - `optimize=false`: use optimizer to compute maximum likelihood value - `writesamples=false`: write out MH samples if true, default is false - `method=1`: optional method variable, for hierarchical models method = tuple(Int,Bool) = (numerical method, true if transition rates are shared) Example: If you are in the folder where data/HCT116_testdata is installed, then you can fit the mock RNA histogram running 4 mcmc chains with bash> julia -p 4 julia> fits, stats, measures, data, model, options = fit(nchains = 4) """ function fit(; nchains::Int=2, datatype::String="rna", dttype=String[], datapath="HCT116_testdata/", gene="MYC", cell::String="HCT116", datacond="MOCK", traceinfo=(1.0, 1, -1, 0.65), nascent=(1, 2), infolder::String="HCT116_test", resultfolder::String="HCT116_test", inlabel::String="", label::String="", fittedparam::Vector=Int[], fixedeffects=tuple(), transitions::Tuple=([1, 2], [2, 1]), G::Int=2, R::Int=0, S::Int=0, insertstep::Int=1, Gfamily="", root=".", priormean=Float64[], nalleles=2, priorcv=10.0, onstates=Int[], decayrate=-1.0, splicetype="", probfn=prob_Gaussian, noisepriors=[], hierarchical=tuple(), ratetype="median", propcv=0.01, maxtime::Float64=60.0, samplesteps::Int=1000000, warmupsteps=0, annealsteps=0, temp=1.0, tempanneal=100.0, temprna=1.0, burst=false, optimize=false, writesamples=false, method=1) label, inlabel = create_label(label, inlabel, datatype, datacond, cell, Gfamily) if typeof(fixedeffects) <: AbstractString fixedeffects, fittedparam = make_fixedfitted(datatype, fixedeffects, transitions, R, S, insertstep, length(noisepriors)) println(transitions) println(fixedeffects) println(fittedparam) end fit(nchains, datatype, dttype, datapath, gene, cell, datacond, traceinfo, nascent, infolder, resultfolder, inlabel, label, fittedparam, fixedeffects, transitions, G, R, S, insertstep, root, maxtime, priormean, priorcv, nalleles, onstates, decayrate, splicetype, probfn, noisepriors, hierarchical, ratetype, propcv, samplesteps, warmupsteps, annealsteps, temp, tempanneal, temprna, burst, optimize, writesamples, method) end """ fit(nchains::Int, datatype::String, dttype::Vector, datapath, gene::String, cell::String, datacond::String, traceinfo, nascent, infolder::String, resultfolder::String, inlabel::String, label::String, fittedparam::Vector, fixedeffects::String, G::String, R::String, S::String, insertstep::String, Gfamily, root=".", maxtime::Float64=60.0, priormean=Float64[], priorcv=10.0, nalleles=2, onstates=Int[], decayrate=-1.0, splicetype="", probfn=prob_Gaussian, noisepriors =[], hierarchical=tuple(), ratetype="median", propcv=0.01, samplesteps::Int=1000000, warmupsteps=0, annealsteps=0, temp=1.0, tempanneal=100.0, temprna=1.0, burst=false, optimize=false, writesamples=false) """ function fit(nchains::Int, datatype::String, dttype::Vector, datapath, gene::String, cell::String, datacond::String, traceinfo, nascent, infolder::String, resultfolder::String, inlabel::String, label::String, fixedeffects::String, G::String, R::String, S::String, insertstep::String, Gfamily, root=".", maxtime::Float64=60.0, priormean=Float64[], priorcv=10.0, nalleles=2, onstates=Int[], decayrate=-1.0, splicetype="", probfn=prob_Gaussian, noisepriors=[], hierarchical=tuple(), ratetype="median", propcv=0.01, samplesteps::Int=1000000, warmupsteps=0, annealsteps=0, temp=1.0, tempanneal=100.0, temprna=1.0, burst=false, optimize=false, writesamples=false, method=1) transitions = get_transitions(G, Gfamily) fixedeffects, fittedparam = make_fixedfitted(datatype, fixedeffects, transitions, parse(Int, R), parse(Int, S), parse(Int, insertstep), length(noisepriors)) println(transitions) println(fixedeffects) println(fittedparam) fit(nchains, datatype, dttype, datapath, gene, cell, datacond, traceinfo, nascent, infolder, resultfolder, inlabel, label, fittedparam, fixedeffects, transitions, parse(Int, G), parse(Int, R), parse(Int, S), parse(Int, insertstep), root, maxtime, priormean, priorcv, nalleles, onstates, decayrate, splicetype, probfn, noisepriors, hierarchical, ratetype, propcv, samplesteps, warmupsteps, annealsteps, temp, tempanneal, temprna, burst, optimize, writesamples, method) end """ fit(nchains::Int, datatype::String, dttype::Vector, datapath, gene::String, cell::String, datacond::String, traceinfo, nascent, infolder::String, resultfolder::String, inlabel::String, label::String, fittedparam::Vector, fixedeffects, transitions::Tuple, G::Int, R::Int, S::Int, insertstep::Int, root=".", maxtime::Float64=60.0, priormean=Float64[], priorcv=10.0, nalleles=2, onstates=Int[], decayrate=-1.0, splicetype="", probfn=prob_Gaussian, noisepriors =[], hierarchical=tuple(), ratetype="median", propcv=0.01, samplesteps::Int=1000000, warmupsteps=0, annealsteps=0, temp=1.0, tempanneal=100.0, temprna=1.0, burst=false, optimize=false, writesamples=false) """ function fit(nchains::Int, datatype::String, dttype::Vector, datapath, gene::String, cell::String, datacond::String, traceinfo, nascent, infolder::String, resultfolder::String, inlabel::String, label::String, fittedparam::Vector, fixedeffects::Tuple, transitions::Tuple, G::Int, R::Int, S::Int, insertstep::Int, root=".", maxtime::Float64=60.0, priormean=Float64[], priorcv=10.0, nalleles=2, onstates=Int[], decayrate=-1.0, splicetype="", probfn=prob_Gaussian, noisepriors=[], hierarchical=tuple(), ratetype="median", propcv=0.01, samplesteps::Int=1000000, warmupsteps=0, annealsteps=0, temp=1.0, tempanneal=100.0, temprna=1.0, burst=false, optimize=false, writesamples=false, method=1) println(now()) gene = check_genename(gene, "[") if S > 0 && S != R - insertstep + 1 S = R - insertstep + 1 println("Setting S to ", S) end printinfo(gene, G, R, S, insertstep, datacond, datapath, infolder, resultfolder, maxtime) resultfolder = folder_path(resultfolder, root, "results", make=true) infolder = folder_path(infolder, root, "results") datapath = folder_path(datapath, root, "data") data = load_data(datatype, dttype, datapath, label, gene, datacond, traceinfo, temprna, nascent) noiseparams = occursin("trace", lowercase(datatype)) ? length(noisepriors) : zero(Int) decayrate < 0 && (decayrate = get_decay(gene, cell, root)) if isempty(priormean) if isempty(hierarchical) priormean = prior_ratemean(transitions, R, S, insertstep, decayrate, noisepriors) else priormean = prior_ratemean(transitions, R, S, insertstep, decayrate, noisepriors, hierarchical[1]) end end isempty(fittedparam) && (fittedparam = default_fitted(datatype, transitions, R, S, insertstep, noiseparams)) r = readrates(infolder, inlabel, gene, G, R, S, insertstep, nalleles, ratetype) if isempty(r) r = isempty(hierarchical) ? priormean : set_rates(priormean, transitions, R, S, insertstep, noisepriors, length(data.trace[1])) println("No rate file") end println(r) model = load_model(data, r, priormean, fittedparam, fixedeffects, transitions, G, R, S, insertstep, nalleles, priorcv, onstates, decayrate, propcv, splicetype, probfn, noisepriors, hierarchical, method) options = MHOptions(samplesteps, warmupsteps, annealsteps, maxtime, temp, tempanneal) fit(nchains, data, model, options, resultfolder, burst, optimize, writesamples) end """ fit(nchains, data, model, options, resultfolder, burst, optimize, writesamples) """ function fit(nchains, data, model, options, resultfolder, burst, optimize, writesamples) print_ll(data, model) fits, stats, measures = run_mh(data, model, options, nchains) optimized = 0 if optimize try optimized = Optim.optimize(x -> lossfn(x, data, model), fits.parml, LBFGS()) catch @warn "Optimizer failed" end end if burst bs = burstsize(fits, model) else bs = 0 end finalize(data, model, fits, stats, measures, options.temp, resultfolder, optimized, bs, writesamples) println(now()) # get_rates(stats.medparam, model, false) return fits, stats, measures, data, model, options end """ load_data(datatype, dttype, datapath, label, gene, datacond, traceinfo, temprna, nascent) return data structure """ function load_data(datatype, dttype, datapath, label, gene, datacond, traceinfo, temprna, nascent) if datatype == "rna" len, h = read_rna(gene, datacond, datapath) return RNAData(label, gene, len, h) elseif datatype == "rnaonoff" len, h = read_rna(gene, datacond, datapath[1]) h = div.(h, temprna) LC = readfile(gene, datacond, datapath[2]) return RNAOnOffData(label, gene, len, h, LC[:, 1], LC[:, 2], LC[:, 3]) elseif datatype == "rnadwelltime" len, h = read_rna(gene, datacond, datapath[1]) h = div.(h, temprna) bins, DT = read_dwelltimes(datapath[2:end]) return RNADwellTimeData(label, gene, len, h, bins, DT, dttype) elseif occursin("trace", datatype) if typeof(datapath) <: String trace = read_tracefiles(datapath, datacond, traceinfo) background = Vector[] else trace = read_tracefiles(datapath[1], datacond, traceinfo) background = read_tracefiles(datapath[2], datacond, traceinfo) end (length(trace) == 0) && throw("No traces") println(length(trace)) println(datapath) println(datacond) println(traceinfo) weight = (1 - traceinfo[4]) / traceinfo[4] * length(trace) nf = traceinfo[3] < 0 ? floor(Int, (720 - traceinfo[2] + traceinfo[1]) / traceinfo[1]) : floor(Int, (traceinfo[3] - traceinfo[2] + traceinfo[1]) / traceinfo[1]) if datatype == "trace" return TraceData(label, gene, traceinfo[1], (trace, background, weight, nf)) elseif datatype == "tracenascent" return TraceNascentData(label, gene, traceinfo[1], (trace, background, weight, nf), nascent) elseif datatype == "tracerna" len, h = read_rna(gene, datacond, datapath[3]) return TraceRNAData(label, gene, traceinfo[1], (trace, background, weight, nf), len, h) end else throw("$datatype not included") end end """ load_model(data, r, rm, fittedparam::Vector, fixedeffects::Tuple, transitions::Tuple, G::Int, R::Int, S::Int, insertstep::Int, nalleles, priorcv, onstates, decayrate, propcv, splicetype, probfn, noisepriors, hierarchical) return model structure """ function load_model(data, r, rm, fittedparam::Vector, fixedeffects::Tuple, transitions::Tuple, G::Int, R::Int, S::Int, insertstep::Int, nalleles, priorcv, onstates, decayrate, propcv, splicetype, probfn, noisepriors, hierarchical, method=1) if S > 0 && S != R - insertstep + 1 S = R - insertstep + 1 println("Setting S to ", S) end noiseparams = length(noisepriors) weightind = occursin("Mixture", "$(probfn)") ? num_rates(transitions, R, S, insertstep) + noiseparams : 0 if typeof(data) <: AbstractRNAData reporter = onstates components = make_components_M(transitions, G, 0, data.nRNA, decayrate, splicetype) elseif typeof(data) <: AbstractTraceData reporter = HMMReporter(noiseparams, num_reporters_per_state(G, R, S, insertstep), probfn, weightind, off_states(G, R, S, insertstep)) components = make_components_T(transitions, G, R, S, insertstep, splicetype) elseif typeof(data) <: AbstractTraceHistogramData reporter = HMMReporter(noiseparams, num_reporters_per_state(G, R, S, insertstep), probfn, weightind, off_states(G, R, S, insertstep)) components = make_components_MT(transitions, G, R, S, insertstep, data.nRNA, decayrate, splicetype) elseif typeof(data) <: AbstractHistogramData if isempty(onstates) onstates = on_states(G, R, S, insertstep) else for i in eachindex(onstates) if isempty(onstates[i]) onstates[i] = on_states(G, R, S, insertstep) end onstates[i] = Int64.(onstates[i]) end end reporter = onstates if typeof(data) == RNADwellTimeData if length(onstates) == length(data.DTtypes) components = make_components_MTD(transitions, G, R, S, insertstep, onstates, data.DTtypes, data.nRNA, decayrate, splicetype) else throw("length of onstates and data.DTtypes not the same") end else components = make_components_MTAI(transitions, G, R, S, insertstep, onstates, data.nRNA, decayrate, splicetype) end end if isempty(hierarchical) checklength(r, transitions, R, S, insertstep, reporter) priord = prior_distribution(rm, transitions, R, S, insertstep, fittedparam, decayrate, priorcv, noisepriors) if propcv < 0 propcv = getcv(gene, G, nalleles, fittedparam, inlabel, infolder, root) end if R == 0 return GMmodel{typeof(r),typeof(priord),typeof(propcv),typeof(fittedparam),typeof(method),typeof(components),typeof(reporter)}(r, transitions, G, nalleles, priord, propcv, fittedparam, fixedeffects, method, components, reporter) else return GRSMmodel{typeof(r),typeof(priord),typeof(propcv),typeof(fittedparam),typeof(method),typeof(components),typeof(reporter)}(r, transitions, G, R, S, insertstep, nalleles, splicetype, priord, propcv, fittedparam, fixedeffects, method, components, reporter) end else ~isa(method, Tuple) && throw("method not a Tuple") load_model(data, r, rm, transitions, G, R, S, insertstep, nalleles, priorcv, decayrate, splicetype, propcv, fittedparam, fixedeffects, method, components, reporter, noisepriors, hierarchical) end end """ load_model(data, r, rm, transitions, G::Int, R, S, insertstep, nalleles, priorcv, decayrate, splicetype, propcv, fittedparam, fixedeffects, method, components, reporter, noisepriors, hierarchical) """ function load_model(data, r, rm, transitions, G::Int, R, S, insertstep, nalleles, priorcv, decayrate, splicetype, propcv, fittedparam, fixedeffects, method, components, reporter, noisepriors, hierarchical) nhyper = hierarchical[1] nrates = num_rates(transitions, R, S, insertstep) + reporter.n nindividuals = length(data.trace[1]) nparams = length(hierarchical[2]) ratestart = nhyper * nrates + 1 paramstart = length(fittedparam) + nhyper * nparams + 1 fittedparam, fittedhyper, fittedpriors = make_fitted(fittedparam, hierarchical[1], hierarchical[2], nrates, nindividuals) fixedeffects = make_fixed(fixedeffects, hierarchical[3], nrates, nindividuals) rprior = rm[1:nhyper*nrates] priord = prior_distribution(rprior, transitions, R, S, insertstep, fittedpriors, decayrate, priorcv, noisepriors) pool = Pool(nhyper, nrates, nparams, nindividuals, ratestart, paramstart, fittedhyper) GRSMhierarchicalmodel{typeof(r),typeof(priord),typeof(propcv),typeof(fittedparam),typeof(method),typeof(components),typeof(reporter)}(r, pool, transitions, G, R, S, insertstep, nalleles, splicetype, priord, propcv, fittedparam, fixedeffects, method, components, reporter) end function checklength(r, transitions, R, S, insertstep, reporter) n = num_rates(transitions, R, S, insertstep) if typeof(reporter) <: HMMReporter (length(r) != n + reporter.n) && throw("r has wrong length") else (length(r) != n) && throw("r has wrong length") end nothing end """ default_fitted(datatype, transitions, R, S, insertstep, noiseparams) create vector of fittedparams that includes all rates except the decay time """ function default_fitted(datatype::String, transitions, R, S, insertstep, noiseparams) n = num_rates(transitions, R, S, insertstep) fittedparam = collect(1:n-1) if occursin("trace", datatype) fittedparam = vcat(fittedparam, collect(n+1:n+noiseparams)) end fittedparam end """ make_fixedfitted(fixedeffects::String,transitions,R,S,insertstep) make default fixedeffects tuple and fittedparams vector from fixedeffects String """ function make_fixedfitted(datatype::String, fixedeffects::String, transitions, R, S, insertstep, noiseparams) fittedparam = default_fitted(datatype, transitions, R, S, insertstep, noiseparams) fixed = split(fixedeffects, "-") if length(fixed) > 1 fixed = parse.(Int, fixed) deleteat!(fittedparam, fixed[2:end]) fixed = tuple(fixed) else fixed = tuple() end return fixed, fittedparam end """ make_fitted(fittedparams,N) make fittedparams vector for hierarchical model """ function make_fitted(fittedshared, nhyper, fittedindividual, nrates, nindividuals) f = [fittedshared; fittedindividual] # shared parameters come first followed by hyper parameters and individual parameters fhyper = [fittedindividual] for i in 1:nhyper-1 append!(f, fittedindividual .+ i * nrates) push!(fhyper, fittedindividual .+ i * nrates) end fpriors = copy(f) for i in 1:nindividuals append!(f, fittedindividual .+ (i + nhyper - 1) * nrates) end f, fhyper, fpriors end """ make_fixed(fixedpool, fixedindividual, nrates, nindividuals) make fixed effects tuple for hierarchical model """ function make_fixed(fixedshared, fixedindividual, nrates, nindividuals) fixed = Vector{Int}[] for f in fixedshared push!(fixed, f) end for h in fixedindividual push!(fixed, [h + i * nrates for i in 0:nindividuals-1]) end tuple(fixed...) end """ prior_ratemean(transitions::Tuple, R::Int, S::Int, insertstep, decayrate, noisepriors) default priors for rates (includes all parameters, fitted or not) """ function prior_ratemean(transitions::Tuple, R::Int, S::Int, insertstep, decayrate, noisepriors) if S > 0 S = R - insertstep + 1 end ntransitions = length(transitions) nrates = num_rates(transitions, R, S, insertstep) rm = fill(.1*max(R,1), nrates) rm[collect(1:ntransitions)] .= 0.01 rm[nrates] = decayrate [rm; noisepriors] end """ prior_ratemean(transitions::Tuple, R::Int, S::Int, insertstep, decayrate, noisepriors, nindividuals, nhyper, cv=1.0) default priors for hierarchical models, arranged into a single vector, shared and hyper parameters come first followed by individual parameters """ function prior_ratemean(transitions::Tuple, R::Int, S::Int, insertstep, decayrate, noisepriors, nhyper, cv=1.0) rm = prior_ratemean(transitions::Tuple, R::Int, S::Int, insertstep, decayrate, noisepriors) r = copy(rm) for i in 2:nhyper append!(r, cv .* rm) end # for i in 1:nindividuals # append!(r, rm) # end r end function set_rates(rm, transitions::Tuple, R::Int, S::Int, insertstep, noisepriors, nindividuals) r = copy(rm) nrates = num_rates(transitions, R, S, insertstep) + length(noisepriors) for i in 1:nindividuals append!(r, rm[1:nrates]) end r end """ prior_distribution(rm, transitions, R::Int, S::Int, insertstep, fittedparam::Vector, decayrate, priorcv, noiseparams, weightind) """ function prior_distribution(rm, transitions, R::Int, S::Int, insertstep, fittedparam::Vector, decayrate, priorcv, noisepriors, factor=10) if isempty(rm) throw("No prior mean") # rm = prior_ratemean(transitions, R, S, insertstep, decayrate, noisepriors) end if priorcv isa Number n = num_rates(transitions, R, S, insertstep) rcv = fill(priorcv, length(rm)) rcv[n] = 0.1 rcv[n+1:n+length(noisepriors)] /= factor else rcv = priorcv end if length(rcv) == length(rm) return distribution_array(log.(rm[fittedparam]), sigmalognormal(rcv[fittedparam]), Normal) else throw("priorcv not the same length as prior mean") end end """ lossfn(x,data,model) Compute loss function """ lossfn(x, data, model) = loglikelihood(x, data, model)[1] """ burstsize(fits,model::AbstractGMmodel) Compute burstsize and stats using MCMC chain """ function burstsize(fits, model::AbstractGMmodel) if model.G > 1 b = Float64[] for p in eachcol(fits.param) r = get_rates(p, model) push!(b, r[2*model.G-1] / r[2*model.G-2]) end return BurstMeasures(mean(b), std(b), median(b), mad(b), quantile(b, [0.025; 0.5; 0.975])) else return 0 end end function burstsize(fits::Fit, model::GRSMmodel) if model.G > 1 b = Float64[] L = size(fits.param, 2) rho = 100 / L println(rho) for p in eachcol(fits.param) r = get_rates(p, model) if rand() < rho push!(b, burstsize(r, model)) end end return BurstMeasures(mean(b), std(b), median(b), mad(b), quantile(b, [0.025; 0.5; 0.975])) else return 0 end end burstsize(r, model::AbstractGRSMmodel) = burstsize(r, model.R, length(model.Gtransitions)) function burstsize(r, R, ntransitions) total = min(Int(div(r[ntransitions+1], r[ntransitions])) * 2, 400) M = make_mat_M(make_components_M([(2, 1)], 2, R, total, r[end], ""), r) # M = make_components_M(transitions, G, R, nhist, decay, splicetype) nT = 2 * 2^R L = nT * total S0 = zeros(L) S0[2] = 1.0 s = time_evolve_diff([1, 10 / minimum(r[ntransitions:ntransitions+R+1])], M, S0) mean_histogram(s[2, collect(1:nT:L)]) end """ check_genename(gene,p1) Check genename for p1 if p1 = "[" change to "(" (since swarm cannot parse "(") """ function check_genename(gene, p1) if occursin(p1, gene) if p1 == "[" gene = replace(gene, "[" => "(") gene = replace(gene, "]" => ")") elseif p1 == "(" gene = replace(gene, "(" => "]") gene = replace(gene, ")" => "]") end end return gene end """ print_ll(param, data, model, message) compute and print initial loglikelihood """ function print_ll(param, data, model, message) ll, _ = loglikelihood(param, data, model) println(message, ll) end function print_ll(data, model, message="initial ll: ") ll, _ = loglikelihood(get_param(model), data, model) println(message, ll) end """ printinfo(gene,G,datacond,datapath,infolder,resultfolder,maxtime) print out run information """ function printinfo(gene, G, datacond, datapath, infolder, resultfolder, maxtime) println("Gene: ", gene, " G: ", G, " Treatment: ", datacond) println("data: ", datapath) println("in: ", infolder, " out: ", resultfolder) println("maxtime: ", maxtime) end function printinfo(gene, G, R, S, insertstep, datacond, datapath, infolder, resultfolder, maxtime) if R == 0 printinfo(gene, G, datacond, datapath, infolder, resultfolder, maxtime) else println("Gene: ", gene, " G R S insertstep: ", G, R, S, insertstep) println("in: ", infolder, " out: ", resultfolder) println("maxtime: ", maxtime) end end """ finalize(data,model,fits,stats,measures,temp,resultfolder,optimized,burst,writesamples,root) write out run results and print out final loglikelihood and deviance """ function finalize(data, model, fits, stats, measures, temp, writefolder, optimized, burst, writesamples) println("final max ll: ", fits.llml) print_ll(transform_rates(vec(stats.medparam), model), data, model, "median ll: ") println("Median fitted rates: ", stats.medparam[:, 1]) println("ML rates: ", inverse_transform_rates(fits.parml, model)) println("Acceptance: ", fits.accept, "/", fits.total) if typeof(data) <: AbstractHistogramData println("Deviance: ", deviance(fits, data, model)) end println("rhat: ", maximum(measures.rhat)) if optimized != 0 println("Optimized ML: ", Optim.minimum(optimized)) println("Optimized rates: ", exp.(Optim.minimizer(optimized))) end writeall(writefolder, fits, stats, measures, data, temp, model, optimized=optimized, burst=burst, writesamples=writesamples) end function getcv(gene, G, nalleles, fittedparam, inlabel, infolder, root, verbose=true) paramfile = path_Gmodel("param-stats", gene, G, nalleles, inlabel, infolder, root) if isfile(paramfile) cv = read_covlogparam(paramfile) cv = float.(cv) if ~isposdef(cv) || size(cv)[1] != length(fittedparam) cv = 0.02 end else cv = 0.02 end if verbose println("cv: ", cv) end return cv end """ get_decay(gene::String,cell::String,root::String,col::Int=2) get_decay(gene::String,path::String,col::Int) Get decay rate for gene and cell """ function get_decay(gene::String, cell::String, root::String, col::Int=2) if uppercase(cell) == "HBEC" if uppercase(gene) ∈ uppercase.(genes_hbec()) # return log(2.0) / (60 .* halflife_hbec()[gene]) return get_decay(halflife_hbec()[gene]) else println(gene, " has no decay time") return 1.0 end else path = get_file(root, "data/halflives", cell, "csv") if isnothing(path) println(gene, " has no decay time") return -1.0 else return get_decay(gene, path, col) end end end function get_decay(gene::String, path::String, col::Int) a = nothing in = readdlm(path, ',') ind = findfirst(in[:, 1] .== gene) if ~isnothing(ind) a = in[ind, col] end get_decay(a, gene) end function get_decay(a, gene::String) if typeof(a) <: Number return get_decay(float(a)) else println(gene, " has no decay time") return 1.0 end end get_decay(a::Float64) = log(2) / a / 60.0 """ alleles(gene::String,cell::String,root::String,col::Int=3) alleles(gene::String,path::String,col::Int=3) Get allele number for gene and cell """ function alleles(gene::String, cell::String, root::String; nalleles::Int=2, col::Int=3) path = get_file(root, "data/alleles", cell, "csv") if isnothing(path) return 2 else alleles(gene, path, nalleles=nalleles, col=col) end end function alleles(gene::String, path::String; nalleles::Int=2, col::Int=3) a = nothing in, h = readdlm(path, ',', header=true) ind = findfirst(in[:, 1] .== gene) if isnothing(ind) return nalleles else a = in[ind, col] return isnothing(a) ? nalleles : Int(a) end end
StochasticGene
https://github.com/nih-niddk-mbs/StochasticGene.jl.git
[ "MIT" ]
1.2.5
fc1bcee6037ea393ce28426929eff65c76a86779
code
13745
# This file is part of StochasticGene.jl # #genetrap.jl #Fit GRSM models to live cell and smFISH data """ HBEC gene information """ genes_gt() = ["CANX"; "DNAJC5"; "ERRFI1"; "KPNB1"; "MYH9"; "Rab7a"; "RHOA"; "RPAP3"; "Sec16A"; "SLC2A1"] genelength_gt() = Dict([("Sec16A", 42960); ("SLC2A1", 33802); ("ERRFI1", 14615); ("RHOA", 52948); ("KPNB1", 33730); ("MYH9", 106741); ("DNAJC5", 40930); ("CANX", 32710); ("Rab7a", 88663); ("RPAP3", 44130); ("RAB7A", 88663); ("SEC16A", 42960)]) MS2end_gt() = Dict([("Sec16A", 5220); ("SLC2A1", 26001); ("ERRFI1", 5324); ("RHOA", 51109); ("KPNB1", 24000); ("MYH9", 71998); ("DNAJC5", 14857); ("CANX", 4861); ("Rab7a", 83257); ("RPAP3", 38610);("SEC16A", 5220); ("RAB7A", 83257)]) halflife_gt() = Dict([("CANX", 50.0), ("DNAJC5", 5.0), ("ERRFI1", 1.35), ("KPNB1", 9.0), ("MYH9", 10.0), ("Rab7a", 50.0), ("RHOA", 50.0), ("RPAP3", 7.5), ("Sec16A", 8.0), ("SLC2A1", 5.0), ("RAB7A", 50.0), ("SEC16A", 8.0)]) function insert_site_gt(R) for g in genes_gt() println(g, ": ", ceil(MS2end_gt()[g] / genelength_gt()[g] * R)) end end """ fit_genetrap() """ function fit_genetrap(nchains, maxtime, gene::String, transitions, G::Int, R::Int, S::Int, insertstep::Int; onstates=[], priorcv=10.0, propcv=0.01, fittedparam=collect(1:num_rates(transitions, R, R, insertstep)-1), infolder::String="test", folder::String="test", samplesteps::Int=1000, nalleles::Int=2, label="gt", splicetype="", warmupsteps=0, annealsteps=0, temp=1.0, tempanneal=100.0, temprna=1.0, root::String=".", burst=false) println(now()) folder = folder_path(folder, root, "results", make=true) infolder = folder_path(infolder, root, "results") data, model = genetrap(root, gene, transitions, G, R, S, insertstep, 2, splicetype, fittedparam, infolder, folder, label, "ml", temprna, priorcv, propcv, onstates) println("size of histogram: ", data.nRNA) options = MHOptions(samplesteps, warmupsteps, annealsteps, maxtime, temp, tempanneal) println(model.rates) print_ll(data, model) fits, stats, measures = run_mh(data, model, options, nchains) if burst bs = burstsize(fit, model) else bs = 0 end # finalize(data,model,fits,stats,measures,1.,folder,0,bs,root) finalize(data, model, fits, stats, measures, temp, folder, 0, burst, false, root) println(now()) return data, model_genetrap(gene, get_rates(fits.parml, model), transitions, G, R, S, insertstep, fittedparam, nalleles, data.nRNA + 2, priorcv, propcv, onstates, splicetype), fits, stats, measures end """ genetrap() Load data, model and option structures for metropolis-hastings fit root is the folder containing data and results FISH counts is divided by temprna to adjust relative weights of data set temprna = 0 to equalize FISH and live cell counts, """ function genetrap(root, gene::String, transitions::Tuple, G::Int, R::Int, S::Int, insertstep::Int, nalleles, splicetype::String, fittedparam::Vector, infolder::String, label::String, ratetype::String, temprna, priorcv, propcv, onstates, tracedata) r = readrates_genetrap(infolder, ratetype, gene, label, G, R, S, insertstep, nalleles, splicetype) genetrap(root, r, label, gene, transitions, G, R, S, insertstep, nalleles, splicetype, fittedparam, temprna, priorcv, propcv, onstates, tracedata) end function genetrap(root, r, label::String, gene::String, transitions::Tuple, G::Int, R::Int, S::Int, insertstep::Int, nalleles::Int=2, splicetype::String="", fittedparam=collect(1:num_rates(transitions, R, S, insertstep)-1), temprna=1.0, priorcv=10.0, propcv=0.01, onstates=[], tracedata="") data = R == 0 ? data_genetrap_FISH(root, label, gene) : data_genetrap(root, label, gene, temprna, tracedata) model = model_genetrap(gene, r, transitions, G, R, S, insertstep, fittedparam, nalleles, data.nRNA + 2, priorcv, propcv, onstates, splicetype) return data, model end function data_genetrap(root, label, gene, temprna, tracefolder) if ~isempty(tracefolder) traces = read_tracefiles(tracefolder,"",',') histFISH = readFISH_genetrap(root, gene, temprna) return TraceRNAData("traceRNA", "test", interval, traces, length(histFISH),histFISH) else LC = readLCPDF_genetrap(root, gene) if temprna == 0 counts = Int(div(sum(LC[:, 2] + LC[:, 3]), 2)) println(counts) # set FISH counts to mean of live cell counts histFISH = readFISH_genetrap(root, gene, counts) else histFISH = readFISH_genetrap(root, gene, temprna) end return RNAOnOffData(label, gene, length(histFISH), histFISH, LC[:, 1], LC[:, 3], LC[:, 2]) end end function data_genetrap_FISH(root, label, gene) histFISH = readFISH_genetrap(root, gene, 1.0) RNAData(label, gene, length(histFISH), histFISH) end """ model_genetrap load model structure """ function model_genetrap(gene::String, r, transitions, G::Int, R::Int, S::Int, insertstep::Int, fittedparam::Vector, nalleles::Int, nhist::Int, priorcv=10.0, propcv=0.01, onstates=Int[], splicetype="", method=1) if S > 0 S = R end if isempty(onstates) onstates = on_states(G, R, S, insertstep) end nrates = num_rates(transitions, R, S, insertstep) rm = fill(0.1, nrates) rcv = [fill(priorcv, length(rm) - 1); 0.1] if gene ∈ genes_gt() rm[nrates] = log(2.0) / (60 .* halflife_gt()[gene]) end if r == 0.0 r = rm end println(r) d = distribution_array(log.(rm[fittedparam]), sigmalognormal(rcv[fittedparam]), Normal) components = make_components_MTAI(transitions, G, R, S, insertstep, on_states(G, R, S, insertstep), nhist, r[num_rates(transitions, R, S, insertstep)]) return GRSMmodel{typeof(r),typeof(d),typeof(propcv),typeof(fittedparam),typeof(method),typeof(components),typeof(onstates)}(G, R, S, insertstep, nalleles, splicetype, r, d, propcv, fittedparam, method, transitions, components, onstates) end # """ # setpriorrate(G,R,gene,Gprior::Tuple,Sprior::Tuple,Rcv::Float64) # Set prior distribution for mean and cv of rates # """ # function prior_rates_genetrap(G, R, gene, Gprior::Tuple, Sprior::Tuple, Rcv::Float64) # n = G - 1 # rm = [fill(Gprior[1], 2 * n); .1; fill(.1, R); fill(Sprior[1], R); log(2.0) / (60 .* halflife_gt()[gene])] # rcv = [fill(Gprior[2], 2 * n); Rcv; Rcv; fill(Sprior[2], 2 * R); 0.01] # return rm, rcv # end function flip_dwelltimes(folder) for (root, dirs, files) in walkdir(folder) for file in files target = joinpath(root, file) c = readdlm(target,',') writedlm(target,[c[:,1] c[:,3] c[:,2]],',') end end end """ readrates_genetrap(infolder::String,ratetype::String,gene::String,label,G,R,nalleles,splicetype::String) Read in initial rates from previous runs """ function readrates_genetrap(infolder::String, ratetype::String, gene::String, label, G, R, S, insertstep, nalleles, splicetype::String) row = get_row()[ratetype] readrates_genetrap(getratefile_genetrap(infolder, ratetype, gene, label, G, R, S, insertstep, nalleles, splicetype), row) end function readrates_genetrap(infile::String, row::Int) if isfile(infile) && ~isempty(read(infile)) println(infile, ", row: ", get_ratetype()[row]) return readrates(infile, row, true) else println("using default rates") return 0 end end """ getratefile_genetrap(infolder::String, ratetype::String, gene::String, label, G, R, S, insertstep, nalleles, splicetype::String) TBW """ function getratefile_genetrap(infolder::String, ratetype::String, gene::String, label, G, R, S, insertstep, nalleles, splicetype::String) model = R == 0 ? "$G" : "$G$R$S$insertstep" file = "rates" * "_" * label * "_" * gene * "_" * model * "_" * "$(nalleles)" * "$splicetype" * ".txt" joinpath(infolder, file) end """ readLCPDF_genetrap(root,gene) Read in dwell time PDF """ function readLCPDF_genetrap(root, gene) infile = joinpath(root, "DwellTimePDF/$(gene)_PDF.csv") if isfile(infile) LC = readdlm(infile, ',') x = truncate_histogram(LC[:, 2], 0.999, 1000) LC[1:length(x), :] else println("No data for gene: ", gene) end end """ readFISH_genetrap(root,gene,temp=1.,clone=true) Read and assemble smFISH data """ function readFISH_genetrap(root::String, gene::String, temp::Float64=1.0, clone=true) counts = countsFISH_genetrap(root, gene, clone) readFISH_genetrap(root, gene, Int(div(counts, temp)), clone) end function readFISH_genetrap(root::String, gene::String, counts::Int, clone=true) fishfile = joinpath(root, "Fish_4_Genes/$(gene)_steady_state_mRNA.csv") col = clone ? 3 : 2 # Get smFISH RNA histograms if isfile(fishfile) x = readdlm(fishfile, ',')[3:end, col] x = x[x.!=""] x = truncate_histogram(x, 0.99, 1000) x /= sum(x) x *= counts return x else println("No smFISH data for gene: ", gene) end nothing end function make_FISH_histograms(root::String, temp::Float64=1.0, clone=true) path = joinpath(root,"data/FISH") if ~ispath(path) mkpath(path) end for gene in genes_gt() h = readFISH_genetrap(root, gene, temp, clone) file = joinpath(path,"$(gene)_gt.txt") writedlm(file,h) end end """ countsFISH_genetrap(root,gene,x,counts,clone=true) read in smFISH counts """ function countsFISH_genetrap(root, gene, clone=true) countfile = joinpath(root, "counts/total_counts.csv") wttext = "WT_" clonetext = "_clone" if isfile(countfile) countsdata = readdlm(countfile, ',')[:, :] if clone counts = (countsdata[findall(uppercase("$(gene)$clonetext") .== uppercase.(countsdata[:, 1])), 2])[1] else counts = (countsdata[findall("$wttext$(gene)" .== countsdata[:, 1]), 2])[1] end else counts = 1000 end return counts end """ survival_fraction(nu,eta,nr) Fraction of introns that are not spliced prior to ejection """ function survival_fraction(nu, eta, nr) pd = 1.0 for i = 1:nr pd *= nu[i+1] / (nu[i+1] + eta[i]) end return pd end # """ # get_gamma(r,n,nr) # G state forward and backward transition rates # for use in transition rate matrices of Master equation # (different from gamma used in Gillespie algorithms) # """ # function get_gamma(r, n) # gammaf = zeros(n + 2) # gammab = zeros(n + 2) # for i = 1:n # gammaf[i+1] = r[2*(i-1)+1] # gammab[i+1] = r[2*i] # end # return gammaf, gammab # end # """ # get_nu(r,n,nr) # R step forward transition rates # """ # function get_nu(r, n, nr) # r[2*n+1:2*n+nr+1] # end # """ # get_eta(r,n,nr) # Intron ejection rates at each R step # """ # function get_eta(r, n, nr) # eta = zeros(nr) # if length(r) > 2 * n + 2 * nr # eta[1] = r[2*n+1+nr+1] # for i = 2:nr # # eta[i] = eta[i-1] + r[2*n + 1 + nr + i] # eta[i] = r[2*n+1+nr+i] # end # end # return eta # end # """ # Parameter information for GR models # """ # function num_rates(transitions::Tuple, R) # length(transitions) + 2 * R + 2 # end # function num_rates(G::Int, R) # 2 * G + 2 * R # end # function Grange(G::Int) # n = G - 1 # 1:2*n # end # function initiation(G::Int) # n = G - 1 # 2 * n + 1 # end # function Rrange(G::Int, R) # n = G - 1 # 2*n+2:2*n+R+1 # end # function Srange(G::Int, R) # n = G - 1 # 2*n+R+2:2*n+2*R+1 # end # """ # priordistributionLogNormal_genetrap(r,cv,G,R) # LogNormal Prior distribution # """ # function priordistributionLogNormal_genetrap(r, cv, G, R) # sigma = sigmalognormal(cv) # d = [] # j = 1 # # G rates # for i in Grange(G) # push!(d, Distributions.LogNormal(log(r[i]), sigma[j])) # j += 1 # end # # initiation rate # i = initiation(G) # push!(d, Distributions.LogNormal(log(r[i]), sigma[j])) # j += 1 # # Step rates are bounded by length of insertion site to end of gene, i.e sum of reciprocal rates is bounded # t = sum(1 ./ r[Rrange(G, R)]) # push!(d, Distributions.LogNormal(-log(t), sigma[j])) # j += 1 # # priors for splice rates # rs = 0.0 # for i in Srange(G, R) # rs = r[i] # push!(d, Distributions.LogNormal(log(rs), sigma[j])) # j += 1 # end # return d # end # """ # priordistributionGamma_genetrap(r,cv,G,R) # Gamma Prior distribution # """ # function priordistributionGamma_genetrap(rm, cv, G, R) # n = G - 1 # zet = R # d = [] # rsig = cv .^ 2 # j = 1 # # priors for G rates # for i in Grange(G) # theta = rsig[j] * rm[i] # alpha = 1 / rsig[j] # push!(d, Distributions.Gamma(alpha, theta)) # j += 1 # end # # prior for nu1 is upper bounded by rm, i.e. distance is bounded by distance to insertion site # theta = rsig[j] * rm[initiation(G)] # alpha = 1 / rsig[j] # push!(d, Distributions.Gamma(alpha, theta)) # j += 1 # # priors for nu rates are bounded by length of insertion site to end of gene, i.e sum of reciprocal rates is bounded # tm = sum(1 ./ rm[Rrange(G, R)]) # # for i in 2*n + 2 : 2*n + zet + 1 # # tm += 1/rm[i] # # end # theta = rsig[j] / tm # alpha = 1 / rsig[j] # push!(d, Distributions.Gamma(alpha, theta)) # j += 1 # # priors for ejection rates # rs = 0 # for i in Srange(G, R) # rs = rm[i] # theta = rsig[j] * rs # alpha = 1 / rsig[j] # push!(d, Distributions.Gamma(alpha, theta)) # j += 1 # end # return d # end
StochasticGene
https://github.com/nih-niddk-mbs/StochasticGene.jl.git
[ "MIT" ]
1.2.5
fc1bcee6037ea393ce28426929eff65c76a86779
code
17750
# This file is part of StochasticGene.jl ### hmm.jl ### Fit discrete HMMs and continuous hidden Markov process models directly to intensity traces ### ### Notation in discrete HMM algorithms follows Rabier, 1989 ### ### Functions for forward, backward, and Viterbi HMM algorihms ### For continuous processes, numerically solve forward Kolmogorov equation to obtain transition probability matrix ### """ ll_hmm(r, nT, reporters, elementsT, interval, trace) return total loglikelihood of traces with reporter noise and loglikelihood of each trace """ function ll_hmm(r, nT, elementsT::Vector, noiseparams, reporters_per_state, probfn, offstates, interval, trace) a, p0 = make_ap(r, interval, elementsT, nT) lb = trace[3] > 0. ? ll_background(a, p0, offstates, trace[3], trace[4]) : 0. ll, lp = ll_hmm(r, nT, noiseparams::Int, reporters_per_state, probfn, trace[1], log.(max.(a, 0)), log.(max.(p0, 0))) return ll + lb, lp end function ll_hmm(r, nT, noiseparams::Int, reporters_per_state, probfn, traces, loga, logp0) logpredictions = Array{Float64}(undef, 0) for t in traces T = length(t) logb = set_logb(t, nT, r[end-noiseparams+1:end], reporters_per_state, probfn) l = forward_log(loga, logb, logp0, nT, T) push!(logpredictions, logsumexp(l[:, T])) end # for t in trace[2] # T = length(t) # logb = set_logb(t, nT, r[end-noiseparams+1:end], reporters_per_state, probfn) # l = forward_log(loga, logb, logp0, nT, T) # push!(logpredictions, trace[3] / length(trace[2]) * logsumexp(l[:, T])) # end -sum(logpredictions), -logpredictions end function ll_hmm_nascent(r, nT, elementsT::Vector, noiseparams, reporters_per_state, probfn, interval, trace, nascent) a, p0 = make_ap(r, interval, elementsT, nT) lln = ll_nascent(p0, reporters_per_state, nascent) ll, logpredictions = ll_hmm(r, nT, noiseparams, reporters_per_state, probfn, trace, log.(max.(a, 0)), log.(max.(p0, 0))) push!(logpredictions, lln) ll += lln ll, logpredictions end function ll_nascent(p0, reporters_per_state, nascent) pn = sum(p0[reporters_per_state.>0]) d = Binomial(nascent[2], pn) -logpdf(d, nascent[1]) end function ll_background(a, p0, offstates, weight, n) l = -log(sum(p0[offstates]' * a[offstates, offstates]^n)) weight * l end """ ll_hmm_hierarchical(r::Matrix, nT, elementsT::Vector, noiseparams, reporters_per_state, probfn, interval, trace) TBW """ function ll_hmm_hierarchical(r::Matrix, nT, elementsT::Vector, noiseparams, reporters_per_state, probfn, interval, trace) logpredictions = Array{Float64}(undef, 0) for (i, t) in enumerate(trace[1]) T = length(t) loga, logp0 = make_logap(r[:, i], interval, elementsT, nT) logb = set_logb(t, nT, r[end-noiseparams+1:end, i], reporters_per_state, probfn) l = forward_log(loga, logb, logp0, nT, T) push!(logpredictions, logsumexp(l[:, T])) end -sum(logpredictions), -logpredictions end function ll_hmm_hierarchical_rateshared(r::Matrix, nT, elementsT::Vector, noiseparams, reporters_per_state, probfn, interval, trace) logpredictions = Array{Float64}(undef, 0) loga, logp0 = make_logap(r[:, 1], interval, elementsT, nT) for (i, t) in enumerate(trace[1]) T = length(t) logb = set_logb(t, nT, r[end-noiseparams+1:end, i], reporters_per_state, probfn) l = forward_log(loga, logb, logp0, nT, T) push!(logpredictions, logsumexp(l[:, T])) end -sum(logpredictions), -logpredictions end function ll_hmm_hierarchical_rateshared_background(r::Matrix, nT, elementsT::Vector, noiseparams, reporters_per_state, probfn, offstates, interval, trace) logpredictions = Array{Float64}(undef, 0) # loga, logp0 = make_logap(r[:, 1], interval, elementsT, nT) a, p0 = make_ap(r[:,1], interval, elementsT, nT) lb = trace[3] > 0 ? ll_background(a, p0, offstates, trace[3], trace[4]) : 0. # lb = ll_background(r[end-noiseparams+1:end, i], a, p0, offstates, trace[3], trace[4]) loga = log.(max.(a, 0)) logp0 = log.(max.(p0, 0)) for (i, t) in enumerate(trace[1]) T = length(t) logb = set_logb(t, nT, r[end-noiseparams+1:end, i], reporters_per_state, probfn) l = forward_log(loga, logb, logp0, nT, T) push!(logpredictions, logsumexp(l[:, T])) end -sum(logpredictions) + lb, -logpredictions end """ make_ap(r, interval, elementsT, nT ) Return computed discrete HMM transition probability matrix a and equilibrium state probability p0 a is computed by numerically integrating Kolmogorov Forward equation for the underlying stochastic continuous time Markov process behind the GRSM model p0 is left nullspace of transition rate matrix Q (right nullspace of Q') Arguments: - `r`: transition rates - `interval`: time interval between intensity observations - `elementsT`: structure of T matrix elements - `N`: number of HMM states Qtr is the transpose of the Markov process transition rate matrix Q """ function make_ap(r, interval, elementsT, N) Qtr = make_mat(elementsT, r, N) ## transpose of the Markov process transition rate matrix Q kolmogorov_forward(sparse(Qtr'), interval), normalized_nullspace(Qtr) end make_p0(r, elementsT, N) = normalized_nullspace(make_mat(elementsT, r, N)) """ make_logap(r, transitions, interval, G) return log of a and p0 """ function make_logap(r, interval, elementsT, N) a, p0 = make_ap(r, interval, elementsT, N) log.(max.(a, 0)), log.(max.(p0, 0)) end """ set_logb(trace, N, params, reporters) returns matrix logb = P(Observation_i | State_j) for Gaussian distribution -`trace`: Tx2 matrix of intensities. Col 1 = time, Col 2 = intensity -`N`: number of hidden states -`T`: number of observations """ function set_logb(trace, N, params, reporters, probfn=prob_Gaussian) d = probfn(params, reporters, N) logb = Matrix{Float64}(undef, N, length(trace)) t = 1 for obs in trace for j in 1:N logb[j, t] = logpdf(d[j], obs) end t += 1 end return logb end # function set_logb_discrete(trace, N, onstates) # logb = Matrix{Float64}(undef, N, length(trace)) # t = 1 # for obs in trace # if (obs > 0.5 && state ∈ onstates) || (obs < 0.5 && state βˆ‰ onstates) # logb[j, t] = 0.0 # else # logb[j, t] = -Inf # end # end # end """ prob_Gaussian(par, reporters, N) return Gaussian Distribution mean = background + number of reporters * reporter mean variance = sum of variances of background and reporters - `par`: 4 dimemsional vector of mean and std parameters - `reporters`: number of reporters per HMM state -`N`: number of HMM states """ function prob_Gaussian(par, reporters, N) d = Array{Distribution{Univariate,Continuous}}(undef, N) for i in 1:N d[i] = Normal(par[1] + reporters[i] * par[3], sqrt(par[2]^2 + reporters[i] * par[4]^2)) end d end """ prob_GaussianMixture(par,reporters,N) return Gaussian Mixture distribution with 4 Gaussian parameters and 1 weight parameter """ function prob_GaussianMixture(par, reporters, N) d = Array{Distribution{Univariate,Continuous}}(undef, N) for i in 1:N d[i] = MixtureModel(Normal, [(par[1] + reporters[i] * par[3], sqrt(par[2]^2 + reporters[i] * par[4]^2)), (par[1], par[2])], [par[5], 1 - par[5]]) end d end """ prob_GaussianMixture_6(par, reporters, N) Gaussian Mixture distribution with 6 Gaussian parameters and 1 weight parameter """ function prob_GaussianMixture_6(par, reporters, N) d = Array{Distribution{Univariate,Continuous}}(undef, N) for i in 1:N d[i] = MixtureModel(Normal, [(par[1] + reporters[i] * par[3], sqrt(par[2]^2 + reporters[i] * par[4]^2)), (par[5], par[6])], [par[7], 1 - par[7]]) end d end """ kolmogorov_forward(Q::Matrix,interval) return the solution of the Kolmogorov forward equation returns initial condition and solution at time = interval - `Q`: transition rate matrix - `interval`: interval between frames (total integration time) """ function kolmogorov_forward(Q, interval, save=false, method=Tsit5()) tspan = (0.0, interval) prob = ODEProblem(fkf!, Matrix(I, size(Q)), tspan, Q) solve(prob, method, save_everystep=save)[:, 2] end """ fkf!(du,u::Matrix, p, t) in place update of du of ODE system for DifferentialEquations,jl """ function fkf!(du, u::Matrix, p, t) du .= u * p end """ expected_transitions(Ξ±, a, b, Ξ², N, T) returns ΞΎ and Ξ³ ΞΎ[i,j,t] = P(q[t] = S[i], q[t+1] = S[j] | O, Ξ») Ξ³[i,t] = βˆ‘_j ΞΎ[i,j,t] """ function expected_transitions(Ξ±, a, b, Ξ², N, T) ΞΎ = Array{Float64}(undef, N, N, T - 1) Ξ³ = Array{Float64}(undef, N, T - 1) for t in 1:T-1 for j = 1:N for i = 1:N ΞΎ[i, j, t] = Ξ±[i, t] * a[i, j] * b[j, t+1] * Ξ²[j, t+1] end end S = sum(ΞΎ[:, :, t]) ΞΎ[:, :, t] = S == 0.0 ? zeros(N, N) : ΞΎ[:, :, t] / S Ξ³[:, t] = sum(ΞΎ[:, :, t], dims=2) end return ΞΎ, Ξ³ end """ expected_transitions_log(logΞ±, a, b, logΞ², N, T) TBW """ function expected_transitions_log(logΞ±, a, b, logΞ², N, T) ΞΎ = Array{Float64}(undef, N, N, T - 1) Ξ³ = Array{Float64}(undef, N, T - 1) for t in 1:T-1 for j = 1:N for i = 1:N ΞΎ[i, j, t] = logΞ±[i, t] + log(a[i, j]) + log(b[j, t+1]) + logΞ²[j, t+1] end end S = logsumexp(ΞΎ[:, :, t]) ΞΎ[:, :, t] .-= S for i in 1:N Ξ³[i, t] = logsumexp(ΞΎ[i, :, t]) end end return ΞΎ, Ξ³ end """ expected_a(a, b, p0, N, T) expected_a(ΞΎ, Ξ³, N) returns the expected probability matrix a """ function expected_a(a, b, p0, N, T) Ξ±, C = forward(a, b, p0, N, T) Ξ² = backward(a, b, C, N, T) ΞΎ, Ξ³ = expected_transitions(Ξ±, a, b, Ξ², N, T) expected_a(ΞΎ, Ξ³, N) end function expected_a(ΞΎ, Ξ³, N::Int) a = zeros(N, N) ΞΎS = sum(ΞΎ, dims=3) Ξ³S = sum(Ξ³, dims=2) for i in 1:N, j in 1:N a[i, j] = ΞΎS[i, j] / Ξ³S[i] end return a end function expected_a_log(a, b, p0, N, T) Ξ± = forward_log(a, b, p0, N, T) Ξ² = backward_log(a, b, N, T) ΞΎ, Ξ³ = expected_transitions_log(Ξ±, a, b, Ξ², N, T) expected_a_log(ΞΎ, Ξ³, N) end function expected_a_log(ΞΎ, Ξ³, N::Int) a = zeros(N, N) ΞΎS = zeros(N, N) Ξ³S = zeros(N) for i in 1:N for j in 1:N ΞΎS[i, j] = logsumexp(ΞΎ[i, j, :]) end Ξ³S[i] = logsumexp(Ξ³[i, :]) end for i in 1:N, j in 1:N a[i, j] = ΞΎS[i, j] - Ξ³S[i] end return a end function expected_a_loop(a, b, p0, N, T) Ξ± = forward_loop(a, b, p0, N, T) Ξ² = backward_loop(a, b, N, T) ΞΎ, Ξ³ = expected_transitions(Ξ±, a, b, Ξ², N, T) expected_rate(ΞΎ, Ξ³, N) end """ forward(a, b, p0, N, T) returns forward variable Ξ±, and scaling parameter array C using scaled forward algorithm Ξ±[i,t] = P(O1,...,OT,qT=Si,Ξ») Ct = Prod_t 1/βˆ‘_i Ξ±[i,t] """ function forward(a, b, p0, N, T) Ξ± = zeros(N, T) C = Vector{Float64}(undef, T) Ξ±[:, 1] = p0 .* b[:, 1] C[1] = 1 / sum(Ξ±[:, 1]) Ξ±[:, 1] *= C[1] for t in 2:T for j in 1:N for i in 1:N Ξ±[j, t] += Ξ±[i, t-1] * a[i, j] * b[j, t] end end C[t] = 1 / sum(Ξ±[:, t]) Ξ±[:, t] *= C[t] end return Ξ±, C end """ forward_log(a, b, p0, N, T) forward_log!(Ο•, ψ, loga, logb, logp0, N, T) returns log Ξ± (computations are numerically stable) """ function forward_log(loga, logb, logp0, N, T) ψ = zeros(N) Ο• = Matrix{Float64}(undef, N, T) forward_log!(Ο•, ψ, loga, logb, logp0, N, T) return Ο• end function forward_log!(Ο•, ψ, loga, logb, logp0, N, T) Ο•[:, 1] = logp0 + logb[:, 1] for t in 2:T for k in 1:N for j in 1:N ψ[j] = Ο•[j, t-1] + loga[j, k] + logb[k, t] end Ο•[k, t] = logsumexp(ψ) end end end """ forward_loop(a, b, p0, N, T) return Ξ± using unscaled forward algorithm (numerically unstable for large T) """ function forward_loop(a, b, p0, N, T) Ξ± = zeros(N, T) Ξ±[:, 1] = p0 .* b[:, 1] for t in 2:T for j in 1:N for i in 1:N Ξ±[j, t] += Ξ±[i, t-1] * a[i, j] * b[j, t] end end end return Ξ± end """ backward_scaled(a,b) return backward variable Ξ² using scaled backward algorithm Ξ²[i,T] = P(O[t+1]...O[t] | qT = Si,Ξ») """ function backward(a, b, C, N, T) Ξ² = ones(N, T) Ξ²[:, T] /= C[T] for t in T-1:-1:1 for i in 1:N for j in 1:N Ξ²[i, t] += a[i, j] * b[j, t+1] * Ξ²[j, t+1] end end Ξ²[:, t] /= C[t] end return Ξ² end """ backward_log(a, b, N, T) return log Ξ² """ function backward_log(a, b, N, T) loga = log.(a) ψ = zeros(N) Ο• = Matrix{Float64}(undef, N, T) Ο•[:, T] = [0.0, 0.0] for t in T-1:-1:1 for i in 1:N for j in 1:N ψ[j] = Ο•[j, t+1] + loga[i, j] + log.(b[j, t+1]) end Ο•[i, t] = logsumexp(ψ) end end return Ο• end """ backward_loop(a, b, N, T) returns Ξ² using unscaled backward algorithm (numerically unstable for large T) """ function backward_loop(a, b, N, T) Ξ² = zeros(N, T) Ξ²[:, T] = [1.0, 1.0] for t in T-1:-1:1 for i in 1:N for j in 1:N Ξ²[i, t] += a[i, j] * b[j, t+1] * Ξ²[j, t+1] end end end return Ξ² end """ viterbi(loga, logb, logp0, N, T) returns maximum likelihood state path using Viterbi algorithm """ function viterbi(loga, logb, logp0, N, T) Ο• = similar(logb) ψ = similar(Ο•) q = Vector{Int}(undef, T) Ο•[:, 1] = logp0 + logb[:, 1] ψ[:, 1] .= 0 for t in 2:T for j in 1:N m, ψ[j, t] = findmax(Ο•[:, t-1] + loga[:, j]) Ο•[j, t] = m + logb[j, t] end end q[T] = argmax(Ο•[:, T]) for t in T-1:-1:1 q[t] = ψ[q[t+1], t+1] end return q end """ viterbi_exp(a, b, p0, N, T) returns maximum likelihood state path using Viterbi algorithm """ function viterbi_exp(a, b, p0, N, T) loga = log.(a) logb = log.(b) logp0 = log.(p0) viterbi(loga, logb, logp0, N, T) end """ predicted_statepath(r::Vector, N::Int, elementsT, noiseparams, reporters_per_state, probfn, T::Int, interval) predicted_statepath(r, tcomponents, reporter, T, interval) return predicted state path using Viterbi algorithm """ function predicted_statepath(trace, interval, r::Vector, N::Int, elementsT, noiseparams, reporters_per_state, probfn) loga, logp0 = make_logap(r, interval, elementsT, N) logb = set_logb(trace, N, r[end-noiseparams+1:end], reporters_per_state, probfn) viterbi(loga, logb, logp0, N, length(trace)) end function predicted_statepath(trace, interval, r, tcomponents, reporter) predicted_statepath(trace, interval, r, tcomponents.nT, tcomponents.elementsT, reporter.n, reporter.per_state, reporter.probfn) end """ predicted_trace(statepath, noise_dist) predicted_trace(statepath, r, reporter, nstates) return predicted trace from state path """ function predicted_trace(statepath, noise_dist) [mean(noise_dist[state]) for state in statepath] end function predicted_trace(statepath, r, reporter, nstates) d = model.reporter.probfn(r[end-model.reporter.n+1:end], reporter.per_state, nstates) predicted_trace(statepath, d) end """ predicted_trace_state(trace, interval, r::Vector, tcomponents, reporter, noise_dist) return predicted trace and state path """ function predicted_trace_state(trace, interval, r::Vector, tcomponents, reporter, noise_dist) t = predicted_statepath(trace, interval, r, tcomponents, reporter) tp = predicted_trace(t, noise_dist) return tp, t end function predicted_trace_state(trace, interval, model) d = model.reporter.probfn(model.rates[end-model.reporter.n+1:end], model.reporter.per_state, tcomponent(model).nT) predicted_trace_state(trace, interval, model.rates, model.tcomponents, model.reporter, d) end # function predicted_trace_state(trace, interval, model) # t = predicted_statepath(trace, interval, model) # d = model.reporter.probfn(model.rates[end-model.reporter.n+1:end], model.reporter.per_state, tcomponent(model).nT) # tp = [mean(d[state]) for state in t] # return tp, t # end function predicted_statepath(trace, interval, model::AbstractGmodel) tcomponents = tcomponent(model) predicted_statepath(trace, interval, model.rates, tcomponents.nT, tcomponents.elementsT, model.reporter.n, model.reporter.per_state, model.reporter.probfn) end """ predicted_states(data::Union{AbstractTraceData,AbstractTraceHistogramData}, model::AbstractGmodel) return vector of predicted state vectors """ function predicted_states(data::Union{AbstractTraceData,AbstractTraceHistogramData}, model::AbstractGmodel) ts = Vector{Int}[] for t in data.trace[1] push!(ts, predicted_statepath(t, data.interval, model)) end ts end """ predicted_traces(ts::Vector{Vector}, model) predicted_traces(data::Union{AbstractTraceData,AbstractTraceHistogramData}, model) return vector of predicted traces and vector of state paths """ function predicted_traces(ts::Vector, model) tp = Vector{Float64}[] d = model.reporter.probfn(model.rates[end-model.reporter.n+1:end], model.reporter.per_state, tcomponent(model).nT) for t in ts push!(tp, [mean(d[state]) for state in t]) end tp, ts end function predicted_traces(data::Union{AbstractTraceData,AbstractTraceHistogramData}, model) predicted_traces(predicted_states(data, model), model) end
StochasticGene
https://github.com/nih-niddk-mbs/StochasticGene.jl.git
[ "MIT" ]
1.2.5
fc1bcee6037ea393ce28426929eff65c76a86779
code
33142
# This file is part of StochasticGene.jl # io.jl ### Files for saving and reading mh results abstract type Fields end struct Result_Fields <: Fields name::String label::String cond::String gene::String model::String nalleles::String end struct Summary_Fields <: Fields name::String label::String cond::String model::String end """ struct BurstMeasures <: Results Structure for Burst measures """ struct BurstMeasures <: Results mean::Float64 std::Float64 median::Float64 mad::Float64 quantiles::Array end """ decompose_model(model::String) return G, R, S, insertstep given model string """ function decompose_model(model::String) m = parse(Int, model) d = digits(m) return d[4], d[3], d[2], d[1] end # raterow_dict() = Dict([("ml", 1), ("mean", 2), ("median", 3), ("last", 4)]) # statrow_dict() = Dict([("mean", 1), ("SD", 2), ("median", 3), ("MAD", 4)]) """ write_dataframes(resultfolder::String, datapath::String; measure::Symbol=:AIC, assemble::Bool=true, fittedparams=Int[]) write_dataframes(resultfolder::String,datapath::String;measure::Symbol=:AIC,assemble::Bool=true) collates run results into a csv file Arguments - `resultfolder`: name of folder with result files - `datapath`: name of folder where data is stored - `measure`: measure used to assess winner - `assemble`: if true then assemble results into summary files """ function write_dataframes(resultfolder::String, datapath::String; measure::Symbol=:AIC, assemble::Bool=true, fittedparams=Int[]) write_dataframes_only(resultfolder, datapath, assemble=assemble, fittedparams=fittedparams) write_winners(resultfolder, measure) end function write_dataframes_only(resultfolder::String, datapath::String; assemble::Bool=true, fittedparams=Int[]) dfs = make_dataframes(resultfolder, datapath, assemble, fittedparams) for df in dfs for dff in dfs for dfff in dff csvfile = joinpath(resultfolder, dfff[1]) CSV.write(csvfile, dfff[2]) end end end nothing end """ write_winners(resultfolder,measure) Write best performing model for measure """ function write_winners(resultfolder, measure) df = best_measure(resultfolder, measure) if ~isempty(df) for i in eachindex(df) csvfile = joinpath(resultfolder, df[i][1]) CSV.write(csvfile, df[i][2]) end end nothing end """ write_augmented(summaryfile::String, resultfolder::String) write_augmented(summaryfile::String,resultfolder,datapath) Augment summary file with G=2 burst size, model predicted moments, and fit measures """ function write_augmented(summaryfile::String, resultfolder::String) if ~ispath(summaryfile) summaryfile = joinpath(resultfolder, summaryfile) end CSV.write(summaryfile, augment_dataframe(read_dataframe(summaryfile), resultfolder)) end """ read_dataframe(csvfile::String) """ read_dataframe(csvfile::String) = DataFrame(CSV.File(csvfile)) """ get_suffix(file::String) """ get_suffix(file::String) = chop(file, tail=4), last(file, 3) # does not account for csv files with less than 4 fields function fields(file::String) file, suffix = get_suffix(file) v = split(file, "_") if suffix == "csv" if length(v) == 4 s = Summary_Fields(v[1], v[2], v[3], v[4]) else println(file) throw("Incorrect file name format") end else if length(v) == 6 s = Result_Fields(v[1], v[2], v[3], v[4], v[5], v[6]) elseif length(v) == 5 s = Result_Fields(v[1], v[2], "", v[3], v[4], v[5]) else println(file) throw("Incorrect file name format") end end return s end function isratefile(folder::String) files = readdir(folder) any(occursin.(".csv", files) .& occursin.("rates", files)) end isfish(string::String) = occursin("FISH", string) function get_genes(file::String) r, header = readdlm(file, ',', header=true) return r[:, 1] end get_genes(root, cond, datapath) = get_genes(cond, joinpath(root, datapath)) function get_genes(cond, datapath) genes = Vector{String}(undef, 0) files = readdir(datapath) for file in files if occursin(cond, file) push!(genes, split(file, "_")[1]) end end return genes end """ get_genes(folder,type,label,cond,model) """ function get_genes(folder, type, label, cond, model) genes = Array{String,1}(undef, 0) files = get_files(folder, type, label, cond, model) for file in files push!(genes, get_gene(file)) end return genes end get_files(folder, resultname) = get_files(folder::String, resultname, label, cond, model) = get_files(get_resultfiles(folder), resultname, label, cond, model) file_indices(parts, resultname, label, cond, model) = (getfield.(parts, :name) .== resultname) .& (getfield.(parts, :label) .== label) .& (getfield.(parts, :cond) .== cond) .& occursin.(model, getfield.(parts, :model)) function get_files(files::Vector, resultname, label, cond, model) parts = fields.(files) files[file_indices(parts, resultname, label, cond, model)] # files[(getfield.(parts, :name).==resultname).&(getfield.(parts, :label).==label).&(getfield.(parts, :cond).==cond).&(getfield.(parts, :model).==model)] end get_gene(file::String) = fields(file).gene get_model(file::String) = fields(file).model get_label(file::String) = fields(file).label get_cond(file::String) = fields(file).cond get_nalleles(file::String) = fields(file).nalleles get_fields(parts::Vector{T}, field::Symbol) where {T<:Fields} = unique(getfield.(parts, field)) get_models(parts::Vector{T}) where {T<:Fields} = get_fields(parts, :model) get_genes(parts::Vector{T}) where {T<:Fields} = get_fields(parts, :gene) get_conds(parts::Vector{T}) where {T<:Fields} = get_fields(parts, :cond) get_labels(parts::Vector{T}) where {T<:Fields} = get_fields(parts, :label) get_names(parts::Vector{T}) where {T<:Fields} = get_fields(parts, :name) get_nalleles(parts::Vector{T}) where {T<:Fields} = get_fields(parts, :nalleles) get_resultfiles(folder::String) = get_resultfiles(readdir(folder)) get_resultfiles(files::Vector) = files[occursin.(".txt", files).&occursin.("_", files)] get_summaryfiles(folder::String) = get_summaryfiles(readdir(folder)) get_summaryfiles(files::Vector) = files[occursin.(".csv", files).&occursin.("_", files)] get_summaryfiles(files::Vector, name) = files[occursin.(".csv", files).&occursin.(name, files)] get_ratesummaryfiles(files::Vector) = get_summaryfiles(files, "rates") get_ratesummaryfiles(folder::String) = get_ratesummaryfiles(get_summaryfiles(folder)) get_measuresummaryfiles(files::Vector) = get_summaryfiles(files, "measures") get_measuresummaryfiles(folder::String) = get_measuresummaryfiles(get_summaryfiles(folder)) get_burstsummaryfiles(files::Vector) = get_summaryfiles(files, "burst") get_burstsummaryfiles(folder::String) = get_burstsummaryfiles(get_summaryfiles(folder)) """ write_moments(outfile,genelist,cond,datapath,root) """ function write_moments(outfile, genelist, cond, datapath, root) f = open(outfile, "w") writedlm(f, ["Gene" "Expression Mean" "Expression Variance"], ',') for gene in genelist h = get_histogram_rna(gene, cond, datapath, root) writedlm(f, [gene mean_histogram(h) var_histogram(h)], ',') end close(f) end """ write_histograms(resultfolder,ratefile,cell,datacond,G::Int,datapath::String,root,outfolder = "histograms") """ function write_histograms(resultfolder, ratefile, cell, datacond, G::Int, datapath::String, root, outfolder="histograms") ratefile = joinpath(resultfolder, ratefile) rates, head = readdlm(ratefile, ',', header=true) outfolder = joinpath(resultfolder, outfolder) if ~isdir(outfolder) mkpath(outfolder) end cond = string.(split(datacond, "-")) for r in eachrow(rates) h = histograms(r, cell, cond, G, datapath, root) for i in eachindex(cond) f = open(joinpath(outfolder, string(r[1]) * cond[i] * ".txt"), "w") writedlm(f, h[i]) close(f) end end end """ assemble_all(folder;fittedparams) """ function assemble_all(folder::String; fittedparams=Int[]) files = get_resultfiles(folder) parts = fields.(files) labels = get_labels(parts) conds = get_conds(parts) models = get_models(parts) names = get_names(parts) if isempty(fittedparams) fittedparams = collect(1:num_rates(models[1])-1) end assemble_all(folder, files, labels, conds, models, names) end function assemble_all(folder::String, files::Vector, labels::Vector, conds::Vector, models::Vector, names) parts = fields.(files) for l in labels, c in conds, g in models any(file_indices(parts, "rates", l, c, g) .== 1) && assemble_all(folder, files, l, c, g, names) end end function assemble_all(folder::String, files::Vector, label::String, cond::String, model::String, names) labels = assemble_rates(folder, files, label, cond, model) assemble_measures(folder, files, label, cond, model) assemble_stats(folder, files, label, cond, model) if model != "1" && "burst" ∈ names assemble_burst_sizes(folder, files, label, cond, model) end if "optimized" ∈ names assemble_optimized(folder, files, label, cond, model, labels) end end function assemble_files(folder::String, files::Vector, outfile::String, header, readfunction) if ~isempty(files) f = open(outfile, "w") writedlm(f, header, ',') for file in files gene = get_gene(file) r = readfunction(joinpath(folder, file)) writedlm(f, [gene r], ',') end close(f) end end """ assemble_rates(folder::String, files::Vector, label::String, cond::String, model::String) TBW """ function assemble_rates(folder::String, files::Vector, label::String, cond::String, model::String) outfile = joinpath(folder, "rates_" * label * "_" * cond * "_" * model * ".csv") ratefiles = get_files(files, "rates", label, cond, model) labels = readdlm(joinpath(folder, ratefiles[1]), ',', header=true)[2] # header = ratelabels(model, split(cond, "-")) assemble_files(folder, ratefiles, outfile, ratelabels(labels, split(cond, "-")), readmedian) return labels end """ assemble_measures(folder::String, files, label::String, cond::String, model::String) write all measures into a single file """ function assemble_measures(folder::String, files, label::String, cond::String, model::String) outfile = joinpath(folder, "measures_" * label * "_" * cond * "_" * model * ".csv") header = ["Gene" "Nalleles" "Deviance" "LogMaxLikelihood" "WAIC" "WAIC SE" "AIC" "Acceptance" "Temperature" "Rhat"] # assemble_files(folder,get_files(files,"measures",label,cond,model),outfile,header,readmeasures) files = get_files(files, "measures", label, cond, model) f = open(outfile, "w") writedlm(f, header, ',') for file in files gene = get_gene(file) nalleles = get_nalleles(file) r = readmeasures(joinpath(folder, file)) writedlm(f, [gene nalleles r], ',') end close(f) end function assemble_measures_model(folder::String, label::String, cond::String, gene::String) outfile = joinpath(folder, "measures_" * label * "_" * cond * "_" * gene * ".csv") header = ["Model" "Nalleles" "normalized LL" "LogMaxLikelihood" "WAIC" "WAIC SE" "AIC" "Acceptance" "Temperature" "Rhat"] files = get_files(get_resultfiles(folder), "measures", label, cond, "") println(files) f = open(outfile, "w") writedlm(f, header, ',') for file in files nalleles = get_nalleles(file) r = readmeasures(joinpath(folder, file)) writedlm(f, [get_model(file) nalleles r], ',') end close(f) end """ assemble_optimized(folder::String, files, label::String, cond::String, model::String, labels) TBW """ function assemble_optimized(folder::String, files, label::String, cond::String, model::String, labels) outfile = joinpath(folder, "optimized_" * label * "_" * cond * "_" * model * ".csv") assemble_files(folder, get_files(files, "optimized", label, cond, model), outfile, labels, read_optimized) end """ assemble_stats(folder::String, files, label::String, cond::String, model::String) TBW """ function assemble_stats(folder::String, files, label::String, cond::String, model::String) outfile = joinpath(folder, "stats_" * label * "_" * cond * "_" * model * ".csv") statfiles = get_files(files, "param-stats", label, cond, model) labels = readdlm(joinpath(folder, statfiles[1]), ',', header=true)[2] assemble_files(folder, statfiles, outfile, statlabels(labels), readstats) end """ assemble_burst_sizes(folder, files, label, cond, model) TBW """ function assemble_burst_sizes(folder, files, label, cond, model) outfile = joinpath(folder, "burst_" * label * "_" * cond * "_" * model * ".csv") assemble_files(folder, get_files(files, "burst", label, cond, model), outfile, ["Gene" "BurstMean" "BurstSD" "BurstMedian" "BurstMAD"], read_burst) end """ rlabels(model::AbstractGRSMmodel) TBW """ function rlabels(model::AbstractGRSMmodel) rlabels_GRSM(model) end function rlabels_GRSM(model) labels = String[] for t in model.Gtransitions push!(labels, "Rate$(t[1])$(t[2])") end push!(labels, "Initiate") for i in 1:model.R-1 push!(labels, "Rshift$i") end push!(labels, "Eject") for i in 1:model.S push!(labels, "Splice$i") end push!(labels, "Decay") if typeof(model.reporter) == HMMReporter for i in 1:model.reporter.n push!(labels, "noiseparam$i") end # for i in 1:div(model.reporter.weightind - num_rates(model) - 1, 2) # push!(labels, "noise_mean$i") # push!(labels, "noise_std$i") # end # for i in 1:num_rates(model)+model.reporter.n-model.reporter.weightind+1 # push!(labels, "bias$i") # end end reshape(labels, 1, :) end function rlabels(model::GRSMhierarchicalmodel) labels = String[] l = rlabels_GRSM(model) for i in 1:model.pool.nhyper+model.pool.nindividuals append!(labels, l) end reshape(labels, 1, :) end """ rlabels(model::AbstractGMmodel) """ function rlabels(model::AbstractGMmodel) labels = String[] for t in model.Gtransitions push!(labels, "Rate$(t[1])$(t[2])") end push!(labels, "Eject") push!(labels, "Decay") if typeof(model.reporter) == HMMReporter for i in 1:model.reporter.n push!(labels, "noiseparam$i") end # for i in 1:div(model.reporter.weightind - num_rates(model) - 1, 2) # push!(labels, "noise_mean$i") # push!(labels, "noise_std$i") # end # for i in 1:num_rates(model)+model.reporter.n-model.reporter.weightind+1 # push!(labels, "bias$i") # end end reshape(labels, 1, :) end function rlabels(model::String) G = parse(Int, model) n = G - 1 Grates = Array{String,2}(undef, 1, 2 * n) for i = 0:n-1 Grates[1, 2*i+1] = "Rate$i$(i+1)" Grates[1, 2*i+2] = "Rate$(i+1)$i" end return [Grates "Eject" "Decay"] end function rlabels(model::String, conds::Vector) nsets = length(conds) r = rlabels(model) if nsets == 1 return r else rates = r .* conds[1] for i = 2:nsets rates = [rates r .* conds[i]] end return rates end end function rlabels(labels::Matrix, conds::Vector) nsets = length(conds) r = labels if nsets == 1 return r else rates = r .* conds[1] for i = 2:nsets rates = [rates r .* reshape(conds[i], 1, length(conds))] end return rates end end rlabels(model::String, conds, fittedparams) = rlabels(model, conds)[1:1, fittedparams] rlabels(labels::Matrix, conds, fittedparams) = rlabels(labels, conds)[1:1, fittedparams] ratelabels(labels::Matrix, conds) = ["Gene" rlabels(labels, conds)] """ statlabels(model::String, conds, fittedparams) TBW """ function statlabels(model::String, conds, fittedparams) label = ["_Mean", "_SD", "_Median", "_MAD", "_CI2.5", "_CI97.5"] Grates = rlabels(model, conds, fittedparams) rates = Matrix{String}(undef, 1, 0) for l in label rates = [rates Grates .* l] end return ["Gene" rates] end function statlabels(labels::Matrix) label = ["_Mean", "_SD", "_Median", "_MAD", "_CI2.5", "_CI97.5"] rates = Matrix{String}(undef, 1, 0) for l in label rates = [rates labels .* l] end return ["Gene" rates] end """ optlabels(model::String, conds, fittedparams) TBW """ optlabels(model::String, conds, fittedparams) = ["Gene" rlabels(model, conds, fittedparams) "LL" "Convergence"] optlabels(labels::Matrix, conds, fittedparams) = ["Gene" rlabels(labels, conds) "LL" "Convergence"] function get_all_rates(file::String, header::Bool) r = readdlm(file, ',', header=header) if header r = r[1] end return r end """ filename(data, model::AbstractGRSMmodel) filename(data, model::AbstractGMmodel) return output file names """ filename(data, model::AbstractGRSMmodel) = filename(data.label, data.gene, model.G, model.R, model.S, model.insertstep, model.nalleles) filename(data, model::AbstractGMmodel) = filename(data.label, data.gene, model.G, model.nalleles) filename(label::String, gene::String, G::Int, R::Int, S::Int, insertstep::Int, nalleles::Int) = filename(label, gene, "$G" * "$R" * "$S" * "$insertstep", "$(nalleles)") filename(label::String, gene, G::Int, nalleles::Int) = filename(label, gene, "$G", "$(nalleles)") filename(label::String, gene::String, model::String, nalleles::String) = "_" * label * "_" * gene * "_" * model * "_" * nalleles * ".txt" """ writeall(path::String,fit,stats,measures,data,temp,model::AbstractGmodel;optimized=0,burst=0) """ function writeall(path::String, fits, stats, measures, data, temp, model::AbstractGmodel; optimized=0, burst=0, writesamples=false) if ~isdir(path) mkpath(path) end name = filename(data, model) write_rates(joinpath(path, "rates" * name), fits, stats, model) write_measures(joinpath(path, "measures" * name), fits, measures, deviance(fits, data, model), temp) write_param_stats(joinpath(path, "param-stats" * name), stats, model) if optimized != 0 write_optimized(joinpath(path, "optimized" * name), optimized) end if burst != 0 write_burstsize(joinpath(path, "burst" * name), burst) end if writesamples write_array(joinpath(path, "ll_sampled_rates" * name), fits.ll) write_array(joinpath(path, "sampled_rates" * name), permutedims(inverse_transform_rates(fits.param, model))) end end function writeall(path::String, fits, stats, measures, data, temp, model::GRSMhierarchicalmodel; optimized=0, burst=0, writesamples=false) name = filename(data, model) write_pool(joinpath(path, "pool" * name), fits, stats, model) if ~isdir(path) mkpath(path) end name = filename(data, model) write_rates(joinpath(path, "rates" * name), fits, stats, model) write_measures(joinpath(path, "measures" * name), fits, measures, deviance(fits, data, model), temp) write_param_stats(joinpath(path, "param-stats" * name), stats, model) write_pool(joinpath(path, "pool" * name), fits, stats, model) if optimized != 0 write_optimized(joinpath(path, "optimized" * name), optimized) end if burst != 0 write_burstsize(joinpath(path, "burst" * name), burst) end if writesamples write_array(joinpath(path, "ll_sampled_rates" * name), fits.ll) write_array(joinpath(path, "sampled_rates" * name), permutedims(inverse_transform_rates(fits.param, model))) end end """ write_rates(file::String,fits) Write rate parameters, rows in order are maximum likelihood mean median last accepted """ function write_rates(file::String, fits::Fit, stats, model) f = open(file, "w") writedlm(f, rlabels(model), ',') # labels writedlm(f, [get_rates(fits.parml, model)], ',') # max posterior writedlm(f, [get_rates(stats.meanparam, model, false)], ',') # mean posterior writedlm(f, [get_rates(stats.medparam, model, false)], ',') # median posterior writedlm(f, [get_rates(fits.param[:, end], model)], ',') # last sample close(f) end """ write_pool(file::String, fits::Fit, stats, model) write pool parameters into a file for hierarchichal models """ function write_pool(file::String, fits::Fit, stats, model) f = open(file, "w") writedlm(f, rlabels(model)[1:1, 1:model.pool.nrates], ',') # labels writedlm(f, [get_rates(fits.parml, model)[1:model.pool.nrates]], ',') # max posterior writedlm(f, [get_rates(stats.meanparam, model, false)[1:model.pool.nrates]], ',') # mean posterior writedlm(f, [get_rates(stats.medparam, model, false)[1:model.pool.nrates]], ',') # median posterior writedlm(f, [get_rates(fits.param[:, end], model)[1:model.pool.nrates]], ',') # last sample close(f) end """ write_measures(file::String, fits::Fit, measures::Measures, dev, temp) write_measures into a file """ function write_measures(file::String, fits::Fit, measures::Measures, dev, temp) f = open(file, "w") writedlm(f, [fits.llml mean(fits.ll) std(fits.ll) quantile(fits.ll, [0.025; 0.5; 0.975])' measures.waic[1] measures.waic[2] aic(fits)], ',') writedlm(f, dev, ',') writedlm(f, [fits.accept fits.total], ',') writedlm(f, temp, ',') writedlm(f, measures.rhat', ',') writedlm(f, maximum(measures.rhat), ',') close(f) end """ write_param_stats(file, stats::Stats, model) write parameter statistics into a file """ function write_param_stats(file, stats::Stats, model) f = open(file, "w") writedlm(f, rlabels(model)[1:1, model.fittedparam], ',') writedlm(f, stats.meanparam', ',') writedlm(f, stats.stdparam', ',') writedlm(f, stats.medparam', ',') writedlm(f, stats.madparam', ',') writedlm(f, stats.qparam, ',') writedlm(f, stats.corparam, ',') writedlm(f, stats.covparam, ',') writedlm(f, stats.covlogparam, ',') close(f) end """ write_optimized(file,optimized) """ function write_optimized(file::String, optimized) f = open(file, "w") writedlm(f, exp.(Optim.minimizer(optimized))', ',') writedlm(f, Optim.minimum(optimized), ',') writedlm(f, Optim.converged(optimized), ',') close(f) end """ write_burstsize(file,burstsize) """ function write_burstsize(file::String, b::BurstMeasures) f = open(file, "w") writedlm(f, b.mean, ',') writedlm(f, b.std, ',') writedlm(f, b.median, ',') writedlm(f, b.mad, ',') writedlm(f, b.quantiles, ',') close(f) end """ write_MHsamples(file::String,samples::Matrix) """ write_array(file::String, d::Array) = writedlm(file, d, header=false) """ get_row() """ get_row() = Dict([("ml", 1); ("mean", 2); ("median", 3); ("last", 4)]) """ get_ratetype() """ get_ratetype() = invert_dict(get_row()) """ occursin_file(a, b, file) determine if string a or string b occurs in file (case insensitive) """ function occursin_file(a, b, file::String) occursin(Regex("DS_Store", "i"), file) && return false if isempty(a) return occursin(Regex(b, "i"), file) elseif isempty(b) return occursin(Regex(a, "i"), file) else return occursin(Regex(a, "i"), file) && occursin(Regex(b, "i"), file) end end """ read_rna(gene, cond, datapath) read in rna histograms """ function read_rna(gene, cond, datapath) h = readfile(gene, cond, datapath)[:, 1] return length(h), h end """ readfiles(gene::String, cond::String, datapath::Vector) read in a set of files """ function readfiles(gene::String, cond::String, datapath::Vector) c = Vector{Vector}(undef, 0) for i in eachindex(datapath) push!(c, readfile(gene, cond, datapath[i])) end c end """ readfile(gene::String, cond::String, path::String) read file if name includes gene and cond """ function readfile(gene::AbstractString, cond::AbstractString, path::AbstractString) if isfile(path) return readfile(path) else for (root, dirs, files) in walkdir(path) for file in files target = joinpath(root, file) if occursin_file(gene, cond, target) return readfile(target) end end end end end """ readfile(file::String) read file accounting for delimiter and headers """ function readfile(file::String) if occursin("csv", file) c = readfile_csv(file) else c = readdlm(file) if typeof(c[1]) <: AbstractString && occursin(",", c[1]) c = readdlm(file, ',') end end if typeof(c[1, 1]) <: AbstractString c = float.(c[2:end, :]) end return c end function readfile_csv(file::String) c = readdlm(file, ',') if typeof(c[1, :]) <: AbstractString c = float.(c[2:end, :]) end return c end """ readfile(file::String, col::Int) read file and return given column """ readfile(file::String, col::Int) = readfile(file)[:, col] """ read_dwelltimes(datapath) read in a set of dwelltime files and return vector of time bins and values """ function read_dwelltimes(datapath) bins = Vector{Vector}(undef, 0) DT = Vector{Vector}(undef, 0) for i in eachindex(datapath) c = readfile(datapath[i]) push!(bins, c[:, 1]) push!(DT, c[:, 2]) end bins, DT end function read_tracefiles(path, cond1, traceinfo::Tuple, col=3) start = max(round(Int, traceinfo[2] / traceinfo[1]), 1) stop = traceinfo[3] < 0 ? -1 : max(round(Int, traceinfo[3] / traceinfo[1]), 1) read_tracefiles(path, cond1, start, stop, col) end """ read_tracefiles(path::String, cond1::String, start::Int, cond2::String="", col=3) read in trace files """ function read_tracefiles(path::String, cond1::String, start::Int, stop::Int, col=3) traces = Vector[] if isempty(path) return traces else for (root, dirs, files) in walkdir(path) for file in files if occursin(cond1, file) t = readfile(joinpath(root, file), col) if stop < 0 (start <= length(t)) && push!(traces, t[start:end]) else (stop <= length(t)) && push!(traces, t[start:stop]) end end end end traces = traces[.!isempty.(traces)] set = sum.(traces) return traces[unique(i -> set[i], eachindex(set))] # only return unique traces end end """ fix_tracefiles(path::String) TBW """ function fix_tracefiles(path::String) for (root, dirs, files) in walkdir(path) for file in files target = joinpath(root, file) t = readdlm(target, header=true) writedlm(target, [t[1] t[1][:, 2]]) end end end """ readrates(infolder, label, gene, G, R, S, insertstep, nalleles, ratetype="median") """ function readrates(infolder, label, gene, G, R, S, insertstep, nalleles, ratetype="median") if R == 0 name = filename(label, gene, G, nalleles) else name = filename(label, gene, G, R, S, insertstep, nalleles) end readrates(joinpath(infolder, "rates" * name), get_row(ratetype)) end """ readrates(file::String,row::Int) readrates(file::String) row 1 maximum likelihood 2 mean 3 median 4 last value of previous run """ readrates(file::String, row::Int) = readrow(file, row) readrates(file::String) = readrates(file, 3) """ get_row(ratetype) """ function get_row(ratetype) if ratetype == "ml" row = 1 elseif ratetype == "mean" row = 2 elseif ratetype == "median" row = 3 elseif ratetype == "last" row = 4 else row = 3 end row end function readrow(file::String, row, delim=',') if isfile(file) && ~isempty(read(file)) contents = readdlm(file, delim, header=false) if ~(typeof(contents[1]) <: Number) contents = readdlm(file, delim, header=true)[1] end if row <= size(contents, 1) m = contents[row, :] return m[.~isempty.(m)] else println("row too large, returning median") return contents[3, :] end else println(file, " does not exist") return Float64[] end end function readrow_flip(file, row) m = readrow(file, row) reshape(m, 1, length(m)) end function readmeasures(file::String) d = readdeviance(file) w = readwaic(file) a = readaccept(file) t = readtemp(file) r = readrhat(file) [d[1] w[1] w[7] w[8] w[9] a t[1] r[1]] end readdeviance(file::String) = readrow(file, 2) readwaic(file::String) = readrow(file, 1) function readaccept(file::String) a = readrow(file, 3) a[1] / a[2] end readtemp(file::String) = readrow(file, 4) readrhat(file::String) = readrow(file, 6) function readml(ratefile::String) m = readrow(ratefile, 1, true) reshape(m, 1, length(m)) end function readmean(ratefile::String) m = readrow(ratefile, 2, true) reshape(m, 1, length(m)) end function readsd(ratefile::String) m = readrow(ratefile, 2) reshape(m, 1, length(m)) end function readstats(statfile::String) mean = readrow_flip(statfile, 1) sd = readrow_flip(statfile, 2) median = readrow_flip(statfile, 3) mad = readrow_flip(statfile, 4) credl = readrow_flip(statfile, 5) credh = readrow_flip(statfile, 7) [mean sd median mad credl credh] end function readmedian(statfile::String) m = readrow(statfile, 3) reshape(m, 1, length(m)) end function readmad(statfile::String) m = readrow(file, 4) reshape(m, 1, length(m)) end function read_corparam(file::String) c = readdlm(file, ',') n = length(c[1, :]) # c[5+n:4+2*n,1:n] c[8:7+n, 1:n] end function read_covparam(file::String) c = readdlm(file, ',') read_covparam(c) end function read_covparam(c::Matrix) n = length(c[1, :]) # c[5+2*n:4+3*n,1:n] c[8+n:7+2*n, 1:n] end function read_covlogparam(file::String) c = readdlm(file, ',') n = length(c[1, :]) c[8+2*n:7+3*n, 1:n] end read_crosscov(statfile::String) = read_crosscov(read_covparam(statfile)) function read_crosscov(C::Matrix) c = Float64[] N = size(C, 1) for i in 1:N for j in i+1:N push!(c, C[i, j]) end end c end function read_burst(file::String) b = readdlm(file, ',') reshape(b[1:4], 1, 4) end function read_optimized(file::String) rates = readrow_flip(file, 1) ll = readrow(file, 2) conv = readrow(file, 3) [rates ll conv] end function write_residency_G(fileout::String, filein::String, G, header) rates = get_all_rates(filein, header) n = G - 1 f = open(fileout, "w") writedlm(f, ["gene" collect(0:n)'], ',') for r in eachrow(rates) writedlm(f, [r[1] residenceprob_G(r[2:2*n+1], n)], ',') end close(f) end """ change_suffix(old, new, folder) TBW """ function change_suffix(old, new, folder) for (root, dirs, files) in walkdir(folder) for file in files target = joinpath(root, file) if endswith(target, old) mv(target, replace(target, old => new)) end end end end """ change_pattern(old, new, folder) TBW """ function change_pattern(old, new, folder) for (root, dirs, files) in walkdir(folder) for file in files target = joinpath(root, file) if occursin(old, target) mv(target, replace(target, old => new)) println(target) end end end end # Functions for saving and loading data and models # """ # write_log(file,datafile,data,model) # write all information necessary for rerunning # """ # function save_data(file::String,data::TransientRNAData) # f = open(file,"w") # writedlm(f, [typeof(data)]) # writedlm(f,[data.label]) # writedlm(f,[data.gene]) # writedlm(f,[data.nRNA]) # writedlm(f,[data.time]) # writedlm(f,[data.histRNA]) # close(f) # end # function load_data(file::String, model::AbstractGMmodel) # end function save_model(file::String, model::AbstractGMmodel) f = open(file, "w") write(f, model.G) writedlm(f, model.nalleles) writedlm(f, model.ratepriors) writedlm(f, model.proposal) writedlm(f, model.fittedparam) writedlm(f, model.method) close(f) end # function load_model(file::String, model::AbstractGRSMmodel) # end
StochasticGene
https://github.com/nih-niddk-mbs/StochasticGene.jl.git
[ "MIT" ]
1.2.5
fc1bcee6037ea393ce28426929eff65c76a86779
code
18047
# This file is part of StochasticGene.jl # metropolis_hastings.jl """ struct MHOptions <: Options Structure for MH options """ struct MHOptions <: Options samplesteps::Int64 warmupsteps::Int64 annealsteps::Int64 maxtime::Float64 temp::Float64 tempanneal::Float64 end """ struct Fit <: Results Structure for MH results """ struct Fit <: Results param::Array ll::Array parml::Array llml::Float64 lppd::Array pwaic::Array prior::Float64 accept::Int total::Int end """ struct Stats Structure for parameter statistics results """ struct Stats meanparam::Array stdparam::Array medparam::Array madparam::Array qparam::Array corparam::Array covparam::Array covlogparam::Array end """ Structure for computed measures -`waic`: Watanabe-Akaike information criterion -`rhat`: r-hat convergence diagnostic """ struct Measures waic::Tuple rhat::Vector end """ run_mh(data,model,options) returns fits, stats, measures Run Metropolis-Hastings MCMC algorithm and compute statistics of results -`data`: AbstractExperimentalData structure -`model`: AbstractGmodel structure with a logprior function -`options`: MHOptions structure model and data must have a likelihoodfn function """ function run_mh(data::AbstractExperimentalData, model::AbstractGmodel, options::MHOptions) fits, waic = metropolis_hastings(data, model, options) if options.samplesteps > 0 stats = compute_stats(fits.param, model) rhat = compute_rhat([fits]) measures = Measures(waic, vec(rhat)) else stats = 0 measures = 0 end return fits, stats, measures end """ run_mh(data,model,options,nchains) """ function run_mh(data::AbstractExperimentalData, model::AbstractGmodel, options::MHOptions, nchains) if nchains == 1 return run_mh(data, model, options) else sd = run_chains(data, model, options, nchains) chain = extract_chain(sd) waic = pooled_waic(chain) fits = merge_fit(chain) stats = compute_stats(fits.param, model) rhat = compute_rhat(chain) return fits, stats, Measures(waic, vec(rhat)) end end """ run_chains(data,model,options,nchains) returns an array of Futures Runs multiple chains of MCMC alorithm """ function run_chains(data, model, options, nchains) sd = Array{Future,1}(undef, nchains) for chain in 1:nchains sd[chain] = @spawn metropolis_hastings(data, model, options) end return sd end """ metropolis_hastings(param,data,model,options) returns fit structure and waic tuple Metropolis-Hastings MCMC algorithm param = array of parameters to be fit model, data, and options are structures stochastic kinetic transcription models Data can include ON and OFF MS2/PP7 reporter time distributions from live cell recordings, scRNA or FISH mRNA data, and burst correlations between alleles """ function metropolis_hastings(data, model, options) param, d = initial_proposal(model) ll, logpredictions = loglikelihood(param, data, model) maxtime = options.maxtime totalsteps = options.warmupsteps + options.samplesteps + options.annealsteps parml = param llml = ll proposalcv = model.proposal if options.annealsteps > 0 param, parml, ll, llml, logpredictions, temp = anneal(logpredictions, param, parml, ll, llml, d, model.proposal, data, model, options.annealsteps, options.temp, options.tempanneal, time(), maxtime * options.annealsteps / totalsteps) end if options.warmupsteps > 0 param, parml, ll, llml, d, proposalcv, logpredictions = warmup(logpredictions, param, param, ll, ll, d, model.proposal, data, model, options.warmupsteps, options.temp, time(), maxtime * options.warmupsteps / totalsteps) end fits = sample(logpredictions, param, parml, ll, llml, d, proposalcv, data, model, options.samplesteps, options.temp, time(), maxtime * options.samplesteps / totalsteps) waic = compute_waic(fits.lppd, fits.pwaic, data) return fits, waic end """ function anneal(logpredictions,param,parml,ll,llml,d,proposalcv,data,model,samplesteps,temp,t1,maxtime) returns variables necessary to continue MCMC (param,parml,ll,llml,logpredictions,temp) runs MCMC with temperature dropping from tempanneal towards temp """ function anneal(logpredictions, param, parml, ll, llml, d, proposalcv, data, model, samplesteps, temp, tempanneal, t1, maxtime) parout = Array{Float64,2}(undef, length(param), samplesteps) prior = logprior(param, model) step = 0 annealrate = 3 / samplesteps anneal = 1 - annealrate # annealing rate with time constant of samplesteps/3 proposalcv = 0.02 while step < samplesteps && time() - t1 < maxtime step += 1 _, logpredictions, param, ll, prior, d = mhstep(logpredictions, param, ll, prior, d, proposalcv, model, data, tempanneal) if ll < llml llml, parml = ll, param end parout[:, step] = param tempanneal = anneal * tempanneal + annealrate * temp end return param, parml, ll, llml, logpredictions, temp end """ warmup(logpredictions,param,rml,ll,llml,d,sigma,data,model,samplesteps,temp,t1,maxtime) returns param,parml,ll,llml,d,proposalcv,logpredictions runs MCMC for options.warmupstep number of samples and does not collect results """ function warmup(logpredictions, param, parml, ll, llml, d, proposalcv, data, model, samplesteps, temp, t1, maxtime) parout = Array{Float64,2}(undef, length(param), samplesteps) prior = logprior(param, model) step = 0 accepttotal = 0 while step < samplesteps && time() - t1 < maxtime step += 1 accept, logpredictions, param, ll, prior, d = mhstep(logpredictions, param, ll, prior, d, proposalcv, model, data, temp) if ll < llml llml, parml = ll, param end parout[:, step] = param accepttotal += accept end # covparam = cov(parout[:,1:step]')*(2.4)^2 / length(param) # if isposdef(covparam) && step > 1000 && accepttotal/step > .25 # d=proposal_dist(param,covparam,model) # proposalcv = covparam # println(proposalcv) # end return param, parml, ll, llml, d, proposalcv, logpredictions end """ sample(logpredictions,param,parml,ll,llml,d,proposalcv,data,model,samplesteps,temp,t1,maxtime) returns Fit structure ll is negative loglikelihood """ function sample(logpredictions, param, parml, ll, llml, d, proposalcv, data, model, samplesteps, temp, t1, maxtime) llout = Array{Float64,1}(undef, samplesteps) pwaic = (0, log.(max.(logpredictions, eps(Float64))), zeros(length(logpredictions))) lppd = fill(-Inf, length(logpredictions)) accepttotal = 0 parout = Array{Float64,2}(undef, length(param), samplesteps) prior = logprior(param, model) step = 0 while step < samplesteps && time() - t1 < maxtime step += 1 accept, logpredictions, param, ll, prior, d = mhstep(logpredictions, param, ll, prior, d, proposalcv, model, data, temp) if ll < llml llml, parml = ll, param end parout[:, step] = param llout[step] = ll accepttotal += accept lppd, pwaic = update_waic(lppd, pwaic, logpredictions) end pwaic = step > 1 ? pwaic[3] / (step - 1) : pwaic[3] lppd .-= log(step) Fit(parout[:, 1:step], llout[1:step], parml, llml, lppd, pwaic, prior, accepttotal, step) end """ mhstep(logpredictions,param,ll,prior,d,sigma,model,data,temp) returns 1,logpredictionst,paramt,llt,priort,dt if accept 1,logpredictionst,paramt,llt,priort,dt if not ll is negative log likelihood """ function mhstep(logpredictions, param, ll, prior, d, proposalcv, model, data, temp) paramt, dt = proposal(d, proposalcv, model) priort = logprior(paramt, model) llt, logpredictionst = loglikelihood(paramt, data, model) mhstep(logpredictions, logpredictionst, ll, llt, param, paramt, prior, priort, d, dt, temp) end function mhstep(logpredictions, logpredictionst, ll, llt, param, paramt, prior, priort, d, dt, temp) # if rand() < exp((ll + prior - llt - priort + mhfactor(param,d,paramt,dt))/temp) if rand() < exp((ll + prior - llt - priort) / temp) return 1, logpredictionst, paramt, llt, priort, dt else return 0, logpredictions, param, ll, prior, d end end """ update_waic(lppd,pwaic,logpredictions) returns lppd and pwaic, which are the running sum and variance of -logpredictions (- sign needed because logpredictions is negative loglikelihood) """ function update_waic(lppd, pwaic, logpredictions) lppd = logsumexp(lppd, -logpredictions) lppd, var_update(pwaic, -logpredictions) end """ computewaic(lppd::Array{T},pwaic::Array{T},data) where {T} returns WAIC and SE of WAIC using lppd and pwaic computed in metropolis_hastings() """ function compute_waic(lppd::Array{T}, pwaic::Array{T}, data) where {T} se = sqrt(length(lppd) * var(lppd - pwaic)) return -2 * sum(lppd - pwaic), 2 * se end """ compute_waic(lppd::Array{T},pwaic::Array{T},data::AbstractHistogramData) where {T} TBW """ function compute_waic(lppd::Array{T}, pwaic::Array{T}, data::AbstractHistogramData) where {T} hist = datahistogram(data) se = sqrt(sum(hist) * var(lppd - pwaic, weights(hist), corrected=false)) return -2 * hist' * (lppd - pwaic), 2 * se end """ compute_waic(lppd::Array{T},pwaic::Array{T},data::AbstractTraceHistogramData) where {T} histogram data precedes trace data in vectors """ function compute_waic(lppd::Array{T}, pwaic::Array{T}, data::AbstractTraceHistogramData) where {T} hist = datahistogram(data) N = length(hist) elppd = lppd - pwaic vh = sum(hist) * var(elppd[1:N], weights(hist), corrected=false) vt = length(elppd[N+1:end]) * var(elppd[N+1:end]) se = sqrt(vh + vt) return -2 * hist' * (elppd[1:N]) - 2 * sum(elppd[N+1:end]), 2 * se end """ aic(fits::Fit) aic(nparams::Int,llml) -`llml`: negative of maximum loglikelihood returns AIC """ aic(fits::Fit) = 2 * length(fits.parml) + 2 * fits.llml aic(nparams::Int, llml) = 2 * nparams + 2 * llml """ initial_proposal(model) return parameters to be fitted and an initial proposal distribution """ function initial_proposal(model) param = get_param(model) d = proposal_dist(param, model.proposal, model) return param, d end """ proposal(d,cv) return rand(d) and proposal distribution for cv (vector or covariance) """ function proposal(d::Distribution, cv, model) param = rand(d) return param, proposal_dist(param, cv, model) end """ proposal_dist(param,cv) return proposal distribution specified by location and scale """ proposal_dist(param::Float64, cv::Float64, model) = Normal(param, proposal_scale(cv, model)) function proposal_dist(param::Vector, cv::Float64, model) d = Vector{Normal{Float64}}(undef, 0) for i in eachindex(param) push!(d, Normal(param[i], proposal_scale(cv, model))) end product_distribution(d) end function proposal_dist(param::Vector, cv::Vector, model) d = Vector{Normal{Float64}}(undef, 0) for i in eachindex(param) push!(d, Normal(param[i], proposal_scale(cv[i], model))) end product_distribution(d) end function proposal_dist(param::Vector, cov::Matrix, model) # c = (2.4)^2 / length(param) if isposdef(cov) return MvNormal(param, cov) else return MvNormal(param, sqrt.(abs.(diag(cov)))) end end """ proposal_scale(cv::Float64,model::AbstractGmodel) return variance of normal distribution of log(parameter) """ proposal_scale(cv::Float64, model::AbstractGmodel) = sqrt(log(1 + cv^2)) """ mhfactor(param,d,paramt,dt) Metropolis-Hastings correction factor for asymmetric proposal distribution """ mhfactor(param, d, paramt, dt) = logpdf(dt, param) - logpdf(d, paramt) #pdf(dt,param)/pdf(d,paramt) # Functions for parallel computing on multiple chains """ extract_chain(sdspawn) returns array of tuples of fetched futures from multiple chains """ function extract_chain(sdspawn) chain = Array{Tuple,1}(undef, length(sdspawn)) for i in eachindex(sdspawn) chain[i] = fetch(sdspawn[i]) end return chain end """ collate_fit(chain) returns array of Fit structures from multiple chains collate fits from multiple metropolis_hastings chains into and array of Fit structures """ function collate_fit(chain) fits = Array{Fit,1}(undef, length(chain)) for i in eachindex(chain) fits[i] = chain[i][1] end return fits end """ collate_waic(chain) return 2D array of collated waic from multiple chains """ function collate_waic(chain) waic = Array{Float64,2}(undef, length(chain), 3) for i in eachindex(chain) waic[i, 1] = chain[i][2][1] waic[i, 2] = chain[i][2][2] waic[i, 3] = chain[i][1].total end return waic # mean(waic,dims=1),median(waic,dims=1), mad(waic[:,1],normalize=false),waic end """ pooled_waic(chain) returns pooled waic and se from multiple chains """ function pooled_waic(chain) waic = collate_waic(chain) return pooled_mean(waic[:, 1], waic[:, 3]), pooled_std(waic[:, 2], waic[:, 3]) end """ merge_param(fits::Vector) returns pooled params from multiple chains """ function merge_param(fits::Vector) param = fits[1].param for i in 2:length(fits) param = [param fits[i].param] end return param end """ merge_ll(fits::Vector) returns pooled negative loglikelihood from multiple chains """ function merge_ll(fits::Vector) ll = fits[1].ll for i in 2:length(fits) ll = [ll; fits[i].ll] end return ll end """ merge_fit(chain::Array{Tuple,1}) merge_fit(fits::Array{Fit,1}) returns Fit structure merged from multiple runs """ merge_fit(chain::Array{Tuple,1}) = merge_fit(collate_fit(chain)) function merge_fit(fits::Array{Fit,1}) param = merge_param(fits) ll = merge_ll(fits) parml, llml = find_ml(fits) lppd = fits[1].lppd pwaic = fits[1].pwaic prior = fits[1].prior accept = fits[1].accept total = fits[1].total for i in 2:length(fits) accept += fits[i].accept total += fits[i].total prior += fits[i].prior lppd = logsumexp(lppd, fits[i].lppd) pwaic += fits[i].pwaic end Fit(param, ll, parml, llml, lppd .- log(length(fits)), pwaic / length(fits), prior / length(fits), accept, total) end """ compute_stats(fits::Fit) returns Stats structure Compute mean, std, median, mad, quantiles and correlations, covariances of parameters """ function compute_stats(paramin::Array{Float64,2}, model) param = inverse_transform_rates(paramin, model) meanparam = mean(param, dims=2) stdparam = std(param, dims=2) corparam = cor(param') covparam = cov(param') # covlogparam = cov(log.(param')) covlogparam = cov(paramin') medparam = median(param, dims=2) np = size(param, 1) madparam = Array{Float64,1}(undef, np) qparam = Matrix{Float64}(undef, 3, 0) for i in 1:np madparam[i] = mad(param[i, :], normalize=false) qparam = hcat(qparam, quantile(param[i, :], [0.025; 0.5; 0.975])) end Stats(meanparam, stdparam, medparam, madparam, qparam, corparam, covparam, covlogparam) end function compute_stats(paramin::Array{Float64,2}, model::GRSMhierarchicalmodel) param = inverse_transform_rates(paramin, model) meanparam = mean(param, dims=2) stdparam = std(param, dims=2) corparam = cor(param') covparam = cov(param') # covlogparam = cov(log.(param')) covlogparam = cov(paramin') medparam = median(param, dims=2) np = size(param, 1) madparam = Array{Float64,1}(undef, np) qparam = Matrix{Float64}(undef, 3, 0) for i in 1:np madparam[i] = mad(param[i, :], normalize=false) qparam = hcat(qparam, quantile(param[i, :], [0.025; 0.5; 0.975])) end Stats(meanparam, stdparam, medparam, madparam, qparam, corparam, covparam, covlogparam) end """ compute_rhat(chain::Array{Tuple,1}) compute_rhat(fits::Array{Fit,1}) compute_rhat(params::Vector{Array}) returns r-hat measure """ compute_rhat(chain::Array{Tuple,1}) = compute_rhat(collate_fit(chain)) function compute_rhat(fits::Vector{Fit}) M = length(fits) params = Vector{Array}(undef, M) for i in 1:M params[i] = fits[i].param end compute_rhat(params) end """ compute_rhat(params::Vector{Array}) """ function compute_rhat(params::Vector{Array}) N = chainlength(params) M = length(params) m = Matrix{Float64}(undef, size(params[1], 1), 2 * M) s = similar(m) for i in 1:M m[:, 2*i-1] = mean(params[i][:, 1:N], dims=2) m[:, 2*i] = mean(params[i][:, N+1:2*N], dims=2) s[:, 2*i-1] = var(params[i][:, 1:N], dims=2) s[:, 2*i] = var(params[i][:, N+1:2*N], dims=2) end B = N * var(m, dims=2) W = mean(s, dims=2) sqrt.((N - 1) / N .+ B ./ W / N) end """ chainlength(params) returns integer half of the minimum number of MCMC runs """ function chainlength(params) N = minimum(size.(params, 2)) div(N, 2) end """ find_ml(fits) returns the negative maximum likelihood out of all the chains """ function find_ml(fits::Array) llml = Array{Float64,1}(undef, length(fits)) for i in eachindex(fits) llml[i] = fits[i].llml end return fits[argmin(llml)].parml, llml[argmin(llml)] end """ crossentropy(logpredictions::Array{T},data::Array{T}) where {T} compute crosscentropy between data histogram and likelilhood """ function crossentropy(logpredictions::Array{T1}, hist::Array{T2}) where {T1,T2} lltot = hist' * logpredictions isfinite(lltot) ? -lltot : Inf end """ hist_entropy(hist) returns entropy of a normalized histogram """ function hist_entropy(hist::Array{Float64,1}) -hist' * log.(normalize_histogram(max.(hist, 0))) end function hist_entropy(hist::Array{Array,1}) l = 0 for h in hist l += hist_entropy(h) end return l end
StochasticGene
https://github.com/nih-niddk-mbs/StochasticGene.jl.git
[ "MIT" ]
1.2.5
fc1bcee6037ea393ce28426929eff65c76a86779
code
22012
# rna.jl # # Fit G state models (generalized telegraph models) to RNA abundance data # For single cell RNA (scRNA) technical noise is included as a yieldfactor # single molecule FISH (smFISH) is treated as loss less # """ fit_rna(nchains::Int,gene::String,cell::String,fittedparam::Vector,fixedeffects::Tuple,datacond,G::Int,maxtime::Float64,infolder::String,resultfolder::String,datafolder,fish::Bool,runcycle::Bool,inlabel,label,nsets::Int,cv=0.,transient::Bool=false,samplesteps::Int=100000,warmupsteps=20000,annealsteps=100000,temp=1.,tempanneal=100.,root = "/home/carsonc/scrna/",yieldprior = 0.05,ejectprior = 1.0) fit_rna(nchains::Int,data::AbstractRNAData,gene::String,cell::String,fittedparam::Vector,fixedeffects::Tuple,datacond,G::Int,maxtime::Float64,infolder::String,resultfolder::String,datafolder,fish::Bool,runcycle,inlabel,label,nsets,cv=0.,transient::Bool=false,samplesteps::Int=100000,warmupsteps=20000,annealsteps=100000,temp=1.,tempanneal=100.,root = "/home/carsonc/scrna/",yieldprior = 0.05,ejectprior = 1.0) Fit steady state or transient GM model to RNA data for a single gene, write the result (through function finalize), and return nothing. # Arguments - `nchains`: number of MCMC chains - `gene`: gene name - `cell`: cell type - `datacond`: condition, if more than one condition use vector of strings e.g. ["DMSO","AUXIN"] - `maxtime`: float maximum time for entire run - `infolder`: folder pointing to results used as initial conditions - `resultfolder`: folder where results go - `datafolder`: folder for data, string or array of strings - `inlabel`: name of input files (not including gene name but including condition) - `label`: = name of output files - `nsets`: int number of rate sets - `runcycle`: if true, cycle through all parameters sequentially in MCMC - `samplesteps`: int number of samples - `warmupsteps`: int number of warmup steps - `annealsteps`: in number of annealing steps - `temp`: MCMC temperature - `tempanneal`: starting temperature for annealing - `root`: root folder of data and Results folders - `fittedparam`: vector of rate indices, indices of parameters to be fit (input as string of ints separated by "-") - `fixedeffects`: (tuple of vectors of rate indices) string indicating which rate is fixed, e.g. "eject" - `data`: data structure """ function fit_rna(nchains::Int, gene::String, cell::String, fittedparam::Vector, fixedeffects::Tuple, transitions::Tuple, datacond, G::Int, maxtime::Float64, infolder::String, resultfolder::String, datafolder, fish::Bool, inlabel, label, nsets::Int, cv=0.0, transient::Bool=false, samplesteps::Int=100000, warmupsteps=0, annealsteps=0, temp=1.0, tempanneal=100.0, root=".", yieldprior::Float64=0.05, priorcv::Float64=10.0, decayrate=-1.0) gene = check_genename(gene, "[") datafolder = folder_path(datafolder, root, "data") if occursin("-", datafolder) datafolder = string.(split(datafolder, "-")) end if occursin("-", datacond) datacond = string.(split(datacond, "-")) end if transient data = data_rna(gene, datacond, datafolder, fish, label, ["T0", "T30", "T120"], [0.0, 30.0, 120.0]) else data = data_rna(gene, datacond, datafolder, fish, label) end fit_rna(nchains, data, gene, cell, fittedparam, fixedeffects, transitions, datacond, G, maxtime, infolder, resultfolder, datafolder, fish, inlabel, label, nsets, cv, transient, samplesteps, warmupsteps, annealsteps, temp, tempanneal, root, yieldprior, priorcv, decayrate) end function fit_rna(nchains::Int, data::AbstractRNAData, gene::String, cell::String, fittedparam::Vector, fixedeffects::Tuple, transitions::Tuple, datacond, G::Int, maxtime::Float64, infolder::String, resultfolder::String, datafolder, fish::Bool, inlabel, label, nsets, cv=0.0, transient::Bool=false, samplesteps::Int=100000, warmupsteps=0, annealsteps=0, temp=1.0, tempanneal=100.0, root=".", yieldprior::Float64=0.05, priorcv::Float64=10.0, decayrate=-1.0) println(now()) printinfo(gene, G, datacond, datafolder, infolder, resultfolder, maxtime) println("size of histogram: ", data.nRNA) resultfolder = joinpath("results", resultfolder) infolder = joinpath("results", infolder) if fish yieldprior = 1.0 end model = model_rna(data, gene, cell, G, cv, fittedparam, fixedeffects, transitions, inlabel, infolder, nsets, root, yieldprior, decayrate, Normal, priorcv, true) options = MHOptions(samplesteps, warmupsteps, annealsteps, maxtime, temp, tempanneal) print_ll(data, model) fits, stats, measures = run_mh(data, model, options, nchains) optimized = 0 try optimized = Optim.optimize(x -> lossfn(x, data, model), fits.parml, LBFGS()) catch @warn "Optimizer failed" end finalize(data, model, fits, stats, measures, temp, resultfolder, optimized, burstsize(fits, model), root) println(now()) get_rates(stats.medparam, model, false) end #Prepare data structures """ data_rna(gene::String,cond::String,datafolder,fish,label) data_rna(gene::String,cond::String,datafolder::String,fish::Bool,label,sets::Vector,time::Vector) data_rna(path,time,gene,time) data_rna(path,time,gene) Load data structure """ function data_rna(gene::String, cond::String, datafolder::String, fish::Bool, label) if cond == "null" cond = "" end datafile = fish ? FISHpath(gene, cond, datafolder) : scRNApath(gene, cond, datafolder) data_rna(datafile, label, gene, fish) end function data_rna(gene::String, cond::Array, datafolder::String, fish::Bool, label) datafile = Array{String,1}(undef, length(cond)) for i in eachindex(cond) datafile[i] = fish ? FISHpath(gene, cond[i], datafolder) : scRNApath(gene, cond[i], datafolder) end data_rna(datafile, label, gene, fish) end function data_rna(gene::String, cond::Array, datafolder::Array, fish::Bool, label) datafile = Array{String,1}(undef, length(cond)) for i in eachindex(cond) datafile[i] = fish ? FISHpath(gene, cond[i], datafolder) : scRNApath(gene, cond[i], datafolder) end println(datafile) data_rna(datafile, label, gene, fish) end function data_rna(gene::String, cond::String, datafolder::String, fish::Bool, label, sets::Vector, time::Vector) if cond == "null" cond = "" end datafile = [] for set in sets folder = joinpath(datafolder, set) path = fish ? FISHpath(gene, cond, datafolder) : scRNApath(gene, cond, datafolder) datafile = vcat(datafile, path) end data_rna(datafile, label, times, gene, false) end function data_rna(path, label, gene::String, fish::Bool) len, h = histograms_rna(path, gene, fish) RNAData(label, gene, len, h) end """ histograms_rna(path,gene) prepare mRNA histograms for gene given data folder path """ function histograms_rna(path::Array, gene::String, fish::Bool) n = length(path) h = Array{Array,1}(undef, n) lengths = Array{Int,1}(undef, n) for i in eachindex(path) lengths[i], h[i] = histograms_rna(path[i], gene, fish) end return lengths, h end function histograms_rna(path::String, gene::String, fish::Bool) if fish h = read_fish(path, gene, 0.98) else h = read_scrna(path, 0.99) if length(h) == 0 throw("data not found") end end return length(h), h end function histograms_rna(path::Array, gene::String, fish::Array{Bool,1}) n = length(path) h = Array{Array,1}(undef, n) lengths = Array{Int,1}(undef, n) for i in eachindex(path) lengths[i], h[i] = histograms_rna(path[i], gene, fish[i]) end return lengths, h end # # Prepare model structures # """ # model_rna(gene,cell,G,fish,fittedparam,fixedeffects,inlabel,infolder,nsets,root,data,verbose=true) # model_rna(r::Vector,d::Vector,G::Int,nalleles::Int,propcv,fittedparam,fixedeffects,fish::Bool,method=0) # model_rna(r,G,nalleles,nsets,propcv,fittedparam,decayprior,yieldprior,method) # model_rna(r,G,nalleles,nsets,propcv,fittedparam,decayprior,method) # model_rna(r,G,nalleles,nsets,propcv,fittedparam,decayprior,noisepriors,method) # make model structure # """ # function model_rna(data, gene::String, cell::String, G::Int, cv, fittedparam, fixedeffects, transitions, inlabel, infolder, nsets, root, yieldprior, decayrate::Float64, fprior=Normal, priorcv=10.0, onstates=[G], verbose=true) # if decayrate < 0 # decayrate = get_decay(gene, cell, root) # end # nalleles = alleles(gene, cell, root) # if verbose # println("alleles: ", nalleles) # if decayrate < 0 # throw("decayrate < 0") # else # println("decay rate: ", decayrate) # end # end # if cv <= 0 # cv = getcv(gene, G, nalleles, fittedparam, inlabel, infolder, root, verbose) # end # if G == 1 # ejectrate = mean_histogram(data.histRNA) * decayrate / nalleles * yieldprior # else # ejectrate = yieldprior # end # r = getr(gene, G, nalleles, decayrate, ejectrate, inlabel, infolder, nsets, root, verbose) # model = model_rna(data.nRNA, r, G, nalleles, nsets, cv, fittedparam, fixedeffects, transitions, decayrate, ejectrate, fprior, priorcv, onstates) # return model # end # function model_rna(nRNA::Int, r::Vector, G::Int, nalleles::Int, nsets::Int, propcv, fittedparam, fixedeffects, transitions, decayprior, ejectprior, f=Normal, cv=10.0, onstates=[G]) # d = prior_rna(r, G, nsets, fittedparam, decayprior, ejectprior, f, cv) # model_rna(nRNA, r::Vector, d, G::Int, nalleles, propcv, fittedparam, fixedeffects, transitions, onstates) # end # function model_rna(nRNA::Int, r::Vector, d, G::Int, nalleles, propcv, fittedparam, fixedeffects, transitions, method=0, onstates=[G]) # # components = make_components_M(transitions,G,data.nRNA+2,r[end]) # components = make_components_M(transitions, G, 0, nRNA + 2, r[end], "") # if length(fixedeffects) > 0 # model = GMfixedeffectsmodel{typeof(r),typeof(d),typeof(propcv),typeof(fittedparam),typeof(method),typeof(components)}(G, nalleles, r, d, propcv, fittedparam, fixedeffects, method, transitions, components, onstates) # else # model = GMmodel{typeof(r),typeof(d),typeof(propcv),typeof(fittedparam),typeof(method),typeof(components)}(G, nalleles, r, d, propcv, fittedparam, method, transitions, components, onstates) # end # return model # end # function model_delay_rna(r::Vector, G::Int, nalleles::Int, nsets::Int, propcv, fittedparam::Array, decayprior, ejectprior, delayprior) # # propcv = proposal_cv_rna(propcv,fittedparam) # d = prior_rna(r, G, nsets, fittedparam, decayprior, ejectprior, delayprior) # GMdelaymodel{typeof(r),typeof(d),typeof(propcv),typeof(fittedparam),Int64}(G, nalleles, r, d, propcv, fittedparam, 1) # end # """ # transient_rna(nchains,gene::String,fittedparam,cond::Vector,G::Int,maxtime::Float64,infolder::String,resultfolder,datafolder,inlabel,label,nsets,runcycle::Bool=false,samplesteps::Int=40000,warmupsteps=20000,annealsteps=100000,temp=1.,tempanneal=100.,root = "/home/carsonc/scrna/") # make structures for transient model fit # """ # function transient_rna(nchains, gene::String, cell, fittedparam, cond::Vector, G::Int, maxtime::Float64, infolder::String, resultfolder, datafolder, inlabel, label, nsets, runcycle::Bool=false, samplesteps::Int=40000, warmupsteps=20000, annealsteps=100000, temp=1.0, tempanneal=100.0, root="/home/carsonc/scrna/") # data = make_data(gene, cond, G, datafolder, label, nsets, root) # model = make_model(gene, cell, G, fittedparam, inlabel, infolder, nsets, root, data) # param, _ = initial_proposal(model) # return param, data, model # end """ prior_rna(r::Vector,G::Int,nsets::Int,propcv,fittedparam::Array,decayprior,yieldprior) prior_rna(r::Vector,G::Int,nsets::Int,fittedparam::Array,decayprior::Float64,noisepriors::Array) prepare prior distribution r[mod(1:2*G,nsets)] = rates for each model set (i.e. rates for each set are stacked) r[2*G*nsets + 1] == yield factor (i.e remaining after loss due to technical noise) prior for multithresholded smFISH data r[1:2G] = model rates r[2G+1] = additive noise mean r[2G + 1 + 1:length(noisepriors)] = remaining fraction after thresholding (i.e. yield) """ function prior_rna(r::Vector, G::Int, nsets::Int, fittedparam::Array, decayprior::Float64, ejectprior::Float64, f=Normal, cv::Float64=10.0) if length(r) == 2 * G * nsets rm, rcv = setrate(G, nsets, decayprior, ejectprior, cv) return distribution_array(log.(rm[fittedparam]), sigmalognormal(rcv[fittedparam]), f) else throw("rates have wrong length") end end function prior_rna(r::Vector, G::Int, nsets::Int, fittedparam::Array, decayprior::Float64, ejectprior::Float64, noisepriors::Array, f=Normal, cv::Float64=10.0) if length(r) == 2 * G * nsets + length(noisepriors) rm, rcv = setrate(G, nsets, decayprior, ejectprior, noisepriors, cv) return distribution_array(log.(rm[fittedparam]), rcv[fittedparam], f) else throw("rates have wrong length") end end """ setrate(G::Int,nsets::Int,decayrate::Float64,ejectrate::Float64,cv::Float64 = 10.) setrate(G::Int,nsets::Int,decayrate::Float64,ejectrate::Float64,noisepriors::Array,cv::Float64 = 10.) Set mean and cv of rates """ function setr(G, nsets, decayrate, ejectrate) r = setrate(G, nsets, decayrate, ejectrate)[1] println("init rates: ", r) return r end function setrate(G::Int, nsets::Int, decayrate::Float64, ejectrate::Float64, cv::Float64=10.0) rm = Vector{Float64}(undef, 0) rc = similar(rm) for i in 1:nsets rm = vcat(rm, [repeat([0.01; 0.1], (G - 1)); ejectrate; decayrate]) rc = vcat(rc, [cv * ones(2 * (G - 1)); cv; 0.01]) end return rm, rc end function setrate(G::Int, nsets::Int, decayrate::Float64, ejectrate::Float64, noisepriors::Array, cv::Float64=10.0) rm, rc = setrate(G, nsets, decayrate, ejectrate, cv) for nm in noisepriors rm = vcat(rm, nm) rc = vcat(rc, 0.25) end return rm, rc end """ proposal_cv_rna(cv) proposal_cv_rna(propcv,fittedparam) set proposal cv to a vector or matrix """ proposal_cv_rna(cv) = typeof(cv) == Float64 ? propcv * ones(length(fittedparam)) : propcv proposal_cv_rna(propcv, fittedparam) = typeof(propcv) == Float64 ? propcv * ones(length(fittedparam)) : propcv """ fittedparam_rna(G,nsets,loss) fittedparam_rna(G,nsets) select all parameters to be fitted except decay rates yieldfactor is last parameter in loss models """ function fittedparam_rna(G, nsets, loss) fp = fittedparam_rna(G, nsets) if loss == 1 return vcat(fp, nsets * 2 * G + 1) else return fp end end function fittedparam_rna(G, nsets) nrates = 2 * G # total number of rates in GM model k = nrates - 1 # adjust all rate parameters except decay time fp = Array{Int,1}(undef, nsets * k) for j in 0:nsets-1 for i in 1:k fp[k*j+i] = nrates * j + i end end return fp end """ rescale_rate_rna(r,G,decayrate::Float64) set new decay rate and rescale transition rates such that steady state distribution is the same """ function rescale_rate_rna(r, G, decayrate::Float64) rnew = copy(r) if mod(length(r), 2 * G) == 0 rnew *= decayrate / r[2*G] else stride = fld(length(r), fld(length(r), 2 * G)) for i in 0:stride:length(r)-1 rnew[i+1:i+2*G] *= decayrate / r[2*G] end end return rnew end # # Read in data and construct histograms # """ # read_scrna(filename::String,yield::Float64=.99,nhistmax::Int=1000) # Construct mRNA count per cell histogram array of a gene # """ # function read_scrna(filename::String, threshold::Float64=0.99, nhistmax::Int=500) # if isfile(filename) && filesize(filename) > 0 # x = readdlm(filename)[:, 1] # x = truncate_histogram(x, threshold, nhistmax) # if x == 0 # dataFISH = Array{Int,1}(undef, 0) # else # dataFISH = x # end # return dataFISH # else # # println("data file not found") # return Array{Int,1}(undef, 0) # end # end # """ # read_fish(path,gene,threshold) # Read in FISH data from 7timepoint type folders # """ # function read_fish(path::String, cond::String, threshold::Float64=0.98, maxlength=1800) # xr = zeros(maxlength) # lx = 0 # for (root, dirs, files) in walkdir(path) # for file in files # target = joinpath(root, file) # if occursin(cond, target) && occursin("cellular", target) # # println(target) # x1 = readdlm(target)[:, 1] # x1 = truncate_histogram(x1, threshold, maxlength) # lx = length(x1) # # println(lx) # xr[1:min(lx, maxlength)] += x1[1:min(lx, maxlength)] # end # end # end # return truncate_histogram(xr, 1.0, maxlength) # end function read_fish(path1::String, cond1::String, path2::String, cond2::String, threshold::Float64=0.98) x1 = read_fish(path1, cond1, threshold) x2 = read_fish(path2, cond2, threshold) combine_histogram(x1, x2) end # function to create a FISH directory """ new_FISH(newroot::String, oldroot::String, rep::String) TBW """ function new_FISH(newroot::String, oldroot::String, rep::String) for (root, dirs, files) in walkdir(oldroot) for dir in dirs if occursin(rep, dir) oldtarget = joinpath(root, dir) newtarget = replace(oldtarget, oldroot => newroot) println(newtarget) if !ispath(newtarget) mkpath(newtarget) end cp(oldtarget, newtarget, force=true) end end end end # functions to build paths to RNA/FISH data and results # """ # scRNApath(gene::String,cond::String,datapath::String,root::String) # generate path to scRNA data for given gene and condition cond # data files must have format genename_cond.txt # """ # function scRNApath(gene::String, cond::String, datapath::String, root::String) # datapath = joinpath(root, datapath) # if cond == "" # joinpath(datapath, gene * ".txt") # else # joinpath(datapath, gene * "_" * cond * ".txt") # end # end # scRNApath(gene, cond, datapath) = joinpath(datapath, gene * "_" * cond * ".txt") # """ # FISHpath(gene,cond,datapath,root) # generate path to FISH data # """ # # FISHpath(gene,cond,datapath,root) = joinpath(joinpath(joinpath(root,datapath),gene),cond) # FISHpath(gene, cond, datapath, root) = joinpath(root, datapath, gene, cond) # FISHpath(gene, cond, datapath) = joinpath(datapath, gene, cond) # """ # ratepath_Gmodel(gene::String,cond::String,G::Int,nalleles::Int,label,folder,root) # """ # function ratepath_Gmodel(gene::String, cond::String, G::Int, nalleles::Int, label, folder, root) # path_Gmodel("rates", gene, G, nalleles, label * "-" * cond, folder, root) # end # """ # path_Gmodel(type,gene::String,G::Int,nalleles::Int,label::String,folder,root) # """ # function path_Gmodel(type, gene::String, G::Int, nalleles::Int, label::String, folder, root) # filelabel = label * "_" * gene * "_" * "$G" * "_" * "$nalleles" * ".txt" # ratefile = type * "_" * filelabel # joinpath(root, folder, ratefile) # end """ stats_rna(genes::Vector,conds,datapath,threshold=.99) """ function stats_rna(genes::Vector, conds, datapath, threshold=0.99) g = Vector{String}(undef, 0) z = Vector{Float64}(undef, 0) h1 = Vector{Float64}(undef, 0) h2 = Vector{Float64}(undef, 0) for gene in genes t, m1, m2 = expression_rna(gene, conds, datapath, threshold) push!(g, gene) push!(z, t) push!(h1, m2) push!(h2, m1) end return g, z, h1, h2 end """ expression_rna(gene,conds::Vector,folder::String,threshold=.99) """ function expression_rna(gene, conds::Vector, folder::String, threshold=0.99) h = Vector{Vector}(undef, 2) for i in eachindex(conds) datapath = scRNApath(gene, conds[i], folder) h[i] = read_scrna(datapath, threshold) end if length(h[1]) > 0 && length(h[2]) > 0 return log_2sample(h[1], h[2]), mean_histogram(h[1]), mean_histogram(h[2]) else return 0, 0, 0 end end """ expression_rna(gene,conds::Vector,folder::Vector,threshold=.99) """ function expression_rna(gene, conds::Vector, folder::Vector, threshold=0.99) h = Vector{Vector}(undef, 2) for i in eachindex(conds) datapath = scRNApath(gene, conds[i], folder[i]) h[i] = read_scrna(datapath, threshold) end if length(h[1]) > 0 && length(h[2]) > 0 return log_2sample(h[1], h[2]), mean_histogram(h[1]), mean_histogram(h[2]) else return 0, 0, 0 end end """ expression_rna(genes::Vector,cond::String,folder,threshold=.99) """ function expression_rna(genes::Vector, cond::String, folder, threshold=0.99) h1 = Array{Any,2}(undef, 0, 2) for gene in genes datapath = scRNApath(gene, cond, folder) h = read_scrna(datapath, threshold) if length(h) > 0 h1 = vcat(h1, [gene mean_histogram(h)]) end end return h1 end """ rna_fish(gene,cond,fishfolder,rnafolder,yield,root) output RNA histogram and downsampled FISH histogram with loss """ function rna_fish(gene, cond, fishfolder, rnafolder, yield) datarna = histograms_rna(scRNApath(gene, cond, rnafolder), gene, false) f = reduce_fish(gene, cond, datarna[1], fishfolder, yield) return datarna[2], f end """ reduce_fish(gene,cond,nhist,fishfolder,yield,root) sample fish histogram with loss (1-yield) """ function reduce_fish(gene, cond, nhist, fishfolder, yield) fish = histograms_rna(FISHpath(gene, cond, fishfolder), gene, true) technical_loss(fish[2], yield, nhist) fish[2] end
StochasticGene
https://github.com/nih-niddk-mbs/StochasticGene.jl.git
[ "MIT" ]
1.2.5
fc1bcee6037ea393ce28426929eff65c76a86779
code
23783
# This file is part of StochasticGene.jl # simulator.jl # Functions to simulate Markov gene transcription models # Uses hybrid first and next reaction method """ Reaction structure for reaction type action: type of reaction index: rate index for reaction disabled: reactions that are disabled by current reaction enabled: reactions that are enabled by current reaction initial: initial GR state final: final GR state """ struct Reaction action::Int index::Int disabled::Vector{Int64} enabled::Vector{Int64} initial::Int final::Int end """ ReactionIndices structure for rate indices of reaction types """ struct ReactionIndices grange::UnitRange{Int64} irange::UnitRange{Int64} rrange::UnitRange{Int64} erange::UnitRange{Int64} srange::UnitRange{Int64} decay::Int end """ set_actions() create dictionary for all the possible transitions """ set_actions() = Dict("activateG!" => 1, "deactivateG!" => 2, "transitionG!" => 3, "initiate!" => 4, "transitionR!" => 5, "eject!" => 6, "splice!" => 7, "decay!" => 8) # invert_dict(D) = Dict(D[k] => k for k in keys(D)) put into utilities """ simulator(r::Vector{Float64}, transitions::Tuple, G::Int, R::Int, S::Int, insertstep::Int; nalleles::Int=1, nhist::Int=20, onstates::Vector=Int[], bins::Vector=Float64[], traceinterval::Float64=0.0, probfn=prob_GaussianMixture, noiseparams::Int=5, totalsteps::Int=1000000000, totaltime::Float64=0.0, tol::Float64=1e-6, reporterfn=sum, splicetype="", verbose::Bool=false) Simulate any GRSM model. Returns steady state mRNA histogram. If bins not a null vector will return a vector of the mRNA histogram and ON and OFF time histograms. If traceinterval > 0, it will return a vector containing the mRNA histogram and the traces #Arguments - `r`: vector of rates - `transitions`: tuple of vectors that specify state transitions for G states, e.g. ([1,2],[2,1]) for classic 2 state telegraph model and ([1,2],[2,1],[2,3],[3,1]) for 3 state kinetic proof reading model - `G`: number of gene states - `R`: number of pre-RNA steps (set to 0 for classic telegraph models) - `S`: number of splice sites (set to 0 for G (classic telegraph) and GR models and R for GRS models) - `insertstep`: reporter insertion step #Named arguments - `nalleles`: Number of alleles - `nhist::Int`: Size of mRNA histogram - `onstates::Vector`: a vector of ON states (use empty set for any R step is ON) or vector of vector of ON states - `bins::Vector=Float64[]`: vector of time bins for ON and OFF histograms or vector of vectors of time bins - `probfn`=prob_GaussianMixture: reporter distribution - `traceinterval`: Interval in minutes between frames for intensity traces. If 0, traces are not made. - `totalsteps`::Int=10000000: maximum number of simulation steps (not usred when simulating traces) - `tol`::Float64=1e-6: convergence error tolerance for mRNA histogram (not used when simulating traces are made) - `totaltime`::Float64=0.0: total time of simulation - `splicetype`::String: splice action - `reporterfn`=sum: how individual reporters are combined - `verbose::Bool=false`: flag for printing state information #Example: julia> h=simulator(r,transitions,3,2,2,1,nhist=150,bins=[collect(5/3:5/3:200),collect(.1:.1:20)],onstates=[Int[],[2,3]],nalleles=2) """ function simulator(r::Vector{Float64}, transitions::Tuple, G::Int, R::Int, S::Int, insertstep::Int; nalleles::Int=1, nhist::Int=20, onstates::Vector=Int[], bins::Vector=Float64[], traceinterval::Float64=0.0, probfn=prob_Gaussian, noiseparams::Int=4, totalsteps::Int=1000000000, totaltime::Float64=0.0, tol::Float64=1e-6, reporterfn=sum, splicetype="", verbose::Bool=false) if length(r) < num_rates(transitions, R, S, insertstep) + noiseparams * (traceinterval > 0) throw("r has too few elements") end if insertstep > R > 0 throw("insertstep>R") end if S > 0 S = R - insertstep + 1 end mhist, mhist0, m, steps, t, ts, t0, tsample, err = initialize_sim(r, nhist, tol) reactions = set_reactions(transitions, G, R, S, insertstep) tau, state = initialize(r, G, R, length(reactions), nalleles) if length(bins) < 1 onoff = false else onoff = true if ~(eltype(onstates) <: Vector) bins = [bins] onstates = [onstates] end nn = length(onstates) tIA = Vector{Float64}[] tAI = Vector{Float64}[] before = Vector{Int}(undef, nn) after = Vector{Int}(undef, nn) ndt = Int[] dt = Float64[] histofftdd = Vector{Int}[] histontdd = Vector{Int}[] for i in eachindex(onstates) push!(ndt, length(bins[i])) push!(dt, bins[i][2] - bins[i][1]) push!(histofftdd, zeros(Int, ndt[i])) push!(histontdd, zeros(Int, ndt[i])) push!(tIA, zeros(nalleles)) push!(tAI, zeros(nalleles)) end end if traceinterval > 0 par = r[end-noiseparams+1:end] tracelog = [(t, state[:, 1])] end if verbose invactions = invert_dict(set_actions()) end if totaltime > 0.0 err = 0.0 totalsteps = 0 end while (err > tol && steps < totalsteps) || t < totaltime steps += 1 t, rindex = findmin(tau) # reaction index and allele for least time transition index = rindex[1] allele = rindex[2] initial, final, disabled, enabled, action = set_arguments(reactions[index]) dth = t - t0 t0 = t update_mhist!(mhist, m, dth, nhist) if t - ts > tsample && traceinterval == 0 err, mhist0 = update_error(mhist, mhist0) ts = t end if onoff # find before and after states for the same allele to define dwell time histograms for i in eachindex(onstates) before[i] = isempty(onstates[i]) ? num_reporters(state, allele, G, R, insertstep) : Int(gstate(G, state, allele) ∈ onstates[i]) end end if verbose println("---") println("m:", m) println(state) onoff && println("before", before) println(tau) println("t:", t) println(rindex) println(invactions[action], " ", allele) println(initial, "->", final) end m = update!(tau, state, index, t, m, r, allele, G, R, S, disabled, enabled, initial, final, action, insertstep) if onoff for i in eachindex(onstates) after[i] = isempty(onstates[i]) ? num_reporters(state, allele, G, R, insertstep) : Int(gstate(G, state, allele) ∈ onstates[i]) firstpassagetime!(histofftdd[i], histontdd[i], tAI[i], tIA[i], t, dt[i], ndt[i], allele, before[i], after[i], verbose) end verbose && println(tAI) verbose && println(tIA) end if traceinterval > 0 push!(tracelog, (t, state[:, 1])) end end # while verbose && println(steps) # counts = max(sum(mhist), 1) # mhist /= counts if onoff dwelltimes = Vector[] push!(dwelltimes, mhist[1:nhist]) for i in eachindex(histontdd) push!(dwelltimes, histontdd[i]) push!(dwelltimes, histofftdd[i]) end return dwelltimes elseif traceinterval > 0.0 return [mhist[1:nhist], make_trace(tracelog, G, R, S, onstates, traceinterval, par, insertstep, probfn, reporterfn), tracelog] elseif onoff && traceinterval > 0 return [mhist[1:nhist], histontdd, histofftdd, make_trace(tracelog, G, R, S, onstates, traceinterval, par, insertstep, probfn, reporterfn)] else return mhist[1:nhist] end end """ simulate_trace_data(datafolder::String;ntrials::Int=10,r=[0.038, 1.0, 0.23, 0.02, 0.25, 0.17, 0.02, 0.06, 0.02, 0.000231,30,20,200,100,.8], transitions=([1, 2], [2, 1], [2, 3], [3, 1]), G=3, R=2, S=2, insertstep=1,onstates=Int[], interval=1.0, totaltime=1000.) create simulated trace files in datafolder """ function simulate_trace_data(datafolder::String; ntrials::Int=10, r=[0.038, 1.0, 0.23, 0.02, 0.25, 0.17, 0.02, 0.06, 0.02, 0.000231, 30, 20, 200, 100, 0.8], transitions=([1, 2], [2, 1], [2, 3], [3, 1]), G=3, R=2, S=2, insertstep=1, onstates=Int[], interval=1.0, totaltime=1000.0) ~ispath(datafolder) && mkpath(datafolder) for i in 1:ntrials trace = simulator(r, transitions, G, R, S, insertstep, onstates=onstates, traceinterval=interval, totaltime=totaltime)[2][1:end-1, 2] l = length(trace) datapath = joinpath(datafolder, "testtrace$i.trk") writedlm(datapath, [zeros(l) zeros(l) trace collect(1:l)]) end end function simulate_trace_vector(r, transitions, G, R, S, interval, totaltime, ntrials; insertstep=1, onstates=Int[], reporterfn=sum) trace = Array{Array{Float64}}(undef, ntrials) for i in eachindex(trace) trace[i] = simulator(r, transitions, G, R, S, insertstep, onstates=onstates, traceinterval=interval, totaltime=totaltime)[2][1:end-1, 2] end trace end """ simulate_trace(r,transitions,G,R,interval,totaltime,onstates=[G]) simulate a trace """ simulate_trace(r, transitions, G, R, S, insertstep, interval, onstates; totaltime=1000.0, reporterfn=sum) = simulator(r, transitions, G, R, S, insertstep, nalleles=1, nhist=2, onstates=onstates, traceinterval=interval, reporterfn=reporterfn, totaltime=totaltime)[2][1:end-1, :] """ initialize(r, G, R, nreactions, nalleles, initstate=1, initreaction=1) return initial proposed next reaction times and states """ function initialize(r, G, R, nreactions, nalleles, initstate=1, initreaction=1) tau = fill(Inf, nreactions, nalleles) states = zeros(Int, G + R, nalleles) for n in 1:nalleles tau[initreaction, n] = -log(rand()) / r[1] states[initstate, n] = 1 end return tau, states end """ initialize_sim(r, nhist, tol, samplefactor=20.0, errfactor=10.0) """ initialize_sim(r, nhist, tol, samplefactor=20.0, errfactor=10.0) = zeros(nhist + 1), ones(nhist + 1), 0, 0, 0.0, 0.0, 0.0, samplefactor / minimum(r), errfactor * tol """ update_error(mhist, mhist0) TBW """ update_error(mhist, mhist0) = (norm(mhist / sum(mhist) - mhist0 / sum(mhist0), Inf), copy(mhist)) """ update_mhist!(mhist,m,dt,nhist) """ function update_mhist!(mhist, m, dt, nhist) if m + 1 <= nhist mhist[m+1] += dt else mhist[nhist+1] += dt end end """ make_trace(tracelog, G, R, S, onstates, interval, par, insertstep,reporterfn=sum) Return array of frame times and intensities - `tracelog`: Vector if Tuples of (time,state of allele 1) - `interval`: Number of minutes between frames - `onstates`: Vector of G on states, empty for GRS models - `G` and `R` as defined in simulator """ function make_trace(tracelog, G, R, S, onstates::Vector{Int}, interval, par, insertstep, probfn, reporterfn=sum) n = length(tracelog) trace = Matrix(undef, 0, 4) state = tracelog[1][2] frame = interval if isempty(onstates) reporters = num_reporters_per_state(G, R, S, insertstep, reporterfn) else reporters = num_reporters_per_state(G, onstates) end i = 2 base = S > 0 ? 3 : 2 d = probfn(par, reporters, G * base^R) while i < n while tracelog[i][1] <= frame && i < n state = tracelog[i][2] i += 1 end trace = vcat(trace, [frame intensity(state, G, R, S, d) reporters[state_index(state, G, R, S)] state_index(state, G, R, S)]) frame += interval end return trace end """ make_trace(tracelog, G, R, S, onstates::Vector{Vector}, interval, par, insertstep, probfn, reporterfn=sum) """ function make_trace(tracelog, G, R, S, onstates::Vector{Vector}, interval, par, insertstep, probfn, reporterfn=sum) traces = Vector[] for o in onstates push!(traces, make_trace(tracelog, G, R, S, o, interval, par, insertstep, probfn, reporterfn)) end traces end """ intensity(state,onstates,G,R) Returns the trace intensity given the state of a system For R = 0, the intensity is occupancy of any onstates For R > 0, intensity is the number of reporters in the nascent mRNA """ function intensity(state, G, R, S, d) stateindex = state_index(state, G, R, S) max(rand(d[stateindex]), 0) end gstate(G, state, allele) = argmax(state[1:G, allele]) """ state_index(state::Array,G,allele) state_index(state::Array, G, R, S,allele=1) returns state index given state vector """ state_index(state::Array, G, allele) = argmax(state[1:G, allele]) function state_index(state::Array, G, R, S, allele=1) Gstate = gstate(G, state, allele) if R == 0 return Gstate else if S > 0 base = 3 Rstate = state[G+1:end, allele] else base = 2 Rstate = Int.(state[G+1:end, allele] .> 0) end return Gstate + G * decimal(Rstate, base) end end """ num_reporters(state::Matrix, allele, G, R, insertstep=1) return number of states with R steps > 1 """ function num_reporters(state::Matrix, allele, G, R, insertstep) reporters = 0 for i in G+insertstep:G+R reporters = reporters + Int(state[i, allele] > 1) end reporters end """ firstpassagetime!(histofftdd,histontdd, tAI, tIA, t, dt, ndt, allele,insertstep,before,after) decide if transition exits or enters sojourn states then in place update appropriate histogram """ function firstpassagetime!(histofftdd, histontdd, tAI, tIA, t, dt, ndt, allele, before, after, verbose) if before == 1 && after == 0 # turn off firstpassagetime!(histontdd, tAI, tIA, t, dt, ndt, allele) if verbose println("off:", allele) end elseif before == 0 && after == 1 # turn on firstpassagetime!(histofftdd, tIA, tAI, t, dt, ndt, allele) if verbose println("on:", allele) end end end """ firstpassagetime!(hist, t1, t2, t, dt, ndt, allele) in place update of first passage time histograms """ function firstpassagetime!(hist, t1, t2, t, dt, ndt, allele) t1[allele] = t t12 = (t - t2[allele]) / dt if t12 <= ndt && t12 > 0 && t2[allele] > 0 hist[ceil(Int, t12)] += 1 end end """ set_arguments(reaction) return values of fields of Reaction structure """ set_arguments(reaction) = (reaction.initial, reaction.final, reaction.disabled, reaction.enabled, reaction.action) """ set_reactionindices(Gtransitions, R, S, insertstep) return structure of ranges for each type of transition """ function set_reactionindices(Gtransitions, R, S, insertstep) if S > 0 S = R - insertstep + 1 end nG = length(Gtransitions) g = 1:nG i = nG + 1 : nG + Int(R > 0) r = nG + 2 : nG + R e = nG + R + 1 : nG + R + 1 s = nG + 1 + R + 1 : nG + 1 + R + S d = nG + 1 + R + S + 1 ReactionIndices(g, i, r, e, s, d) end """ set_reactions(Gtransitions, G, R, S, insertstep) return vector of Reaction structures for each transition in GRS model reporter first appears at insertstep """ function set_reactions(Gtransitions, G, R, S, insertstep) actions = set_actions() indices = set_reactionindices(Gtransitions, R, S, insertstep) reactions = Reaction[] nG = length(Gtransitions) Sstride = R - insertstep + 1 for g in eachindex(Gtransitions) u = Int[] d = Int[] ginitial = Gtransitions[g][1] gfinal = Gtransitions[g][2] for s in eachindex(Gtransitions) # if ginitial == Gtransitions[s][1] && gfinal != Gtransitions[s][2] if ginitial == Gtransitions[s][1] push!(u, s) end if gfinal == Gtransitions[s][1] push!(d, s) end end if gfinal == G push!(d, nG + 1) push!(reactions, Reaction(actions["activateG!"], g, u, d, ginitial, gfinal)) elseif ginitial == G push!(u, nG + 1) push!(reactions, Reaction(actions["deactivateG!"], g, u, d, ginitial, gfinal)) else push!(reactions, Reaction(actions["transitionG!"], g, u, d, ginitial, gfinal)) end end for i in indices.irange if S > 0 && insertstep == 1 push!(reactions, Reaction(actions["initiate!"], i, [], [nG + 2; nG + 2 + S], G, G + 1)) else push!(reactions, Reaction(actions["initiate!"], i, [], [nG + 2], G, G + 1)) end end i = G for r in indices.rrange i += 1 if S == 0 push!(reactions, Reaction(actions["transitionR!"], r, Int[r], [r - 1; r + 1], i, i + 1)) end if S > 0 && insertstep == 1 push!(reactions, Reaction(actions["transitionR!"], r, Int[r; r + Sstride], [r - 1; r + 1; r + 1 + Sstride], i, i + 1)) end if S > 0 && insertstep > 1 && i > G + insertstep - 1 push!(reactions, Reaction(actions["transitionR!"], r, Int[r; r + Sstride], [r - 1; r + 1; r + 1 + Sstride], i, i + 1)) end if S > 0 && insertstep > 1 && i == G + insertstep - 1 push!(reactions, Reaction(actions["transitionR!"], r, Int[r], [r - 1; r + 1; r + 1 + Sstride], i, i + 1)) end if S > 0 && insertstep > 1 && i < G + insertstep - 1 push!(reactions, Reaction(actions["transitionR!"], r, Int[r], [r - 1; r + 1], i, i + 1)) end end for e in indices.erange if S > 0 push!(reactions, Reaction(actions["eject!"], e, Int[e, e+Sstride], Int[e-1, indices.decay], G + R, 0)) elseif R > 0 push!(reactions, Reaction(actions["eject!"], e, Int[e], Int[e-1, indices.decay], G + R, 0)) else push!(reactions, Reaction(actions["eject!"], e, Int[], Int[e, indices.decay], G + 1, 0)) end end j = G + insertstep - 1 for s in indices.srange j += 1 push!(reactions, Reaction(actions["splice!"], s, Int[], Int[], j, 0)) end push!(reactions, Reaction(actions["decay!"], indices.decay, Int[], Int[indices.decay], 0, 0)) return reactions end """ update!(tau, state, index, t, m, r, allele, G, R, S, disabled, enabled, initial, final, action) updates proposed next reaction time and state given the selected action and returns updated number of mRNA (uses if-then statements because that executes faster than an element of an array of functions) Arguments are same as defined in simulator """ function update!(tau, state, index, t, m, r, allele, G, R, S, disabled, enabled, initial, final, action, insertstep) if action < 5 if action < 3 if action == 1 activateG!(tau, state, index, t, m, r, allele, G, R, disabled, enabled, initial, final) else deactivateG!(tau, state, index, t, m, r, allele, G, R, disabled, enabled, initial, final) end else if action == 3 transitionG!(tau, state, index, t, m, r, allele, G, R, disabled, enabled, initial, final) else initiate!(tau, state, index, t, m, r, allele, G, R, S, disabled, enabled, initial, final, insertstep) end end else if action < 7 if action == 5 transitionR!(tau, state, index, t, m, r, allele, G, R, S, disabled, enabled, initial, final, insertstep) else m = eject!(tau, state, index, t, m, r, allele, G, R, S, disabled, enabled, initial) end else if action == 7 splice!(tau, state, index, t, m, r, allele, G, R, initial) else m = decay!(tau, index, t, m, r) end end end return m end """ transitionG!(tau, state, index, t, m, r, allele, G, R, disabled, enabled, initial, final) update tau and state for G transition """ function transitionG!(tau, state, index, t, m, r, allele, G, R, disabled, enabled, initial, final) for e in enabled tau[e, allele] = -log(rand()) / r[e] + t end for d in disabled tau[d, allele] = Inf end state[final, allele] = 1 state[initial, allele] = 0 end """ activateG!(tau,state,index,t,m,r,allele,G,R,disabled,enabled,initial,final) """ function activateG!(tau, state, index, t, m, r, allele, G, R, disabled, enabled, initial, final) transitionG!(tau, state, index, t, m, r, allele, G, R, disabled, enabled, initial, final) if R > 0 && state[G+1, allele] > 0 tau[enabled[end], allele] = Inf end end """ deactivateG!(tau, state, index, t, m, r, allele, G, R, disabled, enabled, initial, final) """ function deactivateG!(tau, state, index, t, m, r, allele, G, R, disabled, enabled, initial, final) transitionG!(tau, state, index, t, m, r, allele, G, R, disabled, enabled, initial, final) end """ initiate!(tau, state, index, t, m, r, allele, G, R, S, enabled) """ function initiate!(tau, state, index, t, m, r, allele, G, R, S, disabled, enabled, initial, final, insertstep) if final + 1 > G + R || state[final+1, allele] == 0 tau[enabled[1], allele] = -log(rand()) / (r[enabled[1]]) + t end if insertstep == 1 state[final, allele] = 2 if S > 0 tau[enabled[2], allele] = -log(rand()) / (r[enabled[2]]) + t end else state[final, allele] = 1 end tau[index, allele] = Inf end """ transitionR!(tau, state, index, t, m, r, allele, G, R, S, u, d, initial, final) """ function transitionR!(tau, state, index, t, m, r, allele, G, R, S, disabled, enabled, initial, final, insertstep) if state[initial-1, allele] > 0 tau[enabled[1], allele] = -log(rand()) / r[enabled[1]] + t end if final + 1 > G + R || state[final+1, allele] == 0 tau[enabled[2], allele] = -log(rand()) / r[enabled[2]] + t end if S > 0 && final >= G + insertstep # tau[enabled[3], allele] = -log(rand()) / r[enabled[3]] + t if final == insertstep + G tau[enabled[3], allele] = -log(rand()) / r[enabled[3]] + t elseif state[initial, allele] > 1 tau[enabled[3], allele] = r[enabled[3]-1] / r[enabled[3]] * (tau[enabled[3]-1, allele] - t) + t end end for d in disabled tau[d, allele] = Inf end if final == insertstep + G state[final, allele] = 2 else state[final, allele] = state[initial, allele] end state[initial, allele] = 0 end """ eject!(tau, state, index, t, m, r, allele, G, R, S, disabled, enabled) """ function eject!(tau, state, index, t, m, r, allele, G, R, S, disabled, enabled, initial) if state[initial-1, allele] > 0 tau[enabled[1], allele] = -log(rand()) / (r[enabled[1]]) + t end for d in disabled tau[d, allele] = Inf end if R > 0 state[initial, allele] = 0 end set_decay!(tau, enabled[end], t, m, r) end """ splice!(tau, state, index, t, m, r, allele, G, R, initial) """ function splice!(tau, state, index, t, m, r, allele, G, R, initial) state[initial, allele] = 1 tau[index, allele] = Inf end """ decay!(tau, index, t, m, r) """ function decay!(tau, index, t, m, r) m -= 1 if m == 0 tau[index, 1] = Inf else tau[index, 1] = -log(rand()) / (m * r[index]) + t end m end """ set_decay!(tau, index, t, m, r) update tau matrix for decay rate """ function set_decay!(tau, index, t, m, r) m += 1 if m == 1 tau[index, 1] = -log(rand()) / r[index] + t else tau[index, 1] = (m - 1) / m * (tau[index, 1] - t) + t end m end
StochasticGene
https://github.com/nih-niddk-mbs/StochasticGene.jl.git
[ "MIT" ]
1.2.5
fc1bcee6037ea393ce28426929eff65c76a86779
code
34367
# Julia 1.5 # Stochastic Simulator to compute: # Live Cell ON/OFF distributions # smFISH steady state histograms # G state and R step Occupancy probabilities # Mean dwell time for being ON # """ get_gamma(r,n,nr) G state forward and backward transition rates for use in transition rate matrices of Master equation (different from gamma used in Gillespie algorithms) """ function get_gamma(r,n) gammaf = zeros(n+2) gammab = zeros(n+2) for i = 1:n gammaf[i+1] = r[2*(i-1)+1] gammab[i+1] = r[2*i] end return gammaf, gammab end """ get_nu(r,n,nr) R step forward transition rates """ get_nu(r,n,nr) =r[2*n+1 : 2*n+nr+1] """ get_eta(r,n,nr) Intron ejection rates at each R step """ get_eta(r,n,nr) = r[2*n+1+nr+1:2*n+1+nr+nr] function prep_param_telegraph(r,n,nr) # Transition rates # gammap = zeros(n+1) # gamman = zeros(n+1) # nu = zeros(nr+1) # eps = zeros(nr) # for i = 1:n # gammap[i] = r[2*(i-1)+1] # gamman[i+1] = r[2*i] # end # for i = 1:zeta+1 # nu[i] = r[2*n+i] # end # # Splice rate is non decreasing, rates in r represent increase in splice rate from previous step # eps[1] = r[2*n + 1 + zeta + 1] # for i = 2:zeta # eps[i] = eps[i-1] + r[2*n + 1 + zeta + i] # end gammap,gamman = get_gamma(r,n) return gammap[2:n+2],gamman[1:n+1],get_nu(r,n,nr),get_eta(r,n,nr) end #Compute dwelltime and steady state mRNA distributions function telegraphsplice0(range::Array,nhist::Int,n::Int,zeta::Int,rin::Vector,total::Int,tol::Float64,nalleles::Int) # decay reaction index reactiondecay = 2*n + 2*zeta + 2 # dwell time arrays ndt = length(range) dt = range[2]-range[1] histofftdd = zeros(Int,ndt) histontdd = zeros(Int,ndt) # ss mRNA array mhist = zeros(nhist+1) # tIA and TAI are times when gene state transitions between active and inactive states # they are used to compute dwell times tIA = zeros(Float64,nalleles) tAI = zeros(Float64,nalleles) # active start site mu = n # Get rates gammaf,gammab,nu,eta = prep_param_telegraph(rin,n,zeta) # assign decay rate delta = rin[reactiondecay] # assign correlation rate if length(rin) > reactiondecay rcorr = rin[reactiondecay+1] else rcorr = 0. end #initialize mRNA number to 0 m = 0 mproduced = 0 # Initialize gene states state = ones(Int,nalleles) # pre-mRNA states z = Array{Array{Int,1},1}(undef,nalleles) # Intron states intron = Array{Array{Int,1},1}(undef,nalleles) # initialize propensities af = Array{Float64,1}(undef,nalleles) ab = Array{Float64,1}(undef,nalleles) apre1 = Array{Float64,1}(undef,nalleles) az = Array{Array{Float64,1},1}(undef,nalleles) aintron = Array{Array{Float64,1},1}(undef,nalleles) apremid = zeros(nalleles) # sum(az[2:zeta]) middle pre-mRNAstep afree = zeros(nalleles) # az[zeta+1] create free mRNA for i = 1:nalleles z[i] = zeros(Int,zeta) # Intialize pre-mRNA state to all 0 af[i] = gammaf[state[i]] ab[i] = gammab[state[i]] az[i] = zeros(zeta+1) # apre1[i] = float(1-z[i][1])*nu[1]*float(state[i]==n+1) #first pre-mRNA step apre1[i] = float(state[i] > mu)*float(1-z[i][1])*nu[1] #first pre-mRNA step intron[i] = zeros(Int,zeta) aintron[i] = zeros(zeta) end astate = af + ab adecay = 0. #m*delta amrna = apre1 + apremid + afree t=0. # time ts=0. # time from last sample tsample = 20/minimum(rin) # sample every 100 decay times steps = 0 err = 10*tol hoff0 = ones(ndt)/ndt hon0 = ones(ndt)/ndt mhist0 = ones(nhist+1) # Begin simulation while err > tol && steps < total steps += 1 asum = sum(amrna) + sum(astate) + adecay if asum > 0. # choose which state to update and time of update r = asum*rand() tau = -log(rand())/asum # update time t += tau #print(tau,' ',asum,' ',state,'\n') if m + 1 <= nhist mhist[m+1] += tau else mhist[nhist+1] += tau end if r > sum(amrna + astate) # mRNA decay m -= 1 adecay = m*delta else agenecs = amrna[1] + astate[1] agene0 = 0. l = 1 while r > agenecs agene0 = agenecs agenecs += amrna[1+l] + astate[l+1] l += 1 end if l > 1 r -= agene0 end if r > amrna[l] # state update if r > ab[l] + amrna[l] # update forward reaction state[l] += 1 else # update backward reaction state[l] -= 1 end # update propensities af[l] = gammaf[state[l]] ab[l] = gammab[state[l]] astate[l] = af[l] + ab[l] # Activate coupling if any alleles are in state mu + 1 if rcorr > 0. ba = false for k = 1:nalleles ba |= state[k] > mu end if ba for k = 1:nalleles if state[k] == mu af[k] = gammaf[state[k]] + rcorr astate[k] = af[k] + ab[k] end end else for k = 1:nalleles if state[k] == mu af[k] = gammaf[state[k]] astate[k] = af[k] + ab[k] end end end end if state[l] > mu apre1[l] = float(1-z[l][1])*nu[1] # apre1 = az[l][1] else apre1[l] = 0. end amrna[l] = apremid[l] + apre1[l] + afree[l] + sum(aintron[l]) else # premRNA update if r > apremid[l] + apre1[l] + sum(aintron[l]) # increase free mRNA m += 1 adecay = m*delta mproduced += 1 z[l][zeta] = 0 #az[l][zeta+1] = 0 afree[l] = 0. # ON state ends, OFF state begins if sum(intron[l]) == 1 && intron[l][zeta] == 1 tAI[l] = t tactive = (tAI[l] - tIA[l])/dt if tactive <= ndt && tactive > 0 tactive = ceil(Int,tactive) histontdd[tactive] += 1 end end intron[l][zeta] = 0 aintron[l][zeta] = 0. if zeta == 1 if state[l] > mu #az[l][1] = nu[1] apre1[l] = nu[1] else #az[l][1] = 0 apre1[l] = 0. end else az[l][zeta] = float(z[l][zeta-1])*nu[zeta] apremid[l] = sum(az[l][2:zeta]) end amrna[l] = apre1[l] + apremid[l] + afree[l] + sum(aintron[l]) elseif r > apremid[l] + apre1[l] # eject intron aintronsum = apremid[l] + apre1[l] i = 0 while r > aintronsum i += 1 aintronsum += aintron[l][i] end intron[l][i] = 0 aintron[l][i] = 0 # ON state ends, OFF state begins if sum(intron[l]) == 0 #&& nhist == 0 tAI[l] = t tactive = (tAI[l] - tIA[l])/dt if tactive <= ndt && tactive > 0 tactive = ceil(Int,tactive) histontdd[tactive] += 1 end end amrna[l] = apremid[l] + apre1[l] + afree[l] + sum(aintron[l]) # println("*",apre1) elseif r > apremid[l] # increase first pre-mRNA state # OFF state ends, ON state begins if sum(intron[l]) == 0 #&& nhist == 0 tIA[l] = t tinactive = (tIA[l] - tAI[l])/dt if tinactive <= ndt && tinactive > 0 tinactive = ceil(Int,tinactive) histofftdd[tinactive] += 1 end end z[l][1] = 1 #az[l][1] = 0 apre1[l] = 0. intron[l][1] = 1 aintron[l][1] = eta[1] if zeta == 1 #az[l][2] = nu[2] afree[l] = nu[2] else az[l][2] = float(1-z[l][2])*nu[2] apremid[l] = sum(az[l][2:zeta]) end amrna[l] = apre1[l] + apremid[l] + afree[l] + sum(aintron[l]) else # update mid pre-mRNA state azsum = az[l][2] k = 1 while r > azsum azsum += az[l][2+k] k += 1 end i = k + 1 z[l][i] = 1 z[l][i-1] = 0 az[l][i] = 0. if intron[l][i-1] == 1 intron[l][i] = 1 intron[l][i-1] = 0 aintron[l][i] = eta[i] aintron[l][i-1] = 0. else intron[l][i] = 0 aintron[l][i] = 0. end if i == zeta #az[l][i+1] = nu[i+1] afree[l] = nu[i+1] else az[l][i+1] = float(1-z[l][i+1])*nu[i+1] end if i == 2 if state[l] > mu #az[l][1] = nu[1] apre1[l] = nu[1] else az[l][1] = 0. apre1[l] = 0. end else az[l][i-1] = float(z[l][i-2])*nu[i-1] end apremid[l] = sum(az[l][2:zeta]) amrna[l] = apre1[l] + apremid[l] + afree[l] + sum(aintron[l]) end # if r > apremid[l] + apre1[l] end # if r > amrna[l] end #if r > sum(amrna + adecay) end #if asum > 0 # Compute change in histograms from last sample ts += tau if ts > tsample hoff = histofftdd/sum(histofftdd) hon = histontdd/sum(histontdd) err = max(norm(hoff-hoff0,Inf),norm(hon-hon0,Inf)) hoff0 = copy(hoff) hon0 = copy(hon) errss = norm(mhist/sum(mhist) - mhist0/sum(mhist0),Inf) err = max(err,errss) mhist0 = copy(mhist) ts = 0. end end # while bursts < nbursts && steps < total sumoff = sum(histofftdd) sumon = sum(histontdd) counts = max(sum(mhist),1) mhist /= counts # print(mproduced/t) return histofftdd/max(sumoff,1), histontdd/max(sumon,1), mhist[1:nhist] end function telegraphPDF(t::Vector,n::Int,zeta::Int,rin::Vector) telegraphsplice(t,n,zeta,rin,10000000,1e-6,1) end # Compute ON OFF time histograms function telegraphsplice(range::Array,n::Int,zeta::Int,rin::Vector,total::Int,tol::Float64,nalleles::Int=1,CDF::Bool=false) # Generalized n-zeta telegraph model # Compute dwell time histograms # n+1 total gene states # gene states are labeled from 1 to n+1 # zeta pre-mRNA steps # There are 2n gene reactions, zeta pre-mRNA reactions, and 1 mRNA decay reaction # rin = reaction rates # forward gene reactions are labeled by odd numbers <2n, backward reactions are even numbers <= 2n # reactions [2n+1, 2n+zeta] are pre-mRNA recations,organized by starting spot, reaction 2n(zeta+1)+1 is mRNA decay reaction # Use Gillespie direct method with speed up from Gibson and Bruck # decay reaction index reactiondecay = 2*n + 2*zeta + 2 # dwell time arrays ndt = length(range) dt = range[2]-range[1] histofftdd = zeros(Int,ndt) histontdd = zeros(Int,ndt) # tIA and TAI are times when gene state transitions between active and inactive states # they are used to compute dwell times tIA = zeros(Float64,nalleles) tAI = zeros(Float64,nalleles) # active start site mu = n # get rates gammaf,gammab,nu,eta = prep_param_telegraph(rin,n,zeta) # assign decay rate delta = rin[reactiondecay] # assign correlation rate if length(rin) > reactiondecay rcorr = rin[reactiondecay+1] else rcorr = 0. end #initialize mRNA number to 0 m = 0 # Initialize gene states state = ones(Int,nalleles) # pre-mRNA states z = Array{Array{Int,1},1}(undef,nalleles) # Intron states intron = Array{Array{Int,1},1}(undef,nalleles) # initialize propensities af = Array{Float64,1}(undef,nalleles) ab = Array{Float64,1}(undef,nalleles) apre1 = Array{Float64,1}(undef,nalleles) az = Array{Array{Float64,1},1}(undef,nalleles) aintron = Array{Array{Float64,1},1}(undef,nalleles) apremid = zeros(nalleles) # sum(az[2:zeta]) middle pre-mRNAstep afree = zeros(nalleles) # az[zeta+1] create free mRNA for i = 1:nalleles z[i] = zeros(Int,zeta) # Intialize pre-mRNA state to all 0 af[i] = gammaf[state[i]] ab[i] = gammab[state[i]] az[i] = zeros(zeta+1) # apre1[i] = float(1-z[i][1])*nu[1]*float(state[i]==n+1) #first pre-mRNA step apre1[i] = float(state[i] > mu)*float(1-z[i][1])*nu[1] #first pre-mRNA step intron[i] = zeros(Int,zeta) aintron[i] = zeros(zeta) end astate = af + ab adecay = 0. #m*delta amrna = apre1 + apremid + afree t=0. # time ts=0. # time from last sample tsample = 20/minimum(rin) # sample every 100 decay times steps = 0 err = 10*tol bursts = 0 hoff0 = ones(ndt)/ndt hon0 = ones(ndt)/ndt # Begin simulation while err > tol && steps < total steps += 1 asum = sum(amrna) + sum(astate) + adecay if asum > 0. # choose which state to update and time of update r = asum*rand() tau = -log(rand())/asum # update time t += tau #print(tau,' ',asum,' ',state,'\n') if r > sum(amrna + astate) # mRNA decay m -= 1 adecay = m*delta else agenecs = amrna[1] + astate[1] agene0 = 0. l = 1 while r > agenecs agene0 = agenecs agenecs += amrna[1+l] + astate[l+1] l += 1 end if l > 1 r -= agene0 end if r > amrna[l] # state update if r > ab[l] + amrna[l] # update forward reaction state[l] += 1 else # update backward reaction state[l] -= 1 end # update propensities af[l] = gammaf[state[l]] ab[l] = gammab[state[l]] astate[l] = af[l] + ab[l] # Activate coupling if any alleles are in state mu + 1 if rcorr > 0. ba = false for k = 1:nalleles ba |= state[k] > mu end if ba for k = 1:nalleles if state[k] == mu af[k] = gammaf[state[k]] + rcorr astate[k] = af[k] + ab[k] end end else for k = 1:nalleles if state[k] == mu af[k] = gammaf[state[k]] astate[k] = af[k] + ab[k] end end end end if state[l] > mu apre1[l] = float(1-z[l][1])*nu[1] # apre1 = az[l][1] else apre1[l] = 0. end amrna[l] = apremid[l] + apre1[l] + afree[l] + sum(aintron[l]) else # premRNA update if r > apremid[l] + apre1[l] + sum(aintron[l]) # increase free mRNA m += 1 adecay = m*delta z[l][zeta] = 0 #az[l][zeta+1] = 0 afree[l] = 0. # ON state ends, OFF state begins if sum(intron[l]) == 1 && intron[l][zeta] == 1 tAI[l] = t tactive = (tAI[l] - tIA[l])/dt if tactive <= ndt && tactive > 0 tactive = ceil(Int,tactive) histontdd[tactive] += 1 end end intron[l][zeta] = 0 aintron[l][zeta] = 0. if zeta == 1 if state[l] > mu #az[l][1] = nu[1] apre1[l] = nu[1] else #az[l][1] = 0 apre1[l] = 0. end else az[l][zeta] = float(z[l][zeta-1])*nu[zeta] apremid[l] = sum(az[l][2:zeta]) end amrna[l] = apre1[l] + apremid[l] + afree[l] + sum(aintron[l]) elseif r > apremid[l] + apre1[l] # eject intron aintronsum = apremid[l] + apre1[l] i = 0 while r > aintronsum i += 1 aintronsum += aintron[l][i] end intron[l][i] = 0 aintron[l][i] = 0 # ON state ends, OFF state begins if sum(intron[l]) == 0 #&& nhist == 0 tAI[l] = t tactive = (tAI[l] - tIA[l])/dt if tactive <= ndt && tactive > 0 tactive = ceil(Int,tactive) histontdd[tactive] += 1 end end amrna[l] = apremid[l] + apre1[l] + afree[l] + sum(aintron[l]) elseif r > apremid[l] # increase first pre-mRNA state # OFF state ends, ON state begins if sum(intron[l]) == 0 #&& nhist == 0 tIA[l] = t tinactive = (tIA[l] - tAI[l])/dt if tinactive <= ndt && tinactive > 0 tinactive = ceil(Int,(tIA[l] - tAI[l])/dt) histofftdd[tinactive] += 1 bursts += 1 end end z[l][1] = 1 #az[l][1] = 0 apre1[l] = 0. intron[l][1] = 1 aintron[l][1] = eta[1] if zeta == 1 #az[l][2] = nu[2] afree[l] = nu[2] else az[l][2] = float(1-z[l][2])*nu[2] apremid[l] = sum(az[l][2:zeta]) end amrna[l] = apre1[l] + apremid[l] + afree[l] + sum(aintron[l]) else # update mid pre-mRNA state azsum = az[l][2] k = 1 while r > azsum azsum += az[l][2+k] k += 1 end i = k + 1 z[l][i] = 1 z[l][i-1] = 0 az[l][i] = 0. if intron[l][i-1] == 1 intron[l][i] = 1 intron[l][i-1] = 0 aintron[l][i] = eta[i] aintron[l][i-1] = 0. else intron[l][i] = 0 aintron[l][i] = 0. end if i == zeta #az[l][i+1] = nu[i+1] afree[l] = nu[i+1] else az[l][i+1] = float(1-z[l][i+1])*nu[i+1] end if i == 2 if state[l] > mu #az[l][1] = nu[1] apre1[l] = nu[1] else az[l][1] = 0. apre1[l] = 0. end else az[l][i-1] = float(z[l][i-2])*nu[i-1] end apremid[l] = sum(az[l][2:zeta]) amrna[l] = apre1[l] + apremid[l] + afree[l] + sum(aintron[l]) end # if r > apremid[l] + apre1[l] end # if r > amrna[l] end #if r > sum(amrna + adecay) end #if asum > 0 # Compute change in histograms from last sample ts += tau if ts > tsample hoff = histofftdd/sum(histofftdd) hon = histontdd/sum(histontdd) err = max(norm(hoff-hoff0,Inf),norm(hon-hon0,Inf)) hoff0 = copy(hoff) hon0 = copy(hon) ts = 0. end end # while bursts < nbursts && steps < total sumoff = sum(histofftdd) sumon = sum(histontdd) if CDF if sumon > 0 && sumoff > 0 #return [histofftdd[2]/sumoff; histontdd[2]/sumon], mhistn return cumsum(histofftdd/sumoff), cumsum(histontdd/sumon) else return zeros(length(histofftdd)),zeros(length(histontdd)) end else return histofftdd/sumoff/dt, histontdd/sumon/dt end end # Splicing leads to termination model #Compute dwelltime and steady state mRNA distributions # function telegraphsplicedeath(range::Array,nhist::Int,n::Int,zeta::Int,rin::Vector,total::Int,tol::Float64,nalleles::Int) # # # Generalized n-zeta telegraph model # # n+1 total gene states # # gene states are labeled from 1 to n+1 # # zeta pre-mRNA steps # # There are 2n gene reactions, zeta pre-mRNA reactions, and 1 mRNA decay reaction # # rin = reaction rates # # forward gene reactions are labeled by odd numbers <2n, backward reactions are even numbers <= 2n # # reactions [2n+1, 2n+zeta] are pre-mRNA recations,organized by starting spot, reaction 2n(zeta+1)+1 is mRNA decay reaction # # spliced introns before the last zeta state lead to exon ejection # # # Use Gillespie direct method with speed up from Gibson and Bruck # # # decay reaction index # reactiondecay = 2*n + 2*zeta + 2 # # # dwell time arrays # ndt = length(range) # dt = range[2]-range[1] # histofftdd = zeros(Int,ndt) # histontdd = zeros(Int,ndt) # # # ss mRNA array # mhist = zeros(nhist+1) # # # tIA and TAI are times when gene state transitions between active and inactive states # # they are used to compute dwell times # tIA = zeros(Float64,nalleles) # tAI = zeros(Float64,nalleles) # # # active start site # mu = n # # print(n," ",mu," ",zeta,'\n') # # # Initialize rates # gammaf = zeros(n+1) # gammab = zeros(n+1) # nu = Array{Float64,1}(undef,zeta+1) # eta = Array{Float64,1}(undef,zeta) # # # gene rates # for i = 1:n # gammaf[i] = rin[2*(i-1)+1] # gammab[i+1] = rin[2*i] # end # # # pre-mRNA stepping rates # for i = 1:zeta+1 # nu[i] = rin[2*n + i] # end # # # pre-mRNA ejection rates # for i = 1:zeta # eta[i] = rin[2*n + zeta + 1 + i] # end # # # assign decay rate # delta = rin[reactiondecay] # # # assign correlation rate # if length(rin) > reactiondecay # rcorr = rin[reactiondecay+1] # else # rcorr = 0. # end # # #initialize mRNA number to 0 # m = 0 # # # Initialize gene states # state = ones(Int,nalleles) # # # pre-mRNA states # z = Array{Array{Int,1},1}(undef,nalleles) # # # Intron states # intron = Array{Array{Int,1},1}(undef,nalleles) # # # initialize propensities # af = Array{Float64,1}(undef,nalleles) # ab = Array{Float64,1}(undef,nalleles) # apre1 = Array{Float64,1}(undef,nalleles) # az = Array{Array{Float64,1},1}(undef,nalleles) # aintron = Array{Array{Float64,1},1}(undef,nalleles) # # apremid = zeros(nalleles) # sum(az[2:zeta]) middle pre-mRNAstep # afree = zeros(nalleles) # az[zeta+1] create free mRNA # # for i = 1:nalleles # z[i] = zeros(Int,zeta) # Intialize pre-mRNA state to all 0 # af[i] = gammaf[state[i]] # ab[i] = gammab[state[i]] # az[i] = zeros(zeta+1) # # apre1[i] = float(1-z[i][1])*nu[1]*float(state[i]==n+1) #first pre-mRNA step # apre1[i] = float(state[i] > mu)*float(1-z[i][1])*nu[1] #first pre-mRNA step # intron[i] = zeros(Int,zeta) # aintron[i] = zeros(zeta) # end # # astate = af + ab # # adecay = 0. #m*delta # # amrna = apre1 + apremid + afree # # t=0. # time # ts=0. # time from last sample # tsample = 100/minimum(rin) # sample every 100 min rate times # steps = 0 # err = 10*tol # # hoff0 = ones(ndt)/ndt # hon0 = ones(ndt)/ndt # # mhist0 = ones(nhist+1) # # # Begin simulation # while err > tol && steps < total # # steps += 1 # # asum = sum(amrna) + sum(astate) + adecay # # if asum > 0. # # choose which state to update and time of update # r = asum*rand() # tau = -log(rand())/asum # # update time # t += tau # if m + 1 <= nhist # mhist[m+1] += tau # else # mhist[nhist+1] += tau # end # if r > sum(amrna + astate) # # mRNA decay # m -= 1 # adecay = m*delta # else # agenecs = amrna[1] + astate[1] # agene0 = 0. # l = 1 # while r > agenecs # agene0 = agenecs # agenecs += amrna[1+l] + astate[l+1] # l += 1 # end # if l > 1 # r -= agene0 # end # if r > amrna[l] # # state update # if r > ab[l] + amrna[l] # # update forward reaction # state[l] += 1 # else # # update backward reaction # state[l] -= 1 # end # # update propensities # af[l] = gammaf[state[l]] # ab[l] = gammab[state[l]] # astate[l] = af[l] + ab[l] # # Activate coupling if any alleles are in state mu + 1 # if rcorr > 0. # ba = false # for k = 1:nalleles # ba |= state[k] > mu # end # if ba # for k = 1:nalleles # if state[k] == mu # af[k] = gammaf[state[k]] + rcorr # astate[k] = af[k] + ab[k] # end # end # else # for k = 1:nalleles # if state[k] == mu # af[k] = gammaf[state[k]] # astate[k] = af[k] + ab[k] # end # end # end # end # if state[l] > mu # apre1[l] = float(1-z[l][1])*nu[1] # # apre1 = az[l][1] # else # apre1[l] = 0. # end # amrna[l] = apremid[l] + apre1[l] + afree[l] + sum(aintron[l]) # else # # premRNA update # if r > apremid[l] + apre1[l] + sum(aintron[l]) # # increase free mRNA # m += 1 # adecay = m*delta # z[l][zeta] = 0 # #az[l][zeta+1] = 0 # afree[l] = 0. # # ON state ends, OFF state begins # if sum(intron[l]) == 1 && intron[l][zeta] == 1 # tAI[l] = t # tactive = (tAI[l] - tIA[l])/dt # if tactive <= ndt && tactive > 0 # tactive = ceil(Int,tactive) # histontdd[tactive] += 1 # end # end # intron[l][zeta] = 0 # aintron[l][zeta] = 0. # if zeta == 1 # if state[l] > mu # #az[l][1] = nu[1] # apre1[l] = nu[1] # else # #az[l][1] = 0 # apre1[l] = 0. # end # else # az[l][zeta] = float(z[l][zeta-1])*nu[zeta] # apremid[l] = sum(az[l][2:zeta]) # end # amrna[l] = apre1[l] + apremid[l] + afree[l] + sum(aintron[l]) # elseif r > apremid[l] + apre1[l] # # eject intron # aintronsum = apremid[l] + apre1[l] # i = 0 # while r > aintronsum # i += 1 # aintronsum += aintron[l][i] # end # intron[l][i] = 0 # aintron[l][i] = 0 # if i < zeta # z[l][i] = 0 # az[l][i+1] = 0 # if i == 1 # if state[l] > mu # apre1[l] = nu[1] # else # apre1[l] = 0. # end # else # az[l][i] = float(z[l][i-1])*nu[i] # end # end # apremid[l] = sum(az[l][2:zeta]) # # ON state ends, OFF state begins # if sum(intron[l]) == 0 #&& nhist == 0 # tAI[l] = t # tactive = (tAI[l] - tIA[l])/dt # if tactive <= ndt && tactive > 0 # tactive = ceil(Int,tactive) # histontdd[tactive] += 1 # end # end # amrna[l] = apremid[l] + apre1[l] + afree[l] + sum(aintron[l]) # elseif r > apremid[l] # # increase first pre-mRNA state # # OFF state ends, ON state begins # if sum(intron[l]) == 0 #&& nhist == 0 # tIA[l] = t # tinactive = (tIA[l] - tAI[l])/dt # if tinactive <= ndt && tinactive > 0 # tinactive = ceil(Int,(tIA[l] - tAI[l])/dt) # histofftdd[tinactive] += 1 # end # end # z[l][1] = 1 # apre1[l] = 0. # intron[l][1] = 1 # aintron[l][1] = eta[1] # if zeta == 1 # afree[l] = nu[2] # else # az[l][2] = float(1-z[l][2])*nu[2] # apremid[l] = sum(az[l][2:zeta]) # end # amrna[l] = apre1[l] + apremid[l] + afree[l] + sum(aintron[l]) # else # # update mid pre-mRNA state # azsum = az[l][2] # k = 1 # while r > azsum # azsum += az[l][2+k] # k += 1 # end # i = k + 1 # z[l][i] = 1 # z[l][i-1] = 0 # az[l][i] = 0. # if intron[l][i-1] == 1 # intron[l][i] = 1 # intron[l][i-1] = 0 # aintron[l][i] = eta[i] # aintron[l][i-1] = 0. # else # intron[l][i] = 0 # aintron[l][i] = 0. # end # if i == zeta # #az[l][i+1] = nu[i+1] # afree[l] = nu[i+1] # else # az[l][i+1] = float(1-z[l][i+1])*nu[i+1] # end # if i == 2 # if state[l] > mu # #az[l][1] = nu[1] # apre1[l] = nu[1] # else # az[l][1] = 0. # apre1[l] = 0. # end # else # az[l][i-1] = float(z[l][i-2])*nu[i-1] # end # apremid[l] = sum(az[l][2:zeta]) # amrna[l] = apre1[l] + apremid[l] + afree[l] + sum(aintron[l]) # end # if r > apremid[l] + apre1[l] # end # if r > amrna[l] # end #if r > sum(amrna + adecay) # end #if asum > 0 # # Compute change in histograms from last sample # ts += tau # if ts > tsample # hoff = histofftdd/sum(histofftdd) # hon = histontdd/sum(histontdd) # err = max(norm(hoff-hoff0,Inf),norm(hon-hon0,Inf)) # hoff0 = copy(hoff) # hon0 = copy(hon) # errss = norm(mhist/sum(mhist) - mhist0/sum(mhist0),Inf) # err = max(err,errss) # mhist0 = copy(mhist) # ts = 0. # end # end # while bursts < nbursts && steps < total # # sumoff = sum(histofftdd) # sumon = sum(histontdd) # # counts = max(sum(mhist),1) # mhist /= counts # # return histofftdd/max(sumoff,1), histontdd/max(sumon,1), mhist[1:nhist] # end function telegraphssoff(n::Int,zeta::Int,rin::Vector,nhist::Int,nalleles::Int) r = copy(rin) r[end] /= survivalfraction(rin,n,zeta) off,on,hist = telegraphsplice0(collect(1:10),nhist,n,zeta,r,100000000,1e-7,nalleles) return hist end function telegraphss(n::Int,zeta::Int,r::Vector{Float64},nhist::Int,nalleles::Int) off,on,hist = telegraphsplice0(collect(1:10),nhist,n,zeta,r,100000000,1e-7,nalleles) return hist end # Compute smFISH histogram function telegraphsplice(n::Int,zeta::Int,rin::Vector,total::Int,tmax::Float64,nhist::Int,nalleles::Int,count=false) # Generalized n, zeta, telegraph model, # Compute steady state mRNA histogram # n+1 total gene states # gene states are labeled from 1 to n+1 # zeta pre-mRNA steps # There are 2n gene reactions, zeta pre-mRNA reactions, and 1 mRNA decay reaction # rin = reaction rates # forward gene reactions are labeled by odd numbers <2n, backward reactions are even numbers <= 2n # reactions [2n+1, 2n+zeta] are pre-mRNA reactions,organized by starting spot, reaction 2n(zeta+1)+1 is mRNA decay reaction # Use Gillespie direct method with speed up from Gibson and Bruck # decay reaction index reactiondecay = 2*n + 2*zeta + 2 # time t=0. #Initialize m histogram mhist=zeros(nhist+1) mu = n # Initialize rates # gammaf = zeros(n+1) # gammab = zeros(n+1) # nu = Array{Float64,1}(undef,zeta+1) # eta = Array{Float64,1}(undef,zeta) # # assign gene rates # for i = 1:n # gammaf[i] = rin[2*(i-1)+1] # gammab[i+1] = rin[2*i] # end # # assign pre-mRNA rates # for i = 1:zeta+1 # nu[i] = rin[2*n + i] # end # # pre-mRNA ejection rates # for i = 1:zeta # eta[i] = rin[2*n + zeta + 1 + i] # end gammaf,gammab,nu,eta = prep_param_telegraph(rin,n,zeta) # assign decay rate delta = rin[reactiondecay] # assign correlation rate if length(rin) > reactiondecay rcorr = rin[reactiondecay+1] else rcorr = 0. end #initialize mRNA number to 0 m = 0 # Initialize gene states state = ones(Int,nalleles) state[1] = mu + 1 # pre-mRNA states z = Array{Array{Int,1},1}(undef,nalleles) # Intron states intron = Array{Array{Int,1},1}(undef,nalleles) # initialize propensities af = Array{Float64,1}(undef,nalleles) ab = Array{Float64,1}(undef,nalleles) apre1 = Array{Float64,1}(undef,nalleles) az = Array{Array{Float64,1},1}(undef,nalleles) aintron = Array{Array{Float64,1},1}(undef,nalleles) apremid = zeros(nalleles) # sum(az[2:zeta]) middle pre-mRNAstep afree = zeros(nalleles) # az[zeta+1] create free mRNA for i = 1:nalleles z[i] = zeros(Int,zeta) # Intialize pre-mRNA state to all 0 af[i] = gammaf[state[i]] ab[i] = gammab[state[i]] az[i] = zeros(zeta+1) # apre1[i] = float(1-z[i][1])*nu[1]*float(state[i]==n+1) #first pre-mRNA step apre1[i] = float(state[i]>mu)*float(1-z[i][1])*nu[1] #first pre-mRNA step intron[i] = zeros(Int,zeta) aintron[i] = zeros(zeta) end astate = af + ab adecay = 0. #m*delta amrna = apre1 + apremid + afree bursts = 0 steps = 0 while t < tmax && steps < total steps += 1 asum = sum(amrna) + sum(astate) + adecay if asum > 0. # choose which state to update and time of update r = asum*rand() tau = -log(rand())/asum # update time t += tau #print(tau,' ',asum,' ',state,'\n') if m + 1 <= nhist mhist[m+1] += tau else mhist[nhist+1] += tau end if r > sum(amrna + astate) # mRNA decay m -= 1 adecay = m*delta else agenecs = amrna[1] + astate[1] agene0 = 0. l = 1 while r > agenecs agene0 = agenecs agenecs += amrna[1+l] + astate[l+1] l += 1 end if l > 1 r -= agene0 end if r > amrna[l] # state update if r > ab[l] + amrna[l] # update forward reaction state[l] += 1 else # update backward reaction state[l] -= 1 end # update propensities af[l] = gammaf[state[l]] ab[l] = gammab[state[l]] astate[l] = af[l] + ab[l] # Activate coupling if any alleles are in state mu + 1 if rcorr > 0. ba = false for k = 1:nalleles ba |= state[k] > mu end if ba for k = 1:nalleles if state[k] == mu af[k] = gammaf[state[k]] + rcorr astate[k] = af[k] + ab[k] end end else for k = 1:nalleles if state[k] == mu af[k] = gammaf[state[k]] astate[k] = af[k] + ab[k] end end end end if state[l] > mu apre1[l] = float(1-z[l][1])*nu[1] # apre1 = az[l][1] else apre1[l] = 0. end amrna[l] = apremid[l] + apre1[l] + afree[l] + sum(aintron[l]) else # premRNA update if r > apremid[l] + apre1[l] + sum(aintron[l]) # increase free mRNA m += 1 adecay = m*delta z[l][zeta] = 0 #az[l][zeta+1] = 0 afree[l] = 0. intron[l][zeta] = 0 aintron[l][zeta] = 0. if zeta == 1 if state[l] > mu #az[l][1] = nu[1] apre1[l] = nu[1] else #az[l][1] = 0 apre1[l] = 0. end else az[l][zeta] = float(z[l][zeta-1])*nu[zeta] apremid[l] = sum(az[l][2:zeta]) end amrna[l] = apre1[l] + apremid[l] + afree[l] + sum(aintron[l]) elseif r > apremid[l] + apre1[l] aintronsum = apremid[l] + apre1[l] i = 0 while r > aintronsum i += 1 aintronsum += aintron[l][i] end intron[l][i] = 0 aintron[l][i] = 0 amrna[l] = apremid[l] + apre1[l] + afree[l] + sum(aintron[l]) # println("*",apre1) elseif r > apremid[l] # increase first pre-mRNA state z[l][1] = 1 #az[l][1] = 0 apre1[l] = 0. intron[l][1] = 1 aintron[l][1] = eta[1] if zeta == 1 #az[l][2] = nu[2] afree[l] = nu[2] else az[l][2] = float(1-z[l][2])*nu[2] apremid[l] = sum(az[l][2:zeta]) end amrna[l] = apre1[l] + apremid[l] + afree[l] + sum(aintron[l]) else # update mid pre-mRNA state azsum = az[l][2] k = 1 while r > azsum azsum += az[l][2+k] k += 1 end i = k + 1 z[l][i] = 1 z[l][i-1] = 0 az[l][i] = 0. if intron[l][i-1] == 1 intron[l][i] = 1 intron[l][i-1] = 0 aintron[l][i] = eta[i] aintron[l][i-1] = 0. else intron[l][i] = 0 aintron[l][i] = 0. end if i == zeta #az[l][i+1] = nu[i+1] afree[l] = nu[i+1] else az[l][i+1] = float(1-z[l][i+1])*nu[i+1] end if i == 2 if state[l] > mu #az[l][1] = nu[1] apre1[l] = nu[1] else az[l][1] = 0. apre1[l] = 0. end else az[l][i-1] = float(z[l][i-2])*nu[i-1] end apremid[l] = sum(az[l][2:zeta]) amrna[l] = apre1[l] + apremid[l] + afree[l] + sum(aintron[l]) end # if r > apremid[l] + apre1[l] end # if r > amrna[l] end #if r > sum(amrna + adecay) end #if asum > 0 end # while t counts = max(sum(mhist),1) mhist /= counts if count return mhist[1:nhist],counts else return mhist[1:nhist] end end function telegraphspliceoff(n::Int,zeta::Int,rin::Vector,total::Int,tmax::Float64,nhist::Int,nalleles::Int,count=false) r = copy(rin) r[end] /= survivalfraction(rin,n,zeta) telegraphsplice(n,zeta,r,total,tmax,nhist,nalleles) end function telegraph(range::Array,nhist::Int,n::Int,zeta::Int,rin::Vector,nalleles::Int) r = copy(rin) telegraphsplice0(range,nhist,n,zeta,r,100000000,1e-7,nalleles) end function telegraphoff(range::Array,nhist::Int,n::Int,zeta::Int,rin::Vector,nalleles::Int) r = copy(rin) r[end] /= survivalfraction(rin,n,zeta) telegraphsplice0(range,nhist,n,zeta,r,100000000,1e-7,nalleles) end
StochasticGene
https://github.com/nih-niddk-mbs/StochasticGene.jl.git
[ "MIT" ]
1.2.5
fc1bcee6037ea393ce28426929eff65c76a86779
code
8222
function prep_param_telegraph(r,n,zeta) # Transition rates gammap = zeros(n+1) gamman = zeros(n+1) nu = zeros(zeta+1) eps = zeros(zeta) for i = 1:n gammap[i] = r[2*(i-1)+1] gamman[i+1] = r[2*i] end for i = 1:zeta+1 nu[i] = r[2*n+i] end # Splice rate is non decreasing, rates in r represent increase in splice rate from previous step eps[1] = r[2*n + 1 + zeta + 1] for i = 2:zeta eps[i] = eps[i-1] + r[2*n + 1 + zeta + i] end return gammap,gamman,nu,eps end #Compute dwelltime and steady state mRNA distributions function telegraphsplice0(range::Array,nhist::Int,n::Int,zeta::Int,rin::Vector,total::Int,tol::Float64,nalleles::Int) # decay reaction index reactiondecay = 2*n + 2*zeta + 2 # dwell time arrays ndt = length(range) dt = range[2]-range[1] histofftdd = zeros(Int,ndt) histontdd = zeros(Int,ndt) # ss mRNA array mhist = zeros(nhist+1) # tIA and TAI are times when gene state transitions between active and inactive states # they are used to compute dwell times tIA = zeros(Float64,nalleles) tAI = zeros(Float64,nalleles) # active start site mu = n # Get rates gammaf,gammab,nu,eta = prep_param_telegraph(rin,n,zeta) # assign decay rate delta = rin[reactiondecay] # assign correlation rate if length(rin) > reactiondecay rcorr = rin[reactiondecay+1] else rcorr = 0. end #initialize mRNA number to 0 m = 0 mproduced = 0 # Initialize gene states state = ones(Int,nalleles) # pre-mRNA states z = Array{Array{Int,1},1}(undef,nalleles) # Intron states intron = Array{Array{Int,1},1}(undef,nalleles) # initialize propensities af = Array{Float64,1}(undef,nalleles) ab = Array{Float64,1}(undef,nalleles) apre1 = Array{Float64,1}(undef,nalleles) az = Array{Array{Float64,1},1}(undef,nalleles) aintron = Array{Array{Float64,1},1}(undef,nalleles) apremid = zeros(nalleles) # sum(az[2:zeta]) middle pre-mRNAstep afree = zeros(nalleles) # az[zeta+1] create free mRNA for i = 1:nalleles z[i] = zeros(Int,zeta) # Intialize pre-mRNA state to all 0 af[i] = gammaf[state[i]] ab[i] = gammab[state[i]] az[i] = zeros(zeta+1) # apre1[i] = float(1-z[i][1])*nu[1]*float(state[i]==n+1) #first pre-mRNA step apre1[i] = float(state[i] > mu)*float(1-z[i][1])*nu[1] #first pre-mRNA step intron[i] = zeros(Int,zeta) aintron[i] = zeros(zeta) end astate = af + ab adecay = 0. #m*delta amrna = apre1 + apremid + afree t=0. # time ts=0. # time from last sample tsample = 20/minimum(rin) # sample every 100 decay times steps = 0 err = 10*tol hoff0 = ones(ndt)/ndt hon0 = ones(ndt)/ndt mhist0 = ones(nhist+1) intensity = Matrix{Float64}(undef,0,2) # Begin simulation while err > tol && steps < total steps += 1 intensity = vcat(intensity,[t sum(intron[1])]) asum = sum(amrna) + sum(astate) + adecay if asum > 0. # choose which state to update and time of update r = asum*rand() tau = -log(rand())/asum # update time t += tau #print(tau,' ',asum,' ',state,'\n') if m + 1 <= nhist mhist[m+1] += tau else mhist[nhist+1] += tau end if r > sum(amrna + astate) # mRNA decay m -= 1 adecay = m*delta else agenecs = amrna[1] + astate[1] agene0 = 0. l = 1 while r > agenecs agene0 = agenecs agenecs += amrna[1+l] + astate[l+1] l += 1 end if l > 1 r -= agene0 end if r > amrna[l] # state update if r > ab[l] + amrna[l] # update forward reaction state[l] += 1 else # update backward reaction state[l] -= 1 end # update propensities af[l] = gammaf[state[l]] ab[l] = gammab[state[l]] astate[l] = af[l] + ab[l] # Activate coupling if any alleles are in state mu + 1 if rcorr > 0. ba = false for k = 1:nalleles ba |= state[k] > mu end if ba for k = 1:nalleles if state[k] == mu af[k] = gammaf[state[k]] + rcorr astate[k] = af[k] + ab[k] end end else for k = 1:nalleles if state[k] == mu af[k] = gammaf[state[k]] astate[k] = af[k] + ab[k] end end end end if state[l] > mu apre1[l] = float(1-z[l][1])*nu[1] # apre1 = az[l][1] else apre1[l] = 0. end amrna[l] = apremid[l] + apre1[l] + afree[l] + sum(aintron[l]) else # premRNA update if r > apremid[l] + apre1[l] + sum(aintron[l]) # increase free mRNA m += 1 adecay = m*delta mproduced += 1 z[l][zeta] = 0 #az[l][zeta+1] = 0 afree[l] = 0. # ON state ends, OFF state begins if sum(intron[l]) == 1 && intron[l][zeta] == 1 tAI[l] = t tactive = (tAI[l] - tIA[l])/dt if tactive <= ndt && tactive > 0 tactive = ceil(Int,tactive) histontdd[tactive] += 1 end end intron[l][zeta] = 0 aintron[l][zeta] = 0. if zeta == 1 if state[l] > mu #az[l][1] = nu[1] apre1[l] = nu[1] else #az[l][1] = 0 apre1[l] = 0. end else az[l][zeta] = float(z[l][zeta-1])*nu[zeta] apremid[l] = sum(az[l][2:zeta]) end amrna[l] = apre1[l] + apremid[l] + afree[l] + sum(aintron[l]) elseif r > apremid[l] + apre1[l] # eject intron aintronsum = apremid[l] + apre1[l] i = 0 while r > aintronsum i += 1 aintronsum += aintron[l][i] end intron[l][i] = 0 aintron[l][i] = 0 # ON state ends, OFF state begins if sum(intron[l]) == 0 #&& nhist == 0 tAI[l] = t tactive = (tAI[l] - tIA[l])/dt if tactive <= ndt && tactive > 0 tactive = ceil(Int,tactive) histontdd[tactive] += 1 end end amrna[l] = apremid[l] + apre1[l] + afree[l] + sum(aintron[l]) # println("*",apre1) elseif r > apremid[l] # increase first pre-mRNA state # OFF state ends, ON state begins if sum(intron[l]) == 0 #&& nhist == 0 tIA[l] = t tinactive = (tIA[l] - tAI[l])/dt if tinactive <= ndt && tinactive > 0 tinactive = ceil(Int,tinactive) histofftdd[tinactive] += 1 end end z[l][1] = 1 #az[l][1] = 0 apre1[l] = 0. intron[l][1] = 1 aintron[l][1] = eta[1] if zeta == 1 #az[l][2] = nu[2] afree[l] = nu[2] else az[l][2] = float(1-z[l][2])*nu[2] apremid[l] = sum(az[l][2:zeta]) end amrna[l] = apre1[l] + apremid[l] + afree[l] + sum(aintron[l]) else # update mid pre-mRNA state azsum = az[l][2] k = 1 while r > azsum azsum += az[l][2+k] k += 1 end i = k + 1 z[l][i] = 1 z[l][i-1] = 0 az[l][i] = 0. if intron[l][i-1] == 1 intron[l][i] = 1 intron[l][i-1] = 0 aintron[l][i] = eta[i] aintron[l][i-1] = 0. else intron[l][i] = 0 aintron[l][i] = 0. end if i == zeta #az[l][i+1] = nu[i+1] afree[l] = nu[i+1] else az[l][i+1] = float(1-z[l][i+1])*nu[i+1] end if i == 2 if state[l] > mu #az[l][1] = nu[1] apre1[l] = nu[1] else az[l][1] = 0. apre1[l] = 0. end else az[l][i-1] = float(z[l][i-2])*nu[i-1] end apremid[l] = sum(az[l][2:zeta]) amrna[l] = apre1[l] + apremid[l] + afree[l] + sum(aintron[l]) end # if r > apremid[l] + apre1[l] end # if r > amrna[l] end #if r > sum(amrna + adecay) end #if asum > 0 # Compute change in histograms from last sample ts += tau if ts > tsample hoff = histofftdd/sum(histofftdd) hon = histontdd/sum(histontdd) err = max(norm(hoff-hoff0,Inf),norm(hon-hon0,Inf)) hoff0 = copy(hoff) hon0 = copy(hon) errss = norm(mhist/sum(mhist) - mhist0/sum(mhist0),Inf) err = max(err,errss) mhist0 = copy(mhist) ts = 0. end end # while bursts < nbursts && steps < total sumoff = sum(histofftdd) sumon = sum(histontdd) counts = max(sum(mhist),1) mhist /= counts # print(mproduced/t) return histofftdd/max(sumoff,1), histontdd/max(sumon,1), mhist[1:nhist], intensity end
StochasticGene
https://github.com/nih-niddk-mbs/StochasticGene.jl.git
[ "MIT" ]
1.2.5
fc1bcee6037ea393ce28426929eff65c76a86779
code
13233
# using Distributions # using StatsBase # using Statistics # using DelimitedFiles # using Dates # using Distributed # using LinearAlgebra # using Plots # using SparseArrays # using DifferentialEquations # using LSODA # using DataFrames # using FFTW # using Downloads # using CSV # using MultivariateStats # using Optim # using Test # include("common.jl") # include("transition_rate_matrices.jl") # include("chemical_master.jl") # include("simulator.jl") # include("utilities.jl") # include("metropolis_hastings.jl") # # include("trace.jl") # include("hmm.jl") # include("io.jl") # include("biowulf.jl") # include("fit.jl") # include("analysis.jl") # include("biowulf.jl") """ test(r,transitions,G,nhist,nalleles,onstates,bins) returns dwell time and mRNA histograms for simulations and chemical master equation solutions G = 2 r = [.01,.02,.03,.04,.001,.001] transitions = ([1,2],[2,1],[2,3],[3,1]) OFF,ON,mhist,modelOFF,modelON,histF = test(r,transitions,G,20,1,[2],collect(1.:200)) e.g. julia> incluce("test.jl") julia> G = 3; julia> r = [.01,.02,.03,.04,.001,.001]; julia> transitions = ([1,2],[2,1],[2,3],[3,1]); julia> onstates = [2,3] julia> OFFsim,ONsim,mRNAsim,OFFchem,ONchem,mRNAchem = test(r,transitions,G,20,1,onstates,collect(1.:200)); """ """ eg fit model to trace r = [0.05,.1,.001,.001]; transitions = ([1,2],[2,1]); G = 2; R = 0; onstates = [2]; interval = 5/3; par=[30, 14, 200, 75]; data = test_data(trace,interval); model = test_model(r,par,transitions,G,onstates); options = test_options(1000); @time fit,stats,measures = run_mh(data,model,options); """ function make_test(; G=2, R=1, S=1, insertstep=1, transitions=([1, 2], [2, 1]), rtarget=[0.02, 0.1, 0.5, 0.2, 0.1, 0.01, 50, 15, 200, 70, 0.9], rinit=[fill(0.1, num_rates(transitions, R, S, insertstep) - 1); 0.01; [20, 5, 100, 10, 0.9]], nsamples=5000, onstates=Int[], totaltime=1000.0, ntrials=10, fittedparam=[collect(1:num_rates(transitions, R, S, insertstep)-1); collect(num_rates(transitions, R, S, insertstep)+1:num_rates(transitions, R, S, insertstep)+5)], propcv=0.01, cv=100.0, interval=1.0) trace = simulate_trace_vector(rtarget, transitions, G, R, S, interval, totaltime, ntrials) data = StochasticGene.TraceData("trace", "test", interval, (trace, [], 0.)) model = load_model(data, rinit, Float64[], fittedparam, tuple(), transitions, G, R, S, insertstep, 1, 10.0, Int[], rtarget[num_rates(transitions, R, S, insertstep)], propcv, "", prob_GaussianMixture, 5, 5, tuple()) options = StochasticGene.MHOptions(nsamples, 0, 0, 100.0, 1.0, 1.0) return data, model, options end function test(; r=[0.038, 1.0, 0.23, 0.02, 0.25, 0.17, 0.02, 0.06, 0.02, 0.000231], transitions=([1, 2], [2, 1], [2, 3], [3, 1]), G=3, R=2, S=2, insertstep=1, nRNA=150, nalleles=2, bins=[collect(5/3:5/3:200), collect(5/3:5/3:200), collect(0.1:0.1:20), collect(0.1:0.1:20)], total=1000000, tol=1e-6, onstates=[Int[], Int[], [2, 3], [2, 3]], dttype=["ON", "OFF", "ONG", "OFFG"]) hs = test_sim(r, transitions, G, R, S, insertstep, nRNA, nalleles, onstates[[1, 3]], bins[[1, 3]], total, tol) h = test_chem(r, transitions, G, R, S, insertstep, nRNA, nalleles, onstates, bins, dttype) hs = StochasticGene.normalize_histogram.(hs) l = 0 for i in eachindex(h) l += StochasticGene.norm(h[i] - hs[i]) end return StochasticGene.make_array(h), StochasticGene.make_array(hs), l, isapprox(StochasticGene.make_array(h), StochasticGene.make_array(hs), rtol=0.01) end function test_chem(r, transitions, G, R, S, insertstep, nRNA, nalleles, onstates, bins, dttype) for i in eachindex(onstates) if isempty(onstates[i]) # onstates[i] = on_states(onstates[i], G, R, S, insertstep) onstates[i] = StochasticGene.on_states(G, R, S, insertstep) end onstates[i] = Int64.(onstates[i]) end components = StochasticGene.make_components_MTD(transitions, G, R, S, insertstep, onstates, dttype, nRNA, r[StochasticGene.num_rates(transitions, R, S, insertstep)], "") StochasticGene.likelihoodarray(r, G, components, bins, onstates, dttype, nalleles, nRNA) end function test_sim(r, transitions, G, R, S, insertstep, nhist, nalleles, onstates, bins, total, tol) StochasticGene.simulator(r, transitions, G, R, S, insertstep, nhist=nhist,nalleles=nalleles, onstates=onstates, bins=bins, totalsteps=total, tol=tol) end function fit_rna_test(root=".") G = 2 gene = "CENPL" cell = "HCT116" fish = false nalleles = 2 nsets = 1 propcv = 0.05 fittedparam = [1,2,3] fixedeffects = () transitions = ([1,2],[2,1]) ejectprior = 0.05 r = [0.01, 0.1, 1.0, 0.01006327034802035] decayrate = 0.01006327034802035 datacond = "MOCK" datafolder = "data/HCT116_testdata" label = "scRNA_test" data = StochasticGene.data_rna(gene,datacond,datafolder,fish,label) model = StochasticGene.model_rna(data,r,G,nalleles,nsets,propcv,fittedparam,fixedeffects,transitions,decayrate,ejectprior) options = StochasticGene.MHOptions(100000,0,0,30.,1.,100.) fit,stats,measures = StochasticGene.run_mh(data,model,options,1); return stats.meanparam, fit.llml, model end function test_fit_rna(; gene="CENPL", cell="HCT116", fish=false, G=2, nalleles=2, nunits=100000, propcv=0.05, fittedparam=[1, 2, 3], fixedeffects=tuple(), transitions=([1, 2], [2, 1]), ejectprior=0.05, r=[0.01, 0.1, 1.0, 0.01006327034802035], decayrate=0.01006327034802035, datacond="MOCK", datapath="data/HCT116_testdata", label="scRNA_test", root=".") data = load_data("rna", [], folder_path(datapath, root, "data"), label, gene, datacond, 1.0, 1.0, 1.0) model = load_model(data, r, Float64[], fittedparam, fixedeffects, transitions, G, 0, 0, 1, nalleles, 10.0, Int[], r[end], propcv, "", prob_GaussianMixture, 5, 5) options = StochasticGene.MHOptions(100000,0,0,60.,1.,1.) fits, stats, measures = run_mh(data, model, options) h = likelihoodfn(fits.parml, data, model) h,normalize_histogram(data.histRNA) end function test_fit_rnaonoff(; G=2, R=1, S=1, transitions=([1, 2], [2, 1]), insertstep=1, rtarget=[0.02, 0.1, 0.5, 0.2, 0.1, 0.01], rinit=fill(0.01, num_rates(transitions, R, S, insertstep)), nunits=100000, nhist=20, nalleles=2, onstates=Int[], bins=collect(0:1.0:200.0), fittedparam=collect(1:length(rtarget)-1), propcv=0.05, priorcv=10.0, splicetype="") # OFF, ON, mhist = test_sim(rtarget, transitions, G, R, S, nhist, nalleles, onstates, bins) h = simulator(rtarget, transitions, G, R, S, nhist, nalleles, onstates=onstates, bins=bins, totalsteps=3000) hRNA = div.(h[1], 30) data = StochasticGene.RNAOnOffData("test", "test", nhist, hRNA, bins, h[2], h[3]) model = load_model(data, rinit, Float64[], fittedparam, tuple(), transitions, G, R, S, insertstep, nalleles, priorcv, onstates, rtarget[end], propcv, splicetype, prob_GaussianMixture, 5, 5) options = StochasticGene.MHOptions(nunits, 0, 0, 100.0, 1.0, 1.0) fits, stats, measures = run_mh(data, model, options) h = likelihoodfn(fits.parml, data, model) h,StochasticGene.datapdf(data),fits, stats, measures, data, model, options end function test_fit_rnadwelltime(; rtarget=[0.038, 1.0, 0.23, 0.02, 0.25, 0.17, 0.02, 0.06, 0.02, 0.000231], transitions=([1, 2], [2, 1], [2, 3], [3, 1]), G=3, R=2, S=2, insertstep=1, nRNA=150, nunits=100000, nalleles=2, onstates=[Int[], Int[], [2, 3], [2, 3]], bins=[collect(5/3:5/3:200), collect(5/3:5/3:200), collect(0.01:0.1:10), collect(0.01:0.1:10)], dttype=["ON", "OFF", "ONG", "OFFG"], fittedparam=collect(1:length(rtarget)-1), propcv=0.01, priorcv=10.0, splicetype="") h = test_sim(rtarget, transitions, G, R, S, insertstep, nRNA, nalleles, onstates[[1, 3]], bins[[1, 3]], 30000, 1e-6) data = RNADwellTimeData("test", "test", nRNA, h[1], bins, h[2:end], dttype) println(typeof(data)) rinit = StochasticGene.prior_ratemean(transitions, R, S, insertstep, rtarget[end], 0, 0) model = load_model(data, rinit, Float64[], fittedparam, tuple(), transitions, G, R, S, insertstep, nalleles, priorcv, onstates, rtarget[end], propcv, splicetype, prob_GaussianMixture, 5, 5) options = StochasticGene.MHOptions(nunits, 1000, 0, 120.0, 1.0, 1.0) fits, stats, measures = run_mh(data, model, options, nworkers()) h = likelihoodfn(fits.parml, data, model) h,StochasticGene.datapdf(data),fits, stats, measures, data, model, options end function test_fit_trace(; G=2, R=1, S=1, insertstep=1, transitions=([1, 2], [2, 1]), rtarget=[0.02, 0.1, 0.5, 0.2, 0.1, 0.01, 50, 15, 200, 70], rinit=[fill(0.1, num_rates(transitions, R, S, insertstep) - 1); 0.01; [20, 5, 100, 10]], nsamples=5000, onstates=Int[], totaltime=1000.0, ntrials=10, fittedparam=[collect(1:num_rates(transitions, R, S, insertstep)-1); collect(num_rates(transitions, R, S, insertstep)+1:num_rates(transitions, R, S, insertstep)+4)], propcv=0.01, cv=100.0, interval=1.0, weight=0, nframes=1, noisepriors=[50, 15, 200, 70]) trace = simulate_trace_vector(rtarget, transitions, G, R, S, interval, totaltime, ntrials) data = StochasticGene.TraceData("trace", "test", interval, (trace, [], weight, nframes)) model = load_model(data, rinit, Float64[], fittedparam, tuple(), transitions, G, R, S, insertstep, 1, 10.0, Int[], rtarget[num_rates(transitions, R, S, insertstep)], propcv, "", prob_Gaussian, noisepriors, tuple()) options = StochasticGene.MHOptions(nsamples, 0, 0, 100.0, 1.0, 1.0) fits, stats, measures = run_mh(data, model, options) StochasticGene.get_rates(fits.parml, model), rtarget, fits, stats, measures,model,data end function test_init(r, transitions, G, R, S, insertstep) onstates = on_states(G, R, S, insertstep) indices = set_indices(length(transitions), R, S, insertstep) base = S > 0 ? 3 : 2 nT = G * base^R components = make_components_MTAI(transitions, G, R, S, insertstep, onstates, 2, r[num_rates(transitions, R, S, insertstep)], "") T = make_mat_T(components.tcomponents, r) TA = make_mat_TA(components.tcomponents, r) TI = make_mat_TI(components.tcomponents, r) pss = normalized_nullspace(T) nonzeros = nonzero_rows(TI) SAinit = init_SA(r, onstates, components.tcomponents.elementsT, pss) SIinit = init_SI(r, onstates, components.tcomponents.elementsT, pss, nonzeros) return SIinit, SAinit, onstates, components.tcomponents, pss, nonzeros, T, TA, TI[nonzeros, nonzeros] end function histogram_model(r, transitions, G::Int, R::Int, S::Int, insertstep::Int, nalleles::Int, nhist::Int, fittedparam, onstates, propcv, cv) ntransitions = length(transitions) if length(r) != num_rates(transitions, R, S, insertstep) throw("r does not have", num_rates(transitions, R, S, insertstep), "elements") end method = 1 if typeof(cv) <: Real rcv = fill(cv, length(r)) else rcv = cv end d = distribution_array(log.(r[fittedparam]), sigmalognormal(rcv[fittedparam]), Normal) if R > 0 components = make_components_MTAI(transitions, G, R, S, insertstep, on_states(G, R, S, insertstep), nhist, r[num_rates(transitions, R, S, insertstep)]) return GRSMmodel{typeof(r),typeof(d),typeof(propcv),typeof(fittedparam),typeof(method),typeof(components),Int}(G, R, S, nalleles, "", r, d, propcv, fittedparam, method, transitions, components, 0) else components = make_components(transitions, G, r, nhist, set_indices(ntransitions), onstates) return GMmodel{typeof(r),typeof(d),Float64,typeof(fittedparam),typeof(method),typeof(components)}(G, nalleles, r, d, proposal, fittedparam, method, transitions, components, onstates) end end function test_fit_trace_hierarchical(; G=2, R=1, S=0, insertstep=1, transitions=([1, 2], [2, 1]), rtarget=[0.02, 0.1, 0.5, 0.2, 1.0, 50, 15, 200, 70], rinit=[], nsamples=50000, onstates=Int[], totaltime=100.0, ntrials=1, fittedparam=collect(1:num_rates(transitions, R, S, insertstep)-1), propcv=0.01, cv=100.0, interval=1.0, noisepriors=[50, 15, 200, 70], hierarchical=(2, collect(num_rates(transitions, R, S, insertstep)+1:num_rates(transitions, R, S, insertstep)+ length(noisepriors)), tuple()), method=(1, true)) trace = simulate_trace_vector(rtarget, transitions, G, R, S, interval, totaltime, ntrials) data = StochasticGene.TraceData("trace", "test", interval, (trace, [], 0.0)) rm = StochasticGene.prior_ratemean(transitions, R, S, insertstep, 1.0, noisepriors, length(data.trace[1]), hierarchical[1]) isempty(rinit) && (rinit = rm) model = load_model(data, rinit, rm, fittedparam, tuple(), transitions, G, R, S, insertstep, 1, 10.0, Int[], rtarget[num_rates(transitions, R, S, insertstep)], propcv, "", prob_Gaussian, noisepriors, hierarchical, method) options = StochasticGene.MHOptions(nsamples, 0, 0, 100.0, 1.0, 1.0) fits, stats, measures = run_mh(data, model, options) nrates = num_rates(transitions, R, S, insertstep) StochasticGene.get_rates(fits.parml, model)[1:nrates], rtarget[1:nrates] end # """ # 0.006249532442813658 # 0.01590032848543878 # 3.3790567344108426 # 0.7267835250522062 # 0.0147184704573748 # 0.008557372599505498 # 61.15683730665482 # 20.930539320417463 # 254.92857617350322 # 213.0382725610589 # 0.6643622910563245 # """
StochasticGene
https://github.com/nih-niddk-mbs/StochasticGene.jl.git
[ "MIT" ]
1.2.5
fc1bcee6037ea393ce28426929eff65c76a86779
code
5329
### trace.jl """ simulate_trace_vector(r, par, transitions, G, R, onstates, interval, steps, ntrials) return vector of traces """ function simulate_trace_vector(r, transitions, G, R, S, interval, totaltime, ntrials; insertstep=1, onstates=Int[], reporterfn=sum) trace = Array{Array{Float64}}(undef, ntrials) for i in eachindex(trace) trace[i] = simulator(r[1:end-4], transitions, G, R, S, 1, 1, insertstep=insertstep, onstates=onstates, traceinterval=interval, totaltime=totaltime, par=r[end-3:end])[1:end-1, 2] end trace end """ simulate_trace(r,transitions,G,R,interval,totaltime,onstates=[G]) simulate a trace """ simulate_trace(r, transitions, G, R, S, interval, totaltime; insertstep=1, onstates=Int[], reporterfn=sum) = simulator(r, transitions, G, R, S, 2, 1, insertstep=insertstep, onstates=onstates, traceinterval=interval, reporterfn=reporterfn, totaltime=totaltime, par=r[end-4:end])[1:end-1, :] """ trace_data(trace, interval) set trace data """ function trace_data(trace, interval,nascent = 0.) if nascent > 0 return TraceNascentData("trace", "test", interval, trace, nascent) else return TraceData("trace", "test", interval, trace) end end """ trace_model(r::Vector, transitions::Tuple, G, R, fittedparam; onstates=[G], propcv=0.05, f=Normal, cv=1.) set models """ function trace_model(r::Vector, transitions::Tuple, G, R, S, insertstep, fittedparam; noiseparams=5, probfn=prob_GaussianMixture, weightind=5, propcv=0.05, priorprob=Normal, priormean=[fill(.1, num_rates(transitions, R, S, insertstep)); fill(100,noiseparams-1);.9], priorcv=[fill(10, num_rates(transitions, R, S, insertstep)); fill(.5, noiseparams)], fixedeffects=tuple(), onstates::Vector=[G],genetrap=false,nhist=20,nalleles=2) if length(r) != num_rates(transitions,R,S,insertstep) + noiseparams throw("rate wrong length") end d = trace_prior(priormean, priorcv, fittedparam, num_rates(transitions, R, S, insertstep)+weightind, priorprob) method = 1 if S > 0 S = R - insertstep + 1 end if genetrap #components = make_components_MTAI(transitions, G, R, S, insertstep, on_states(G, R, S, insertstep), nhist, r[num_rates(transitions, R, S, insertstep)]) components = make_components_MT(transitions, G, R, S, insertstep, nhist, rr[num_rates(transitions, R, S, insertstep)]) else components = make_components_T(transitions, G, R, S, insertstep, "") end # println(reporters) if R > 0 reporter = HMMReporter(noiseparams, num_reporters_per_state(G, R, S, insertstep), probfn, num_rates(transitions,R,S,insertstep) + weightind) if isempty(fixedeffects) return GRSMmodel{typeof(r),typeof(d),typeof(propcv),typeof(fittedparam),typeof(method),typeof(components),typeof(reporter)}(G, R, S, insertstep, nalleles, "", r, d, propcv, fittedparam, method, transitions, components, reporter) else return GRSMfixedeffectsmodel{typeof(r),typeof(d),typeof(propcv),typeof(fittedparam),typeof(method),typeof(components),typeof(reporter)}(G, R, S, nalleles, "", r, d, propcv, fittedparam, fixedeffects, method, transitions, components, reporter) end else return GMmodel{typeof(r),typeof(d),typeof(propcv),typeof(fittedparam),typeof(method),typeof(components)}(G, nalleles, r, d, propcv, fittedparam, method, transitions, components, onstates) end end """ trace_options(samplesteps::Int=100000, warmupsteps=0, annealsteps=0, maxtime=1000.0, temp=1.0, tempanneal=100.0) set options """ function trace_options(; samplesteps::Int=1000, warmupsteps=0, annealsteps=0, maxtime=1000.0, temp=1.0, tempanneal=1.0) MHOptions(samplesteps, warmupsteps, annealsteps, maxtime, temp, tempanneal) end """ trace_prior(r,fittedparam,f=Normal) return prior distribution """ function trace_prior(r, rcv, fittedparam, ind, f=Normal) if typeof(rcv) <: Real rcv = rcv * ones(length(r)) end distribution_array([logv(r[1:ind-1]);logit(r[ind:end])][fittedparam] , sigmalognormal(rcv[fittedparam]), f) # distribution_array(transform_array(r,ind,fittedparam,logv,logit) , sigmalognormal(rcv[fittedparam]), f) # distribution_array(mulognormal(r[fittedparam],rcv[fittedparam]), sigmalognormal(rcv[fittedparam]), f) end # """ # read_tracefiles(path::String,cond::String,col=3) # read tracefiles # """ # function read_tracefiles(path::String, cond::String, delim::AbstractChar, col=3) # readfn = delim == ',' ? read_tracefile_csv : read_tracefile # read_tracefiles(path, cond, readfn, col) # end # function read_tracefiles(path::String, cond::String="", readfn::Function=read_tracefile, col=3) # traces = Vector[] # for (root, dirs, files) in walkdir(path) # for file in files # target = joinpath(root, file) # if occursin(cond, target) # push!(traces, readfn(target, col)) # end # end # end # set = sum.(traces) # traces[unique(i -> set[i], eachindex(set))] # only return unique traces # end # """ # read_tracefile(target::String,col=3) # read single trace file # """ # read_tracefile(target::String, col=3) = readdlm(target)[:, col] # read_tracefile_csv(target::String, col=3) = readdlm(target, ',')[:, col]
StochasticGene
https://github.com/nih-niddk-mbs/StochasticGene.jl.git
[ "MIT" ]
1.2.5
fc1bcee6037ea393ce28426929eff65c76a86779
code
28675
# This file is part of StochasticGene.jl # # transition_rate_matrices_transpose.jl # # Functions to compute the transpose of the transition rate matrix for Stochastic transitions # Matrices are the transpose to the convention for Kolmogorov forward equations # i.e. reaction directions go from column to row, # Notation: M = transpose of transition rate matrix of full (countably infinite) stochastic process including mRNA kinetics # Q = finite transition rate matrix for GRS continuous Markov process # T = Q' # transpose of Q is more convenient for solving chemical master equation # """ struct Element structure for transition matrix elements fields: - `a`: row, - `b`: column - `index`: rate vector index - `pm`: sign of elements """ struct Element a::Int b::Int index::Int pm::Int end """ struct MComponents structure for matrix components for matrix M """ struct MComponents elementsT::Vector{Element} elementsB::Vector{Element} nT::Int U::SparseMatrixCSC Uminus::SparseMatrixCSC Uplus::SparseMatrixCSC end """ AbstractTComponents abstract type for components of transition matrices """ abstract type AbstractTComponents end """ struct TComponents fields: nT, elementsT """ struct TComponents <: AbstractTComponents nT::Int elementsT::Vector end """ struct TAIComponents{elementType} <: AbstractTComponents fields: nT, elementsT, elementsTA, elementsTI """ struct TAIComponents{elementType} <: AbstractTComponents nT::Int elementsT::Vector{Element} elementsTA::Vector{elementType} elementsTI::Vector{elementType} end """ struct TDComponents <: AbstractTComponents fields: nT, elementsT, elementsTD:: Vector{Vector{Element}} """ struct TDComponents <: AbstractTComponents nT::Int elementsT::Vector{Element} elementsTG::Vector{Element} elementsTD::Vector{Vector{Element}} end """ MTComponents structure for M and T components fields: mcomponents::MComponents tcomponents::TComponents """ struct MTComponents mcomponents::MComponents tcomponents::TComponents end """ MTComponents structure for M and TAI components fields: mcomponents::MComponents tcomponents::TAIComponents """ struct MTAIComponents{elementType} mcomponents::MComponents tcomponents::TAIComponents{elementType} end """ MTDComponents structure for M and TD components fields: mcomponents::MComponents tcomponents::TDComponents """ struct MTDComponents mcomponents::MComponents tcomponents::TDComponents end """ struct Indices index ranges for rates gamma: G transitions nu: R transitions eta: splice transitions decay: mRNA decay rate """ struct Indices gamma::Vector{Int} nu::Vector{Int} eta::Vector{Int} decay::Int end """ make_components_MTAI(transitions,G,R,S,insertstep,onstates,splicetype="") make MTAI structure for GRS models (fitting mRNA, on time, and off time histograms) """ function make_components_MTAI(transitions, G, R, S, insertstep, onstates, nhist, decay, splicetype="") indices = set_indices(length(transitions), R, S, insertstep) elementsT, nT = set_elements_T(transitions, G, R, S, insertstep, indices, splicetype) MTAIComponents(make_components_M(transitions, G, R, nhist, decay, splicetype), make_components_TAI(elementsT, nT, onstates)) end function make_components_MTD(transitions, G, R, S, insertstep, onstates, dttype, nhist, decay, splicetype::String="") indices = set_indices(length(transitions), R, S, insertstep) elementsT, nT = set_elements_T(transitions, G, R, S, insertstep, indices, splicetype) elementsTG = set_elements_T(transitions, indices.gamma) c = Vector{Element}[] for i in eachindex(onstates) if dttype[i] == "ON" push!(c, set_elements_TA(elementsT, onstates[i])) elseif dttype[i] == "OFF" push!(c, set_elements_TI(elementsT, onstates[i])) elseif dttype[i] == "ONG" push!(c, set_elements_TA(elementsTG, onstates[i])) elseif dttype[i] == "OFFG" push!(c, set_elements_TI(elementsTG, onstates[i])) end # dttype[i] == "ON" ? push!(c, set_elements_TA(elementsT, onstates[i])) : push!(c, set_elements_TI(elementsT, onstates[i])) end MTDComponents(make_components_M(transitions, G, R, nhist, decay, splicetype), TDComponents(nT, elementsT, elementsTG, c)) end """ make_components_MT(transitions,G,R,S,insertstep,decay,splicetype="") return MTcomponents structure for GRS models for fitting traces and mRNA histograms """ make_components_MT(transitions, G, R, S, insertstep, nhist, decay, splicetype="") = MTComponents(make_components_M(transitions, G, R, nhist, decay, splicetype), make_components_T(transitions, G, R, S, insertstep, splicetype)) """ make_components_M(transitions, G, R, insertstep, decay, splicetype) return Mcomponents structure matrix components for fitting mRNA histograms """ function make_components_M(transitions, G, R, nhist, decay, splicetype) indices = set_indices(length(transitions), R) elementsT, nT = set_elements_T(transitions, G, R, 0, 0, indices, splicetype) elementsB = set_elements_B(G, R, indices.nu[R+1]) U, Um, Up = make_mat_U(nhist, decay) return MComponents(elementsT, elementsB, nT, U, Um, Up) end """ make_components_T(transitions, G, R, S, insertstep, splicetype) return Tcomponent structure for fitting traces and also for creating TA and TI matrix components """ function make_components_T(transitions, G, R, S, insertstep, splicetype) indices = set_indices(length(transitions), R, S, insertstep) elementsT, nT = set_elements_T(transitions, G, R, S, insertstep, indices, splicetype) TComponents(nT, elementsT) end """ make_components_TAI(elementsT, nT::Int, onstates::Vector) return TAIComponent structure """ function make_components_TAI(elementsT, nT::Int, onstates::Vector) TAIComponents{Element}(nT, elementsT, set_elements_TA(elementsT, onstates), set_elements_TI(elementsT, onstates)) end # function make_components_TAI(elementsT, G::Int, R::Int, base::Int) # TAIComponents{typeof(elementsT)}(nT, elementsT, set_elements_TA(elementsT, G, R, base), set_elements_TI(elementsT, G, R, base)) # end function make_components_TAI(transitions, G, R, S, insertstep, onstates, splicetype::String="") indices = set_indices(length(transitions), R, S, insertstep) elementsT, nT = set_elements_T(transitions, G, R, S, insertstep, indices, splicetype) make_components_TAI(elementsT, nT, onstates) end """ state_index(G::Int,i,z) return state index for state (i,z) """ state_index(G::Int, g, z) = g + G * (z - 1) function inverse_state(i::Int, G, R, S, insertstep::Int, f=sum) base = S > 0 ? 3 : 2 g = mod(i - 1, G) + 1 z = div(i - g, G) + 1 zdigits = digit_vector(z, base, R) r = num_reporters_per_index(z, R, insertstep, base, f) return g, z, zdigits, r end function inverse_state(i::Vector{Int}, G, R, S, insertstep::Int) base = S > 0 ? 3 : 2 z = Int[] g = Int[] zdigits = Vector[] r = Int[] for i in i gi, zi, zdi, ri = inverse_state(i, G, R, S, insertstep) push!(z, zi) push!(g, gi) push!(zdigits, zdi) push!(r, ri) end return g, z, zdigits, r end function inverse_state(i::Vector{Vector{Int}}, G, R, S, insertstep) z = Vector{Int}[] g = Vector{Int}[] zdigits = Vector{Vector}[] r = Vector{Int}[] for i in i gi, zi, zdi, ri = inverse_state(i, G, R, S, insertstep) push!(z, zi) push!(g, gi) push!(zdigits, zdi) push!(r, ri) end return g, z, zdigits, r end """ on_states(onstates, G, R, S, insertstep) return vector of new onstates given onstates argument of fit function """ function on_states(onstates, G, R, S, insertstep) if isempty(onstates) return on_states(G, R, S, insertstep) else return on_states(onstates, G, R, S) end end """ on_states(G, R, S, insertstep) return vector of onstates for GRS model given reporter appears at insertstep """ function on_states(G::Int, R, S, insertstep) base = S > 0 ? 3 : 2 onstates = Int[] on_states!(onstates, G, R, insertstep, base) onstates end """ on_states!(onstates::Vector, G::Int, R::Int, insertstep, base) return vector of on state indices for GR and GRS models """ function on_states!(onstates::Vector, G::Int, R::Int, insertstep, base) (R == 0) && throw("Cannot use empty ON state [] for R = 0") for i in 1:G, z in 1:base^R if any(digits(z - 1, base=base, pad=R)[insertstep:end] .== base - 1) push!(onstates, state_index(G, i, z)) end end end function on_states(onstates::Vector, G, R, S) base = S > 0 ? 3 : 2 o = Int[] for i in 1:G, z in 1:base^R if i ∈ onstates push!(o, state_index(G, i, z)) end end o end function off_states(G::Int, R, S, insertstep) base = S > 0 ? 3 : 2 nT = G * base^R off_states(nT, on_states(G, R, S, insertstep)) end """ off_states(nT,onstates) return barrier (off) states, complement of sojourn (on) states """ off_states(nT, onstates) = setdiff(collect(1:nT), onstates) """ num_reporters_per_state(G::Int, R::Int, S::Int=0,insertstep=1,f=sum) return number of a vector of the number reporters for each state index if f = sum, returns total number of reporters if f = any, returns 1 for presence of any reporter """ function num_reporters_per_state(G::Int, R::Int, S::Int=0, insertstep=1, f=sum) base = S > 0 ? 3 : 2 reporters = Vector{Int}(undef, G * base^R) for i in 1:G, z in 1:base^R # reporters[state_index(G, i, z)] = f(digits(z - 1, base=base, pad=R)[insertstep:end] .== base - 1) reporters[state_index(G, i, z)] = num_reporters_per_index(z, R, insertstep, base, f) # push!(reporters, f(digits(z - 1, base=base, pad=R)[insertstep:end] .== base - 1)) end reporters end function num_reporters_per_state(G::Int, onstates::Vector) reporters = Int[] for i in 1:G push!(reporters, i ∈ onstates ? 1 : 0) end reporters end num_reporters_per_index(z, R, insertstep, base, f=sum) = f(digits(z - 1, base=base, pad=R)[insertstep:end] .== base - 1) """ set_indices(ntransitions, R, S, insertstep) set_indices(ntransitions,R) set_indices(ntransitions) return Indices structure """ function set_indices(ntransitions, R, S, insertstep) if insertstep > R > 0 throw("insertstep>R") end if S > 0 Indices(collect(1:ntransitions), collect(ntransitions+1:ntransitions+R+1), collect(ntransitions+R+2:ntransitions+R+R-insertstep+2), ntransitions + R + R - insertstep + 3) elseif R > 0 set_indices(ntransitions, R) else set_indices(ntransitions) end end set_indices(ntransitions, R) = Indices(collect(1:ntransitions), collect(ntransitions+1:ntransitions+R+1), Int[], ntransitions + R + 2) set_indices(ntransitions) = Indices(collect(1:ntransitions), [ntransitions + 1], Int[], ntransitions + 2) """ set_elements_G!(elements,transitions,G,R,base,gamma) return G transition matrix elements -`elements`: Vector of Element structures -`transitions`: tupe of G state transitions """ function set_elements_G!(elements, transitions, G::Int, gamma, nT) for j = 0:G:nT-1 set_elements_G!(elements, transitions, gamma, j) end end function set_elements_G!(elements, transitions, gamma::Vector=collect(1:length(transitions)), j=0) i = 1 for t in transitions push!(elements, Element(t[1] + j, t[1] + j, gamma[i], -1)) push!(elements, Element(t[2] + j, t[1] + j, gamma[i], 1)) i += 1 end end """ set_elements_RS!(elementsT, G, R, S, insertstep, nu::Vector{Int}, eta::Vector{Int}, splicetype="") inplace update matrix elements in elementsT for GRS state transition matrix, do nothing if R == 0 "offeject" = pre-RNA is completely ejected when spliced """ function set_elements_RS!(elementsT, G, R, S, insertstep, nu::Vector{Int}, eta::Vector{Int}, splicetype="") if R > 0 if splicetype == "offeject" S = 0 base = 2 end if S == 0 base = 2 else base = 3 end for w = 1:base^R, z = 1:base^R zdigits = digit_vector(z, base, R) wdigits = digit_vector(w, base, R) z1 = zdigits[1] w1 = wdigits[1] zr = zdigits[R] wr = wdigits[R] zbar1 = zdigits[2:R] wbar1 = wdigits[2:R] zbarr = zdigits[1:R-1] wbarr = wdigits[1:R-1] sB = 0 for l in 1:base-1 sB += (zbarr == wbarr) * ((zr == 0) - (zr == l)) * (wr == l) end if S > 0 sC = (zbarr == wbarr) * ((zr == 1) - (zr == 2)) * (wr == 2) end for i = 1:G # a = i + G * (z - 1) # b = i + G * (w - 1) a = state_index(G, i, z) b = state_index(G, i, w) if abs(sB) == 1 push!(elementsT, Element(a, b, nu[R+1], sB)) end if S > 0 && abs(sC) == 1 push!(elementsT, Element(a, b, eta[R-insertstep+1], sC)) end if splicetype == "offeject" s = (zbarr == wbarr) * ((zr == 0) - (zr == 1)) * (wr == 1) if abs(s) == 1 push!(elementsT, Element(a, b, eta[R-insertstep+1], s)) end end for j = 1:R-1 zbarj = zdigits[[1:j-1; j+2:R]] wbarj = wdigits[[1:j-1; j+2:R]] zbark = zdigits[[1:j-1; j+1:R]] wbark = wdigits[[1:j-1; j+1:R]] zj = zdigits[j] zj1 = zdigits[j+1] wj = wdigits[j] wj1 = wdigits[j+1] s = 0 for l in 1:base-1 s += (zbarj == wbarj) * ((zj == 0) * (zj1 == l) - (zj == l) * (zj1 == 0)) * (wj == l) * (wj1 == 0) end if abs(s) == 1 push!(elementsT, Element(a, b, nu[j+1], s)) end if S > 0 && j > insertstep - 1 s = (zbark == wbark) * ((zj == 1) - (zj == 2)) * (wj == 2) if abs(s) == 1 push!(elementsT, Element(a, b, eta[j-insertstep+1], s)) end end if splicetype == "offeject" && j > insertstep - 1 s = (zbark == wbark) * ((zj == 0) - (zj == 1)) * (wj == 1) if abs(s) == 1 push!(elementsT, Element(a, b, eta[j-insertstep+1], s)) end end end end s = (zbar1 == wbar1) * ((z1 == base - 1) - (z1 == 0)) * (w1 == 0) if abs(s) == 1 push!(elementsT, Element(G * z, G * w, nu[1], s)) end end end end """ set_elements_TA(elementsT,onstates) set onstate elements """ set_elements_TA(elementsT, onstates) = set_elements_TX(elementsT, onstates, set_elements_TA!) """ set_elements_TA!(elementsTA, elementsT, onstates::Vector) in place set onstate elements """ set_elements_TA!(elementsTA, elementsT, onstates) = set_elements_TX!(elementsTA, elementsT, onstates, ∈) """ set_elements_TI!(elementsTI, elementsT, onstates::Vector) set off state elements """ set_elements_TI(elementsT, onstates) = set_elements_TX(elementsT, onstates, set_elements_TI!) """ set_elements_TI!(elementsTI, elementsT, onstates::Vector) in place set off state elements """ set_elements_TI!(elementsTI, elementsT, onstates) = set_elements_TX!(elementsTI, elementsT, onstates, βˆ‰) """ set_elements_TX(elementsT, onstates::Vector{Int},f!) set on or off state elements for onstates """ function set_elements_TX(elementsT, onstates::Vector{Int}, f!) elementsTX = Vector{Element}(undef, 0) f!(elementsTX, elementsT, onstates::Vector) elementsTX end """ set_elements_TX(elementsT, onstates::Vector{Vector{Int}},f!) set on or off state elements for vector if onstates by calling f! (set_elements_TA! or set_elements_TI!) """ function set_elements_TX(elementsT, onstates::Vector{Vector{Int}}, f!) elementsTX = Vector{Vector{Element}}(undef, length(onstates)) for i in eachindex(onstates) eTX = Vector{Element}(undef, 0) f!(eTX, elementsT, onstates::Vector) elementsTX[i] = eTX end elementsTX end """ set_elements_TX!(elementsTX, elementsT, onstates::Vector,f) add elements to elementsTX if column element satisfies f (∈ or βˆ‰) """ function set_elements_TX!(elementsTX, elementsT, onstates::Vector, f) for e in elementsT if f(e.b, onstates) push!(elementsTX, e) end end end """ set_elements_T(transitions, G, R, S, indices::Indices, splicetype::String) return T matrix elements (Element structure) and size of matrix """ function set_elements_T(transitions, G, R, S, insertstep, indices::Indices, splicetype::String) if R > 0 elementsT = Vector{Element}(undef, 0) base = S > 0 ? 3 : 2 nT = G * base^R set_elements_G!(elementsT, transitions, G, indices.gamma, nT) set_elements_RS!(elementsT, G, R, S, insertstep, indices.nu, indices.eta, splicetype) return elementsT, nT else return set_elements_T(transitions, indices.gamma), G end end function set_elements_T(transitions, gamma::Vector) elementsT = Vector{Element}(undef, 0) set_elements_G!(elementsT, transitions, gamma) elementsT end """ set_elements_B(G, ejectindex) return B matrix elements """ set_elements_B(G, ejectindex) = [Element(G, G, ejectindex, 1)] function set_elements_B(G, R, ejectindex, base=2) if R > 0 elementsB = Vector{Element}(undef, 0) for w = 1:base^R, z = 1:base^R, i = 1:G a = i + G * (z - 1) b = i + G * (w - 1) zdigits = digits(z - 1, base=base, pad=R) wdigits = digits(w - 1, base=base, pad=R) zr = zdigits[R] wr = wdigits[R] zbarr = zdigits[1:R-1] wbarr = wdigits[1:R-1] s = (zbarr == wbarr) * (zr == 0) * (wr == 1) if abs(s) == 1 push!(elementsB, Element(a, b, ejectindex, s)) end end return elementsB else set_elements_B(G, ejectindex) end end """ make_mat!(T::AbstractMatrix,elements::Vector,rates::Vector) set matrix elements of T to those in vector argument elements """ function make_mat!(T::AbstractMatrix, elements::Vector, rates::Vector) for e in elements T[e.a, e.b] += e.pm * rates[e.index] end end """ make_mat(elements,rates,nT) return an nTxnT sparse matrix T """ function make_mat(elements::Vector, rates::Vector, nT::Int) T = spzeros(nT, nT) make_mat!(T, elements, rates) return T end """ make_S_mat """ function make_mat_U(total::Int, decay::Float64) U = spzeros(total, total) Uminus = spzeros(total, total) Uplus = spzeros(total, total) # Generate matrices for m transitions Uplus[1, 2] = decay for m = 2:total-1 U[m, m] = -decay * (m - 1) Uminus[m, m-1] = 1 Uplus[m, m+1] = decay * m end U[total, total] = -decay * (total - 1) Uminus[total, total-1] = 1 return U, Uminus, Uplus end """ make_M_mat return M matrix used to compute steady state RNA distribution """ function make_mat_M(T::SparseMatrixCSC, B::SparseMatrixCSC, decay::Float64, total::Int) U, Uminus, Uplus = make_mat_U(total, decay) make_mat_M(T, B, U, Uminus, Uplus) end function make_mat_M(T::SparseMatrixCSC, B::SparseMatrixCSC, U::SparseMatrixCSC, Uminus::SparseMatrixCSC, Uplus::SparseMatrixCSC) nT = size(T, 1) total = size(U, 1) M = kron(U, sparse(I, nT, nT)) + kron(sparse(I, total, total), T - B) + kron(Uminus, B) + kron(Uplus, sparse(I, nT, nT)) M[end-size(B, 1)+1:end, end-size(B, 1)+1:end] .+= B # boundary condition to ensure probability is conserved return M end function make_mat_M(components::MComponents, rates::Vector) T = make_mat(components.elementsT, rates, components.nT) B = make_mat(components.elementsB, rates, components.nT) make_mat_M(T, B, components.U, components.Uminus, components.Uplus) end """ make_T_mat construct matrices from elements """ make_mat_T(components::AbstractTComponents, rates) = make_mat(components.elementsT, rates, components.nT) make_mat_TA(components::TAIComponents, rates) = make_mat(components.elementsTA, rates, components.nT) make_mat_TI(components::TAIComponents, rates) = make_mat(components.elementsTI, rates, components.nT) make_mat_TA(elementsTA, rates, nT) = make_mat(elementsTA, rates, nT) make_mat_TI(elementsTI, rates, nT) = make_mat(elementsTI, rates, nT) function make_mat_GR(components, rates) nG = components.nG nR = components.nR G = make_mat(components.elementsG, rates, nG) R = make_mat(components.elementsR, rates, nR) RB = make_mat(components.elementsRB, rates, nR) G, R, RB end ##### Coupling Under development struct T2Components <: AbstractTComponents nG::Int nR::Int elementsG::Vector elementsR::Vector elementsRG::Vector end struct M2Components nG::Int nR::Int elementsG::Vector elementsRG::Vector elementsR::Vector elementsB::Vector{Element} U::SparseMatrixCSC Uminus::SparseMatrixCSC Uplus::SparseMatrixCSC end struct MT2Components mcomponents::M2Components tcomponents::T2Components end function set_elements_RS2!(elementsRG, elementsR, R, S, insertstep, nu::Vector{Int}, eta::Vector{Int}, splicetype="") if R > 0 if splicetype == "offeject" S = 0 base = 2 end if S == 0 base = 2 else base = 3 end for b = 1:base^R, a = 1:base^R zdigits = digit_vector(a, base, R) wdigits = digit_vector(b, base, R) z1 = zdigits[1] w1 = wdigits[1] zr = zdigits[R] wr = wdigits[R] zbar1 = zdigits[2:R] wbar1 = wdigits[2:R] zbarr = zdigits[1:R-1] wbarr = wdigits[1:R-1] sB = 0 for l in 1:base-1 sB += (zbarr == wbarr) * ((zr == 0) - (zr == l)) * (wr == l) end if S > 0 sC = (zbarr == wbarr) * ((zr == 1) - (zr == 2)) * (wr == 2) end if abs(sB) == 1 push!(elementsR, Element(a, b, nu[R+1], sB)) end if S > 0 && abs(sC) == 1 push!(elementsR, Element(a, b, eta[R-insertstep+1], sC)) end if splicetype == "offeject" s = (zbarr == wbarr) * ((zr == 0) - (zr == 1)) * (wr == 1) if abs(s) == 1 push!(elementsR, Element(a, b, eta[R-insertstep+1], s)) end end for j = 1:R-1 zbarj = zdigits[[1:j-1; j+2:R]] wbarj = wdigits[[1:j-1; j+2:R]] zbark = zdigits[[1:j-1; j+1:R]] wbark = wdigits[[1:j-1; j+1:R]] zj = zdigits[j] zj1 = zdigits[j+1] wj = wdigits[j] wj1 = wdigits[j+1] s = 0 for l in 1:base-1 s += (zbarj == wbarj) * ((zj == 0) * (zj1 == l) - (zj == l) * (zj1 == 0)) * (wj == l) * (wj1 == 0) end if abs(s) == 1 push!(elementsR, Element(a, b, nu[j+1], s)) end if S > 0 && j > insertstep - 1 s = (zbark == wbark) * ((zj == 1) - (zj == 2)) * (wj == 2) if abs(s) == 1 push!(elementsR, Element(a, b, eta[j-insertstep+1], s)) end end if splicetype == "offeject" && j > insertstep - 1 s = (zbark == wbark) * ((zj == 0) - (zj == 1)) * (wj == 1) if abs(s) == 1 push!(elementsR, Element(a, b, eta[j-insertstep+1], s)) end end end s = (zbar1 == wbar1) * ((z1 == base - 1) - (z1 == 0)) * (w1 == 0) if abs(s) == 1 push!(elementsRG, Element(a, b, nu[1], s)) end end end end function set_elements_G2!(elements, transitions, gamma::Vector=collect(1:length(transitions)), j=0) i = 1 for t in transitions if x push!(elements, Element(t[1] + j, t[1] + j, gamma[i], -1)) push!(elements, Element(t[2] + j, t[1] + j, gamma[i], 1)) i += 1 end end end function set_elements_B2(G, R, ejectindex, base=2) if R > 0 nR = base^R elementsB = Vector{Element}(undef, 0) for b = 1:nR, a = 1:nR zdigits = digits(a - 1, base=base, pad=R) wdigits = digits(b - 1, base=base, pad=R) zr = zdigits[R] wr = wdigits[R] zbarr = zdigits[1:R-1] wbarr = wdigits[1:R-1] s = (zbarr == wbarr) * (zr == 0) * (wr == 1) if abs(s) == 1 push!(elementsB, Element(a, b, ejectindex, s)) end end return elementsB else set_elements_B(G, ejectindex) end end function set_elements_T2(transitions, G, R, S, insertstep, indices::Indices, splicetype::String) if R > 0 elementsG = Vector{Element}(undef, 0) elementsR = Vector{Element}(undef, 0) elementsRG = Vector{Element}(undef, 0) base = S > 0 ? 3 : 2 nR = base^R set_elements_G!(elementsG, transitions) set_elements_RS2!(elementsRG, elementsR, R, S, insertstep, indices.nu, indices.eta, splicetype) return elementsG, elementsRG, elementsR, nR else return set_elements_G(transitions, indices.gamma), G end end function make_components_T2(transitions, G, R, S, insertstep, splicetype) indices = set_indices(length(transitions), R, S, insertstep) elementsG, elementsRG, elementsR, nR = set_elements_T2(transitions, G, R, S, insertstep, indices, splicetype) T2Components(G, nR, elementsG, elementsR, elementsRG) end function make_components_M2(transitions, G, R, nhist, decay) indices = set_indices(length(transitions), R) elementsG, elementsRG, elementsR, nR = set_elements_T2(transitions, G, R, 0, 1, indices, "") elementsB = set_elements_B2(G, R, indices.nu[R+1]) U, Um, Up = make_mat_U(nhist, decay) M2Components(G, nR, elementsG, elementsRG, elementsR, elementsB, U, Um, Up) end make_components_MT2(transitions, G, R, S, insertstep, nhist, decay, splicetype="") = MT2Components(make_components_M2(transitions, G, R, nhist, decay), make_components_T2(transitions, G, R, S, insertstep, splicetype)) function make_mat_T2(components, rates) nG = components.nG nR = components.nR GR = spzeros(nG, nG) GR[nG, nG] = 1.0 G = make_mat(components.elementsG, rates, nG) R = make_mat(components.elementsR, rates, nR) RG = make_mat(components.elementsRG, rates, nR) make_mat_T2(G, GR, R, RG, nG, nR) end function make_mat_T2(G, GR, R, RG, nG, nR) kron(RG, GR) + kron(sparse(I, nR, nR), G) + kron(R, sparse(I, nG, nG)) end function make_mat_B2(components, rates) RB = make_mat(components.elementsB, rates, components.nR) nG = components.nG kron(RB, sparse(I, nG, nG)) end function make_mat_M2(components::M2Components, rates::Vector) T = make_mat_T2(components, rates) B = make_mat_B2(components, rates) make_mat_M(T, B, components.U, components.Uminus, components.Uplus) end function test_mat2(r, transitions, G, R, S, insertstep, nhist=20) components = make_components_MT2(transitions, G, R, S, insertstep, nhist, 1.01, "") T = make_mat_T2(components.tcomponents, r) M = make_mat_M2(components.mcomponents, r) return T, M, components end function test_mat(r, transitions, G, R, S, insertstep, nhist=20) components = make_components_MT(transitions, G, R, S, insertstep, nhist, 1.01, "") T = make_mat_T(components.tcomponents, r) M = make_mat_M(components.mcomponents, r) T, M, components end
StochasticGene
https://github.com/nih-niddk-mbs/StochasticGene.jl.git
[ "MIT" ]
1.2.5
fc1bcee6037ea393ce28426929eff65c76a86779
code
25418
# This file is part of StochasticGene.jl # # transition_rate_matrices_transpose.jl # # Functions to compute the transpose of the transition rate matrix for Stochastic transitions # Matrices are the transpose to the convention for Kolmogorov forward equations # i.e. reaction directions go from column to row, # Notation: M = transpose of transition rate matrix of full (countably infinite) stochastic process including mRNA kinetics # Q = finite transition rate matrix for GRS continuous Markov process # T = Q' # transpose of Q is more convenient for solving chemical master equation # """ struct Element structure for transition matrix elements fields: - `a`: row, - `b`: column - `index`: rate vector index - `pm`: sign of elements """ struct Element a::Int b::Int index::Int pm::Int end """ struct MComponents structure for matrix components for matrix M """ struct MComponents elementsT::Vector{Element} elementsB::Vector{Element} nT::Int U::SparseMatrixCSC Uminus::SparseMatrixCSC Uplus::SparseMatrixCSC end """ AbstractTComponents abstract type for components of transition matrices """ abstract type AbstractTComponents end """ struct TComponents fields: nT, elementsT """ struct TComponents <: AbstractTComponents nT::Int elementsT::Vector end struct T2Components <: AbstractTComponents nG::Int nR::Int elementsG::Vector elementsR::Vector elementsRG::Vector elementsRB::Vector end """ struct TAIComponents{elementType} <: AbstractTComponents fields: nT, elementsT, elementsTA, elementsTI """ struct TAIComponents{elementType} <: AbstractTComponents nT::Int elementsT::Vector{Element} elementsTA::Vector{elementType} elementsTI::Vector{elementType} end """ struct TDComponents <: AbstractTComponents fields: nT, elementsT, elementsTD:: Vector{Vector{Element}} """ struct TDComponents <: AbstractTComponents nT::Int elementsT::Vector{Element} elementsTG::Vector{Element} elementsTD::Vector{Vector{Element}} end """ MTComponents structure for M and T components fields: mcomponents::MComponents tcomponents::TComponents """ struct MTComponents mcomponents::MComponents tcomponents::TComponents end """ MTComponents structure for M and TAI components fields: mcomponents::MComponents tcomponents::TAIComponents """ struct MTAIComponents{elementType} mcomponents::MComponents tcomponents::TAIComponents{elementType} end """ MTDComponents structure for M and TD components fields: mcomponents::MComponents tcomponents::TDComponents """ struct MTDComponents mcomponents::MComponents tcomponents::TDComponents end """ struct Indices index ranges for rates gamma: G transitions nu: R transitions eta: splice transitions decay: mRNA decay rate """ struct Indices gamma::Vector{Int} nu::Vector{Int} eta::Vector{Int} decay::Int end """ make_components_MTAI(transitions,G,R,S,insertstep,onstates,splicetype="") make MTAI structure for GRS models (fitting mRNA, on time, and off time histograms) """ function make_components_MTAI(transitions, G, R, S, insertstep, onstates, nhist, decay, splicetype="") indices = set_indices(length(transitions), R, S, insertstep) elementsT, nT = set_elements_T(transitions, G, R, S, insertstep, indices, splicetype) MTAIComponents(make_components_M(transitions, G, R, nhist, decay, splicetype), make_components_TAI(elementsT, nT, onstates)) end function make_components_MTD(transitions, G, R, S, insertstep, onstates, dttype, nhist, decay, splicetype::String="") indices = set_indices(length(transitions), R, S, insertstep) elementsT, nT = set_elements_T(transitions, G, R, S, insertstep, indices, splicetype) elementsTG = set_elements_T(transitions, indices.gamma) c = Vector{Element}[] for i in eachindex(onstates) if dttype[i] == "ON" push!(c, set_elements_TA(elementsT, onstates[i])) elseif dttype[i] == "OFF" push!(c, set_elements_TI(elementsT, onstates[i])) elseif dttype[i] == "ONG" push!(c, set_elements_TA(elementsTG, onstates[i])) elseif dttype[i] == "OFFG" push!(c, set_elements_TI(elementsTG, onstates[i])) end # dttype[i] == "ON" ? push!(c, set_elements_TA(elementsT, onstates[i])) : push!(c, set_elements_TI(elementsT, onstates[i])) end MTDComponents(make_components_M(transitions, G, R, nhist, decay, splicetype), TDComponents(nT, elementsT, elementsTG, c)) end """ make_components_MT(transitions,G,R,S,insertstep,decay,splicetype="") return MTcomponents structure for GRS models for fitting traces and mRNA histograms """ make_components_MT(transitions, G, R, S, insertstep, nhist, decay, splicetype="") = MTComponents(make_components_M(transitions, G, R, nhist, decay, splicetype), make_components_T(transitions, G, R, S, insertstep, splicetype)) """ make_components_M(transitions, G, R, insertstep, decay, splicetype) return Mcomponents structure matrix components for fitting mRNA histograms """ function make_components_M(transitions, G, R, nhist, decay, splicetype) indices = set_indices(length(transitions), R) elementsT, nT = set_elements_T(transitions, G, R, 0, 0, indices, splicetype) elementsB = set_elements_B(G, R, indices.nu[R+1]) U, Um, Up = make_mat_U(nhist, decay) return MComponents(elementsT, elementsB, nT, U, Um, Up) end """ make_components_T(transitions, G, R, S, insertstep, splicetype) return Tcomponent structure for fitting traces and also for creating TA and TI matrix components """ function make_components_T(transitions, G, R, S, insertstep, splicetype) indices = set_indices(length(transitions), R, S, insertstep) elementsT, nT = set_elements_T(transitions, G, R, S, insertstep, indices, splicetype) TComponents(nT, elementsT) end """ make_components_TAI(elementsT, nT::Int, onstates::Vector) return TAIComponent structure """ function make_components_TAI(elementsT, nT::Int, onstates::Vector) TAIComponents{Element}(nT, elementsT, set_elements_TA(elementsT, onstates), set_elements_TI(elementsT, onstates)) end # function make_components_TAI(elementsT, G::Int, R::Int, base::Int) # TAIComponents{typeof(elementsT)}(nT, elementsT, set_elements_TA(elementsT, G, R, base), set_elements_TI(elementsT, G, R, base)) # end function make_components_TAI(transitions, G, R, S, insertstep, onstates, splicetype::String="") indices = set_indices(length(transitions), R, S, insertstep) elementsT, nT = set_elements_T(transitions, G, R, S, insertstep, indices, splicetype) make_components_TAI(elementsT, nT, onstates) end """ state_index(G::Int,i,z) return state index for state (i,z) """ state_index(G::Int, i, z) = i + G * (z - 1) function on_states(onstates, G, R, S, insertstep) if isempty(onstates) return on_states(G, R, S, insertstep) else return on_states(onstates, G, R, S) end end """ on_states(G, R, S, insertstep) return vector of onstates for GRS model given reporter appears at insertstep """ function on_states(G::Int, R, S, insertstep) base = S > 0 ? 3 : 2 onstates = Int[] on_states!(onstates, G, R, insertstep, base) onstates end """ on_states!(onstates::Vector, G::Int, R::Int, insertstep, base) return vector of on state indices for GR and GRS models """ function on_states!(onstates::Vector, G::Int, R::Int, insertstep, base) for i in 1:G, z in 1:base^R if any(digits(z - 1, base=base, pad=R)[insertstep:end] .== base - 1) push!(onstates, state_index(G, i, z)) end end end function on_states(onstates::Vector, G, R, S) base = S > 0 ? 3 : 2 o = Int[] for i in 1:G, z in 1:base^R if i ∈ onstates push!(o, state_index(G, i, z)) end end o end """ off_states(nT,onstates) return barrier (off) states, complement of sojourn (on) states """ off_states(nT, onstates) = setdiff(collect(1:nT), onstates) """ num_reporters_per_state(G::Int, R::Int, S::Int=0,insertstep=1,f=sum) return number of a vector of the number reporters for each state index if f = sum, returns total number of reporters if f = any, returns 1 for presence of any reporter """ function num_reporters_per_state(G::Int, R::Int, S::Int=0, insertstep=1, f=sum) base = S > 0 ? 3 : 2 reporters = Vector{Int}(undef, G * base^R) for i in 1:G, z in 1:base^R reporters[state_index(G, i, z)] = f(digits(z - 1, base=base, pad=R)[insertstep:end] .== base - 1) # push!(reporters, f(digits(z - 1, base=base, pad=R)[insertstep:end] .== base - 1)) end reporters end function num_reporters_per_state(G::Int, onstates::Vector) reporters = Int[] for i in 1:G push!(reporters, i ∈ onstates ? 1 : 0) end reporters end """ set_indices(ntransitions, R, S, insertstep) set_indices(ntransitions,R) set_indices(ntransitions) return Indices structure """ function set_indices(ntransitions, R, S, insertstep) if insertstep > R > 0 throw("insertstep>R") end if S > 0 Indices(collect(1:ntransitions), collect(ntransitions+1:ntransitions+R+1), collect(ntransitions+R+2:ntransitions+R+R-insertstep+2), ntransitions + R + R - insertstep + 3) elseif R > 0 set_indices(ntransitions, R) else set_indices(ntransitions) end end set_indices(ntransitions, R) = Indices(collect(1:ntransitions), collect(ntransitions+1:ntransitions+R+1), Int[], ntransitions + R + 2) set_indices(ntransitions) = Indices(collect(1:ntransitions), [ntransitions + 1], Int[], ntransitions + 2) """ set_elements_G!(elements,transitions,G,R,base,gamma) return G transition matrix elements -`elements`: Vector of Element structures -`transitions`: tupe of G state transitions """ function set_elements_G!(elements, transitions, G::Int, gamma, nT) for j = 0:G:nT-1 set_elements_G!(elements, transitions, gamma, j) end end function set_elements_G!(elements, transitions, gamma::Vector=collect(1:length(transitions)), j=0) i = 1 for t in transitions push!(elements, Element(t[1] + j, t[1] + j, gamma[i], -1)) push!(elements, Element(t[2] + j, t[1] + j, gamma[i], 1)) i += 1 end end function set_elements_RS!(elementsRG, elementsR, elementsRM, R, S, insertstep, nu::Vector{Int}, eta::Vector{Int}, splicetype="") if R > 0 if splicetype == "offeject" S = 0 base = 2 end if S == 0 base = 2 else base = 3 end for w = 1:base^R, z = 1:base^R zdigits = digit_vector(z, base, R) wdigits = digit_vector(w, base, R) z1 = zdigits[1] w1 = wdigits[1] zr = zdigits[R] wr = wdigits[R] zbar1 = zdigits[2:R] wbar1 = wdigits[2:R] zbarr = zdigits[1:R-1] wbarr = wdigits[1:R-1] sB = 0 for l in 1:base-1 sB += (zbarr == wbarr) * ((zr == 0) - (zr == l)) * (wr == l) end if S > 0 sC = (zbarr == wbarr) * ((zr == 1) - (zr == 2)) * (wr == 2) end for i = 1:1 # a = i + G * (z - 1) # b = i + G * (w - 1) a = state_index(1, i, z) b = state_index(1, i, w) if abs(sB) == 1 push!(elementsRM, Element(a, b, nu[R+1], sB)) end if S > 0 && abs(sC) == 1 push!(elementsR, Element(a, b, eta[R-insertstep+1], sC)) end if splicetype == "offeject" s = (zbarr == wbarr) * ((zr == 0) - (zr == 1)) * (wr == 1) if abs(s) == 1 push!(elementsR, Element(a, b, eta[R-insertstep+1], s)) end end for j = 1:R-1 zbarj = zdigits[[1:j-1; j+2:R]] wbarj = wdigits[[1:j-1; j+2:R]] zbark = zdigits[[1:j-1; j+1:R]] wbark = wdigits[[1:j-1; j+1:R]] zj = zdigits[j] zj1 = zdigits[j+1] wj = wdigits[j] wj1 = wdigits[j+1] s = 0 for l in 1:base-1 s += (zbarj == wbarj) * ((zj == 0) * (zj1 == l) - (zj == l) * (zj1 == 0)) * (wj == l) * (wj1 == 0) end if abs(s) == 1 push!(elementsR, Element(a, b, nu[j+1], s)) end if S > 0 && j > insertstep - 1 s = (zbark == wbark) * ((zj == 1) - (zj == 2)) * (wj == 2) if abs(s) == 1 push!(elementsR, Element(a, b, eta[j-insertstep+1], s)) end end if splicetype == "offeject" && j > insertstep - 1 s = (zbark == wbark) * ((zj == 0) - (zj == 1)) * (wj == 1) if abs(s) == 1 push!(elementsR, Element(a, b, eta[j-insertstep+1], s)) end end end end s = (zbar1 == wbar1) * ((z1 == base - 1) - (z1 == 0)) * (w1 == 0) if abs(s) == 1 push!(elementsRG, Element(z, w, nu[1], s)) end end end end """ set_elements_RS!(elementsT, G, R, S, insertstep, nu::Vector{Int}, eta::Vector{Int}, splicetype="") inplace update matrix elements in elementsT for GRS state transition matrix, do nothing if R == 0 "offeject" = pre-RNA is completely ejected when spliced """ function set_elements_RS!(elementsT, G, R, S, insertstep, nu::Vector{Int}, eta::Vector{Int}, splicetype="") if R > 0 if splicetype == "offeject" S = 0 base = 2 end if S == 0 base = 2 else base = 3 end for w = 1:base^R, z = 1:base^R zdigits = digit_vector(z, base, R) wdigits = digit_vector(w, base, R) z1 = zdigits[1] w1 = wdigits[1] zr = zdigits[R] wr = wdigits[R] zbar1 = zdigits[2:R] wbar1 = wdigits[2:R] zbarr = zdigits[1:R-1] wbarr = wdigits[1:R-1] sB = 0 for l in 1:base-1 sB += (zbarr == wbarr) * ((zr == 0) - (zr == l)) * (wr == l) end if S > 0 sC = (zbarr == wbarr) * ((zr == 1) - (zr == 2)) * (wr == 2) end for i = 1:G # a = i + G * (z - 1) # b = i + G * (w - 1) a = state_index(G, i, z) b = state_index(G, i, w) if abs(sB) == 1 push!(elementsT, Element(a, b, nu[R+1], sB)) end if S > 0 && abs(sC) == 1 push!(elementsT, Element(a, b, eta[R-insertstep+1], sC)) end if splicetype == "offeject" s = (zbarr == wbarr) * ((zr == 0) - (zr == 1)) * (wr == 1) if abs(s) == 1 push!(elementsT, Element(a, b, eta[R-insertstep+1], s)) end end for j = 1:R-1 zbarj = zdigits[[1:j-1; j+2:R]] wbarj = wdigits[[1:j-1; j+2:R]] zbark = zdigits[[1:j-1; j+1:R]] wbark = wdigits[[1:j-1; j+1:R]] zj = zdigits[j] zj1 = zdigits[j+1] wj = wdigits[j] wj1 = wdigits[j+1] s = 0 for l in 1:base-1 s += (zbarj == wbarj) * ((zj == 0) * (zj1 == l) - (zj == l) * (zj1 == 0)) * (wj == l) * (wj1 == 0) end if abs(s) == 1 push!(elementsT, Element(a, b, nu[j+1], s)) end if S > 0 && j > insertstep - 1 s = (zbark == wbark) * ((zj == 1) - (zj == 2)) * (wj == 2) if abs(s) == 1 push!(elementsT, Element(a, b, eta[j-insertstep+1], s)) end end if splicetype == "offeject" && j > insertstep - 1 s = (zbark == wbark) * ((zj == 0) - (zj == 1)) * (wj == 1) if abs(s) == 1 push!(elementsT, Element(a, b, eta[j-insertstep+1], s)) end end end end s = (zbar1 == wbar1) * ((z1 == base - 1) - (z1 == 0)) * (w1 == 0) if abs(s) == 1 push!(elementsT, Element(G * z, G * w, nu[1], s)) end end end end """ set_elements_TA(elementsT,onstates) set onstate elements """ set_elements_TA(elementsT, onstates) = set_elements_TX(elementsT, onstates, set_elements_TA!) """ set_elements_TA!(elementsTA, elementsT, onstates::Vector) in place set onstate elements """ set_elements_TA!(elementsTA, elementsT, onstates) = set_elements_TX!(elementsTA, elementsT, onstates, ∈) """ set_elements_TI!(elementsTI, elementsT, onstates::Vector) set off state elements """ set_elements_TI(elementsT, onstates) = set_elements_TX(elementsT, onstates, set_elements_TI!) """ set_elements_TI!(elementsTI, elementsT, onstates::Vector) in place set off state elements """ set_elements_TI!(elementsTI, elementsT, onstates) = set_elements_TX!(elementsTI, elementsT, onstates, βˆ‰) """ set_elements_TX(elementsT, onstates::Vector{Int},f!) set on or off state elements for onstates """ function set_elements_TX(elementsT, onstates::Vector{Int}, f!) elementsTX = Vector{Element}(undef, 0) f!(elementsTX, elementsT, onstates::Vector) elementsTX end """ set_elements_TX(elementsT, onstates::Vector{Vector{Int}},f!) set on or off state elements for vector if onstates by calling f! (set_elements_TA! or set_elements_TI!) """ function set_elements_TX(elementsT, onstates::Vector{Vector{Int}}, f!) elementsTX = Vector{Vector{Element}}(undef, length(onstates)) for i in eachindex(onstates) eTX = Vector{Element}(undef, 0) f!(eTX, elementsT, onstates::Vector) elementsTX[i] = eTX end elementsTX end """ set_elements_TX!(elementsTX, elementsT, onstates::Vector,f) add elements to elementsTX if column element satisfies f (∈ or βˆ‰) """ function set_elements_TX!(elementsTX, elementsT, onstates::Vector, f) for e in elementsT if f(e.b, onstates) push!(elementsTX, e) end end end """ set_elements_T(transitions, G, R, S, indices::Indices, splicetype::String) return T matrix elements (Element structure) and size of matrix """ function set_elements_T(transitions, G, R, S, insertstep, indices::Indices, splicetype::String) if R > 0 elementsT = Vector{Element}(undef, 0) base = S > 0 ? 3 : 2 nT = G * base^R set_elements_G!(elementsT, transitions, G, indices.gamma, nT) set_elements_RS!(elementsT, G, R, S, insertstep, indices.nu, indices.eta, splicetype) return elementsT, nT else return set_elements_T(transitions, indices.gamma), G end end function set_elements_T(transitions, gamma::Vector) elementsT = Vector{Element}(undef, 0) set_elements_G!(elementsT, transitions, gamma) elementsT end """ set_elements_B(G, ejectindex) return B matrix elements """ set_elements_B(G, ejectindex) = [Element(G, G, ejectindex, 1)] function set_elements_B(G, R, ejectindex, base=2) if R > 0 elementsB = Vector{Element}(undef, 0) for w = 1:base^R, z = 1:base^R, i = 1:G a = i + G * (z - 1) b = i + G * (w - 1) zdigits = digits(z - 1, base=base, pad=R) wdigits = digits(w - 1, base=base, pad=R) zr = zdigits[R] wr = wdigits[R] zbarr = zdigits[1:R-1] wbarr = wdigits[1:R-1] s = (zbarr == wbarr) * (zr == 0) * (wr == 1) if abs(s) == 1 push!(elementsB, Element(a, b, ejectindex, s)) end end return elementsB else set_elements_B(G, ejectindex) end end """ make_mat!(T::AbstractMatrix,elements::Vector,rates::Vector) set matrix elements of T to those in vector argument elements """ function make_mat!(T::AbstractMatrix, elements::Vector, rates::Vector) for e in elements T[e.a, e.b] += e.pm * rates[e.index] end end """ make_mat(elements,rates,nT) return an nTxnT sparse matrix T """ function make_mat(elements::Vector, rates::Vector, nT::Int) T = spzeros(nT, nT) make_mat!(T, elements, rates) return T end """ make_S_mat """ function make_mat_U(total::Int, decay::Float64) U = spzeros(total, total) Uminus = spzeros(total, total) Uplus = spzeros(total, total) # Generate matrices for m transitions Uplus[1, 2] = decay for m = 2:total-1 U[m, m] = -decay * (m - 1) Uminus[m, m-1] = 1 Uplus[m, m+1] = decay * m end U[total, total] = -decay * (total - 1) Uminus[total, total-1] = 1 return U, Uminus, Uplus end """ make_M_mat return M matrix used to compute steady state RNA distribution """ function make_mat_M(T::SparseMatrixCSC, B::SparseMatrixCSC, decay::Float64, total::Int) U, Uminus, Uplus = make_mat_U(total, decay) make_mat_M(T, B, U, Uminus, Uplus) end function make_mat_M(T::SparseMatrixCSC, B::SparseMatrixCSC, U::SparseMatrixCSC, Uminus::SparseMatrixCSC, Uplus::SparseMatrixCSC) nT = size(T, 1) total = size(U, 1) M = kron(U, sparse(I, nT, nT)) + kron(sparse(I, total, total), T - B) + kron(Uminus, B) + kron(Uplus, sparse(I, nT, nT)) M[end-size(B, 1)+1:end, end-size(B, 1)+1:end] .+= B # boundary condition to ensure probability is conserved return M end function make_mat_M(components::MComponents, rates::Vector) T = make_mat(components.elementsT, rates, components.nT) B = make_mat(components.elementsB, rates, components.nT) make_mat_M(T, B, components.U, components.Uminus, components.Uplus) end function make_mat_M2(components::MComponents, rates::Vector) mcomponents = make_components_M(transitions, G, R, nhist, decay, splicetype) T = make_mat_T2(components.elementsT, rates, components.nT) B = make_mat_B(components.elementsB, rates, components.nT) make_mat_M(T, B, components.U, components.Uminus, components.Uplus) end """ make_T_mat construct matrices from elements """ make_mat_T(components::AbstractTComponents, rates) = make_mat(components.elementsT, rates, components.nT) make_mat_TA(components::TAIComponents, rates) = make_mat(components.elementsTA, rates, components.nT) make_mat_TI(components::TAIComponents, rates) = make_mat(components.elementsTI, rates, components.nT) make_mat_TA(elementsTA, rates, nT) = make_mat(elementsTA, rates, nT) make_mat_TI(elementsTI, rates, nT) = make_mat(elementsTI, rates, nT) function make_mat_GR(components, rates) nG = components.nG nR = components.nR G = make_mat(components.elementsG, rates, nG) R = make_mat(components.elementsR, rates, nR) RB = make_mat(components.elementsRB, rates, nR) G,R,RB end function make_mat_T2(components, rates) nG = components.nG G = make_mat(components.elementsG, rates, nG) nR = components.nR GR = spzeros(nG, nG) GR[nG, nG] = 1.0 R = make_mat(components.elementsR, rates, nR) RG = make_mat(components.elementsRG, rates, nR) RB = make_mat(components.elementsRB, rates, nR) T = kron(RG, GR) + kron(sparse(I, nR, nR), G) + kron((R + RB), sparse(I, nG, nG)) return T end function make_mat_B() kron(RB,G) end function set_elements_T2(transitions, G, R, S, insertstep, indices::Indices, splicetype::String) if R > 0 elementsG = Vector{Element}(undef, 0) elementsR = Vector{Element}(undef, 0) elementsRG = Vector{Element}(undef, 0) elementsRB = Vector{Element}(undef, 0) base = S > 0 ? 3 : 2 nR = base^R set_elements_G!(elementsG, transitions) set_elements_RS!(elementsRG, elementsR, elementsRB, R, S, insertstep, indices.nu, indices.eta, splicetype) return elementsG, elementsRG, elementsR, elementsRB, nR else return set_elements_G(transitions, indices.gamma), G end end function make_components_T2(transitions, G, R, S, insertstep, splicetype) indices = set_indices(length(transitions), R, S, insertstep) elementsG, elementsRG, elementsR, elementsRB, nR = set_elements_T2(transitions, G, R, S, insertstep, indices, "") T2Components(G, nR, elementsG, elementsR, elementsRG, elementsRB) end function test_mat(r, transitions, G, R, S, insertstep) components = make_components_T(transitions, G, R, S, insertstep, "") make_mat_T(components, r) end function test_mat_2(r, transitions, G, R, S, insertstep) components = make_components_T2(transitions, G, R, S, insertstep, "") make_mat_T2(components, r) end
StochasticGene
https://github.com/nih-niddk-mbs/StochasticGene.jl.git
[ "MIT" ]
1.2.5
fc1bcee6037ea393ce28426929eff65c76a86779
code
15378
# This file is part of StochasticGene.jl # utilities.jl """ invert_dict(D) invert a dictionary """ invert_dict(D) = Dict(D[k] => k for k in keys(D)) """ eig_decompose(M) Take matrix M and return values and vectors """ function eig_decompose(M) Meiv = eigen(M) return Meiv.values, Meiv.vectors end """ nonzero_rows(T) Returns an array of row indices that have at least one nonzero element for matrix T """ function nonzero_rows(T) n = size(T)[2] nonzeros = Array{Int}(undef, 0) for a in 1:size(T)[1] if T[a, :] != zeros(n) push!(nonzeros, a) end end return nonzeros end """ nonzero_states(states,nonzeros) return reindexed state vector with zeros removed """ nonzero_states(states, nonzeros) = [findfirst(o .== nonzeros) for o in intersect(states, nonzeros)] """ normalize_histogram(hist) Returns normalized histogram hist """ normalize_histogram(hist) = hist / sum(hist) """ var_update(vartuple, newValue) vartuple = count, mean, M2 iteration step for online algorithm to compute mean and variance returns count, mean, M2 """ function var_update(vartuple, newValue) count, mean, M2 = vartuple count += 1 delta = newValue - mean mean .+= delta / count delta2 = newValue - mean M2 .+= delta .* delta2 return count, mean, M2 end """ cov_update(covtuple,newValue1,newValue2) update covtuple for online algorithm to compute covariance """ function cov_update(covtuple, newValue1, newValue2) count, meanx, meany, C = covtuple count += 1 dx = newx - meanx meanx .+= dx / count meany .+= (newy - meany) / count C .+= dx * (newy - meany) return count, meanx, meany, C end """ finalize(vartuple) Retrieve the mean, variance and sample variance from an aggregate """ function finalize(vartuple) count, mean, M2 = vartuple if count < 2 return mean, M2 else return mean, M2 ./ (count - 1) end end """ truncate_histogram(x::Array, yield::Float64, nhistmax::Int) return histogram x that accounts for fraction yield of total sum """ function truncate_histogram(x::Array, yield::Float64, nhistmax::Int) if yield < 1.0 counts = sum(x) if counts > 0 nhist = 1 ratio = 0.0 # Only keep yield of all data to limit support of histogram while ratio <= yield && nhist <= nhistmax ratio = sum(x[1:nhist]) / counts nhist += 1 end return x[1:min(nhist, length(x))] else return 0 end else return x[1:min(nhistmax, length(x))] end end """ combine_histogram(x1::Array,x2::Array) add histograms x1 and x2 """ function combine_histogram(x1::Array, x2::Array) n = min(length(x1), length(x2)) x1[1:n] + x2[1:n] end """ pooled_mean(means,counts) compute weighted average of means given count totals """ pooled_mean(means, counts) = counts' * means / sum(counts) """ pooled_variance(vars,counts) computed weighted average of variances given counts """ pooled_variance(vars, counts) = (counts .- 1)' * vars / sum(counts .- 1) """ pooled_std(std,counts) compute weighted average of standard deviations given counts """ pooled_std(std, counts) = sqrt(pooled_variance(std .^ 2, counts)) """ var_ratio(mua,mub,vara,varb,cov) Compute ratio of variances of two variables given means, variances, and covariance of variables """ var_ratio(mua, mub, vara, varb, cov) = mua^2 / mub^2 * (vara / mua^2 - 2 * cov / (mua * mub) + varb / mub^2) """ decimal(x::Vector) convert number to base 10 from any base """ function decimal(x::Vector, base::Int=3) nr = length(x) x' * base .^ collect(0:nr-1) end """ digit_vector(z,base,R) convert z to vector of length R in base=base """ digit_vector(z, base, R) = digits(z - 1, base=base, pad=R) """ findbase(l,n,nr) Find the number of G states for transition rate matrix of size l """ function findbase(l, n, nr) if l == (n + 1) * 3^nr return 3 elseif l == (n + 1) * 2^nr return 2 else throw("wrong length") end end """ KL(x,y) Kullback-Leibler distance """ KL(x, y) = sum(x .* (log.(max.(x, eps(Float64))) - log.(max.(y, eps(Float64))))) """ trim_hist(h::Array,nh::Array) """ function trim_hist(h::Array, nh::Array) for i in eachindex(h) h[i] = h[i][1:nh[i]] end return h end """ distribution_array(param::Vector, cv, dist=Normal) """ function distribution_array(param::Vector, cv, dist=Normal) d = [] for i in eachindex(param) if dist == LogNormal push!(d, LogNormal_meancv(param[i], cv[i])) elseif dist == Gamma push!(d, Gamma_meancv(param[i], cv[i])) else push!(d, dist(param[i], cv[i])) end end return d end """ LogNormal_array(param,cv) Prior distribution arrays """ LogNormal_array(param, cv) = distribution_array(param, cv, LogNormal) """ Gamma_array(param,cv) """ Gamma_array(param, cv) = distribution_array(param, cv, Gamma) """ function LogNormalBeta_array(param,cv,ind) """ function LogNormalBeta_array(param, cv, ind) if ind == 1 d = [setBeta(param[ind], cv[ind])] else barind = 1:ind-1 d = LogNormalarray(param[barind], cv[barind]) push!(d, setBeta(param[ind], cv[ind])) end return d end """ distributionBeta_array(param::Vector, cv::Vector, ind::Int, dist=LogNormal) fill an array with dist(param,cv) """ function distributionBeta_array(param::Vector, cv::Vector, ind::Int, dist=LogNormal) if ind == 1 d = [Beta_meancv(param[ind], cv[ind])] else barind = 1:ind-1 d = distribution_array(param[barind], cv[barind], dist) push!(d, Beta_meancv(param[ind], cv[ind])) end return d end """ Gamma_meancv(mean,cv) LogNormal_meancv(mean,cv) Beta_meancv(mean,cv) Reparameterized distributions to mean and coefficient of variation arguments """ Gamma_meancv(mean, cv) = Gamma(1 / cv^2, mean * cv^2) LogNormal_meancv(mean, cv) = LogNormal(mulognormal(mean, cv), sigmalognormal(cv)) function Beta_meancv(m, cv) cv2 = cv^2 fac = (1 - m) / cv2 / m - 1 if fac <= 0.0 fac = 2 / m end alpha = m * fac beta = (1 - m) * fac Beta(alpha, beta) end """ sigmalognormal(cv) mulognormal(mean,cv) compute LogNormal mu and sigma parameters, i.e. mean and sigma of exp(N(mu,sigma)) given desired mean and coefficient of variation (cv) """ sigmalognormal(cv) = sqrt.(log.(1 .+ cv .^ 2)) mulognormal(mean, cv) = log.(mean) - 0.5 * log.(1 .+ cv .^ 2) mean_dwelltime(x,t) = t' * x """ mean_histogram(x) """ mean_histogram(x::Vector{Float64}) = collect(0:length(x)-1)' * x / sum(x) function mean_histogram(x::Vector{Array}) y = Vector{Float64}(undef, length(x)) for i in eachindex(x) y[i] = mean_histogram(x[i]) end return y end """ Difference_Zscore(x1,x2,sig1,sig2) = (x1 .- x2)./ sqrt(sig1.^2 + sig2.^2) """ Difference_Zscore(x1, x2, sig1, sig2) = (x1 - x2) / sqrt(sig1^2 + sig2^2) """ m2_histogram(x) """ m2_histogram(x) = (collect(0:length(x)-1) .^ 2)' * x / sum(x) """ var_histogram(x) """ function var_histogram(x) m2_histogram(x) - mean_histogram(x)^2 end function moment_histogram(x, n) y = collect(0:length(x)-1) v = (y .- mean_histogram(x)) .^ n v' * x / sum(x) end function factorial_moment(h::Vector, n) m = 0 for i in n:length(h) a = i - 1 for j in 1:n-1 a *= i - j - 1 end m += h[i] * a end return m / sum(h) end function moment_param_estimates(h) e1 = factorial_moment(h, 1) e2 = factorial_moment(h, 2) e3 = factorial_moment(h, 3) r1 = e1 r2 = e2 / e1 r3 = e3 / e2 println(r1, ", ", r2, ", ", r3) lambda = 2 * r1 * (r3 - r2) / (r1 * r2 - 2 * r1 * r3 + r2 * r3) mu = 2 * (r2 - r1) * (r1 - r3) * (r3 - r2) / (r1 * r2 - 2 * r1 * r3 + r2 * r3) / (r1 - 2 * r2 + r3) nu = (-r1 * r2 + 2 * r1 * r3 - r2 * r3) / (r1 - 2 * r2 + r3) return lambda, mu, nu end """ tstat_2sample(x1,x2) Compute t statistics of histograms x1 and x2 """ tstat_2sample(x1, x2) = (mean_histogram(x1) - mean_histogram(x2)) / (sqrt(var_histogram(x1) / length(x1) + var_histogram(x2) / length(x2))) """ log_2sample(x1,x2) compute the log of the ratio of means of histograms x1 and x2 """ log_2sample(x1, x2) = log(mean_histogram(x1)) - log(mean_histogram(x2)) """ delta_2sample(x1,x2) compute the difference of means of x1 and x2 """ delta_2sample(x1, x2) = mean_histogram(x1) - mean_histogram(x2) """ delta_2frac(x1,x2) compute E(x1) - E(x2) of means normalize dot mean of x1 """ delta_2frac(x1, x2) = delta_2sample(x1, x2) / mean_histogram(x1) """ mediansmooth(xin,window) median smooth histogram xin over a window """ function mediansmooth(xin, window) x = copy(xin) halfwin = div(window - 1, 2) for i in 1:length(x)-window+1 x[i+halfwin] = median(x[i:i+window-1]) end x end """ residenceprob_G(file,G,header) residenceprob_G(r,n) Residence probability of G states given by exact steady state solution of master equation """ function residenceprob_G(file::String, G, header=false) r = get_all_rates(file, header) m = size(r)[1] p = Array{Any,2}(undef, m, G + 1) n = G - 1 for i in 1:m p[i, 1] = r[i, 1] p[i, 2:end] = residenceprob_G(r[i, 2:2*n+1], n) end return p end function residenceprob_G(r::Vector, n::Int) Gss = Array{Float64,2}(undef, 1, n + 1) Gss[1, 1] = 1.0 for k in 1:n Gss[1, k+1] = Gss[1, k] * r[2*k-1] / r[2*k] end Gss ./= sum(Gss) end """ splicesiteusage() splice site usage probability is the probabilty of ejection times the probability of not ejection prior to that point """ splicesiteusage(model::GRSMmodel) = splicesiteusage(model.rates, model.G - 1, model.R) function splicesiteusage(r::Vector, n::Int, nr::Int) nu = get_nu(r, n, nr) eta = get_eta(r, n, nr) ssf = zeros(nr) survival = 1 for j in 1:nr ssf[j] = eta[j] / (nu[j+1] + eta[j]) * survival survival *= nu[j+1] / (nu[j+1] + eta[j]) end return ssf end """ onstate_prob(r,components::TComponents) """ function onstate_prob(r,components::TComponents,reporter_per_state) Qtr = make_mat(components.elementsT, r, components.nT) p0=normalized_nullspace(Qtr) return sum(p0[reporter_per_state.>0]), p0 end onstate_prob(param,model::AbstractGmodel) = onstate_prob(get_rates(param, model),model.components,model.reporter.per_state) onstate_prob(model::AbstractGmodel) = onstate_prob(model.rates,model.components,model.reporter.per_state) """ burstoccupancy(n,nr,r) Burst size distribution of GRS model for total pre-mRNA occupancy and unspliced (visible) occupancy obtained by marginalizing over conditional steady state distribution """ burstoccupancy(model::GRSMmodel) = burstoccupancy(model.G - 1, model.R, model.rates) function burstoccupancy(n::Int, nr::Int, r::Vector) T = mat_GSR_T(r, n, nr) pss = normalized_nullspace(T) Rss = zeros(nr) Rssvisible = zeros(nr) ssf = zeros(nr) asum = 0 for w = 1:nr for i = 1:n+1, z = 1:3^nr zdigits = digit_vector(z, 3, nr) a = i + (n + 1) * (z - 1) if sum(zdigits .== 2) == w Rssvisible[w] += pss[a] end if sum(zdigits .> 0) == w Rss[w] += pss[a] end end end Rss ./= sum(Rss), Rssvisible ./= sum(Rssvisible) end model2_mean(ron, roff, eject, decay, nalleles) = 2 * model2_mean(ron, roff, eject, decay) model2_mean(ron, roff, eject, decay) = ron / (ron + roff) * eject / decay model2_variance(ron, roff, eject, decay, nalleles) = 2 * model2_variance(ron, roff, eject, decay) model2_variance(ron, roff, eject, decay) = ron / (ron + roff) * eject / decay + ron * roff / (ron + roff)^2 * eject^2 / decay / (ron + roff + decay) """ test_steadystatemodel(model,nhist) Compare chemical master solution to Gillespie simulation for steadystate mRNA distribution """ function test_steadystatemodel(model::AbstractGMmodel, nhist) G = model.G r = model.rates g1 = steady_state(r[1:2*G], G - 1, nhist, model.nalleles) g2 = simulatorGM(r[1:2*G], G - 1, nhist, model.nalleles) return g1, g2 end function test_model(data::RNAOnOffData, model::GRSMmodel) telegraphsplice0(data.bins, data.nRNA, model.G - 1, model.R, model.rates, 1000000000, 1e-5, model.nalleles) end """ make_histograms(folder,file,label) make_histogram(r) """ function make_histograms(folder, file, label) if ~ispath(folder) mkpath(folder) end a, h = readdlm(file, ',', header=true) for r in eachrow(a) f = open("$folder/$(r[1])_$label.txt", "w") a = r[2:end] a = a[(a.!="").&(a.!="NA")] h = make_histogram(Int.(a) .+ 1) writedlm(f, h) close(f) end end function make_histogram(r) nhist = maximum(r) h = zeros(Int, nhist + 1) for c in r h[c] += 1 end h end """ expv(v::Array) exponential of array """ expv(v::Array) = exp.(v) logv(v::Array) = log.(v) """ logit(x::Float64) logit transform """ logit(x::Float64) = log(x) - log(1 - x) logit(x::Array) = log.(x) .- log.(1 .- x) """ invlogit(x::Float64) inverse logit transform """ invlogit(x::Float64) = 1 / (1 + exp(-x)) invlogit(x::Array) = 1 ./ (1 .+ exp.(-x)) """ logsumexp(u,v) returns log of the sum of exponentials of u and v """ function logsumexp(u::Array, v::Array) w = max(u, v) if w == -Inf return -Inf else return w .+ log.(exp.(u - w) + exp.(v - w)) end end function logsumexp(u::Float64, v::Float64) w = max(u, v) if w == -Inf return -Inf else return w + log(exp(u - w) + exp(v - w)) end end """ logsumexp(v) returns log of the sum of exponentials of elements of v """ function logsumexp(v::Array) w = maximum(v) if w == -Inf return -Inf else return w .+ log(sum(exp.(v .- w))) end end function meantime(r::Vector) sum(1 ./ r) end """ make_array(v) convert containuer of arrays into a single array """ function make_array(v) vconcat = Float64[] for v in v vconcat = [vconcat; v] end return vconcat end """ makestring(v::Vector) convert a vector of strings into a single string """ function makestring(v) s = "" for i in v s *= i end return s end # # function fit_rna_test(root) # gene = "CENPL" # cell = "HCT116" # fish = false # data = data_rna(gene,"MOCK","data/HCT116_testdata",fish,"scRNA_test",root) # model = model_rna(gene,cell,2,fish,.01,[1,2,3],(),"scRNA_test","scRNA_test",1,".",data,.05,1.0) # options = MHOptions(10000,2000,0,120.,1.,100.) # fit,stats,waic = run_mh(data,model,options,1); # return stats.meanparam, fit.llml # end # # function online_covariance(data1, data2) # meanx = meany = C = n = 0 # for x in data1, y in data2 # n += 1 # dx = x - meanx # meanx += dx / n # meany += (y - meany) / n # C += dx * (y - meany) # population_covar = C / n # # Bessel's correction for sample variance # sample_covar = C / (n - 1) # end # end
StochasticGene
https://github.com/nih-niddk-mbs/StochasticGene.jl.git
[ "MIT" ]
1.2.5
fc1bcee6037ea393ce28426929eff65c76a86779
code
8690
using StochasticGene using Test function test_sim(r, transitions, G, R, S, insertstep, nhist, nalleles, onstates, bins, total, tol) simulator(r, transitions, G, R, S, insertstep, nhist=nhist, nalleles=nalleles, onstates=onstates, bins=bins, totalsteps=total, tol=tol) end function test_compare(; r=[0.038, 1.0, 0.23, 0.02, 0.25, 0.17, 0.02, 0.06, 0.02, 0.000231], transitions=([1, 2], [2, 1], [2, 3], [3, 1]), G=3, R=2, S=2, insertstep=1, nRNA=150, nalleles=2, bins=[collect(5/3:5/3:200), collect(5/3:5/3:200), collect(0.1:0.1:20), collect(0.1:0.1:20)], total=1000000000, tol=1e-6, onstates=[Int[], Int[], [2, 3], [2, 3]], dttype=["ON", "OFF", "ONG", "OFFG"]) hs = test_sim(r, transitions, G, R, S, insertstep, nRNA, nalleles, onstates[[1, 3]], bins[[1, 3]], total, tol) h = test_chem(r, transitions, G, R, S, insertstep, nRNA, nalleles, onstates, bins, dttype) hs = StochasticGene.normalize_histogram.(hs) return make_array(h), make_array(hs) end function test_chem(r, transitions, G, R, S, insertstep, nRNA, nalleles, onstates, bins, dttype) for i in eachindex(onstates) if isempty(onstates[i]) onstates[i] = on_states(G, R, S, insertstep) end onstates[i] = Int64.(onstates[i]) end components = make_components_MTD(transitions, G, R, S, insertstep, onstates, dttype, nRNA, r[num_rates(transitions, R, S, insertstep)], "") likelihoodarray(r, G, components, bins, onstates, dttype, nalleles, nRNA) end function test_fit_simrna(; rtarget=[0.33, 0.19, 20.5, 1.0], transitions=([1, 2], [2, 1]), G=2, nRNA=100, nalleles=2, fittedparam=[1, 2, 3], fixedeffects=tuple(), rinit=[0.1, 0.1, 0.1, 1.0], totalsteps=100000) h = simulator(rtarget, transitions, G, 0, 0, 0, nhist=nRNA, totalsteps=totalsteps, nalleles=nalleles) data = RNAData("", "", nRNA, h) model = load_model(data, rinit, StochasticGene.prior_ratemean(transitions, 0, 0, 1, rtarget[end], []), fittedparam, fixedeffects, transitions, G, 0, 0, 0, nalleles, 10.0, Int[], rtarget[end], 0.02, "", prob_Gaussian, [], tuple()) options = StochasticGene.MHOptions(1000000, 0, 0, 20.0, 1.0, 1.0) fits, stats, measures = run_mh(data, model, options) StochasticGene.get_rates(fits.parml, model), rtarget end function test_fit_rna(; gene="CENPL", G=2, nalleles=2, propcv=0.05, fittedparam=[1, 2, 3], fixedeffects=tuple(), transitions=([1, 2], [2, 1]), rinit=[0.01, 0.1, 1.0, 0.01006327034802035], datacond="MOCK", datapath="data/HCT116_testdata", label="scRNA_test", root=".") data = load_data("rna", [], folder_path(datapath, root, "data"), label, gene, datacond, 1.0, 1.0, [1, 2]) model = load_model(data, rinit, StochasticGene.prior_ratemean(transitions, 0, 0, 1, 1., []), fittedparam, fixedeffects, transitions, 2, 0, 0, 1, nalleles, 10.0, Int[], rinit[end], propcv, "", prob_Gaussian, [], tuple()) options = StochasticGene.MHOptions(100000, 0, 0, 60.0, 1.0, 1.0) fits, stats, measures = run_mh(data, model, options) h = likelihoodfn(fits.parml, data, model) h, normalize_histogram(data.histRNA) end function test_fit_rnaonoff(; G=2, R=1, S=1, transitions=([1, 2], [2, 1]), insertstep=1, rtarget=[0.02, 0.1, 0.5, 0.2, 0.1, 0.01], rinit=fill(0.01, num_rates(transitions, R, S, insertstep)), nsamples=100000, nhist=20, nalleles=2, onstates=Int[], bins=collect(1:1.0:200.0), fittedparam=collect(1:length(rtarget)-1), propcv=0.05, priorcv=10.0, splicetype="") # OFF, ON, mhist = test_sim(rtarget, transitions, G, R, S, nhist, nalleles, onstates, bins) h = simulator(rtarget, transitions, G, R, S, insertstep, nalleles=nalleles, nhist=nhist, onstates=onstates, bins=bins, totalsteps=3000) hRNA = div.(h[1], 30) data = StochasticGene.RNAOnOffData("test", "test", nhist, hRNA, bins, h[2], h[3]) model = load_model(data, rinit, StochasticGene.prior_ratemean(transitions, R, S, insertstep, rtarget[end], []), fittedparam, tuple(), transitions, G, R, S, insertstep, nalleles, priorcv, onstates, rtarget[end], propcv, splicetype, prob_Gaussian, [], tuple()) options = StochasticGene.MHOptions(nsamples, 0, 0, 120.0, 1.0, 1.0) fits, stats, measures = run_mh(data, model, options) h = likelihoodfn(fits.parml, data, model) h, StochasticGene.datapdf(data) end function test_fit_rnadwelltime(; rtarget=[0.038, 2.0, 0.23, 0.02, 0.25, 0.17, 0.02, 0.06, 0.02, 0.000231], transitions=([1, 2], [2, 1], [2, 3], [3, 1]), G=3, R=2, S=2, insertstep=1, nRNA=150, nsamples=100000, nalleles=2, onstates=[Int[], Int[], [2, 3], [2, 3]], bins=[collect(5/3:5/3:200), collect(5/3:5/3:200), collect(0.1:0.1:10), collect(0.1:0.1:10)], dttype=["ON", "OFF", "ONG", "OFFG"], fittedparam=collect(1:length(rtarget)-1), propcv=0.01, priorcv=10.0, splicetype="") h = test_sim(rtarget, transitions, G, R, S, insertstep, nRNA, nalleles, onstates[[1, 3]], bins[[1, 3]], 300000, 1e-6) data = RNADwellTimeData("test", "test", nRNA, h[1], bins, h[2:end], dttype) rinit = StochasticGene.prior_ratemean(transitions, R, S, insertstep, rtarget[end], []) model = load_model(data, rinit, StochasticGene.prior_ratemean(transitions, R, S, insertstep, rtarget[end], []), fittedparam, tuple(), transitions, G, R, S, insertstep, nalleles, priorcv, onstates, rtarget[end], propcv, splicetype, prob_Gaussian, [], tuple()) options = StochasticGene.MHOptions(nsamples, 1000, 0, 200.0, 1.0, 1.0) fits, stats, measures = run_mh(data, model, options) h = likelihoodfn(fits.parml, data, model) h, StochasticGene.datapdf(data) end function test_fit_trace(; G=2, R=1, S=1, insertstep=1, transitions=([1, 2], [2, 1]), rtarget=[0.02, 0.1, 0.5, 0.2, 0.1, 0.01, 50, 15, 200, 70], rinit=[fill(0.1, num_rates(transitions, R, S, insertstep) - 1); 0.01; [20, 5, 100, 10]], nsamples=5000, onstates=Int[], totaltime=1000.0, ntrials=10, fittedparam=[collect(1:num_rates(transitions, R, S, insertstep)-1); collect(num_rates(transitions, R, S, insertstep)+1:num_rates(transitions, R, S, insertstep)+4)], propcv=0.01, cv=100.0, interval=1.0, noisepriors=[50, 15, 200, 70]) trace = simulate_trace_vector(rtarget, transitions, G, R, S, interval, totaltime, ntrials) data = StochasticGene.TraceData("trace", "test", interval, (trace, [], 0.0, 1)) model = load_model(data, rinit, StochasticGene.prior_ratemean(transitions, R, S, insertstep, rtarget[end], noisepriors), fittedparam, tuple(), transitions, G, R, S, insertstep, 1, 10.0, Int[], rtarget[num_rates(transitions, R, S, insertstep)], propcv, "", prob_Gaussian, noisepriors, tuple()) options = StochasticGene.MHOptions(nsamples, 0, 0, 100.0, 1.0, 1.0) fits, stats, measures = run_mh(data, model, options) StochasticGene.get_rates(fits.parml, model), rtarget end function test_fit_trace_hierarchical(; G=2, R=1, S=0, insertstep=1, transitions=([1, 2], [2, 1]), rtarget=[0.02, 0.1, 0.5, 0.2, 1.0, 50, 15, 200, 70], rinit=[], nsamples=100000, onstates=Int[], totaltime=1000.0, ntrials=10, fittedparam=collect(1:num_rates(transitions, R, S, insertstep)-1), propcv=0.01, cv=100.0, interval=1.0, noisepriors=[50, 15, 200, 70], hierarchical=(2, collect(num_rates(transitions, R, S, insertstep)+1:num_rates(transitions, R, S, insertstep)+ length(noisepriors)), tuple()), method=(1, true)) trace = simulate_trace_vector(rtarget, transitions, G, R, S, interval, totaltime, ntrials) data = StochasticGene.TraceData("trace", "test", interval, (trace, [], 0.0, 1)) rm = StochasticGene.prior_ratemean(transitions, R, S, insertstep, 1.0, noisepriors, hierarchical[1]) isempty(rinit) && (rinit = StochasticGene.set_rates(rm, transitions, R, S, insertstep, noisepriors, length(data.trace[1]))) model = load_model(data, rinit, rm, fittedparam, tuple(), transitions, G, R, S, insertstep, 1, 10.0, Int[], rtarget[num_rates(transitions, R, S, insertstep)], propcv, "", prob_Gaussian, noisepriors, hierarchical, method) options = StochasticGene.MHOptions(nsamples, 0, 0, 100.0, 1.0, 1.0) fits, stats, measures = run_mh(data, model, options) nrates = num_rates(transitions, R, S, insertstep) h1 = StochasticGene.get_rates(fits.parml, model)[1:nrates] h2 = rtarget[1:nrates] return h1, h2 end @testset "StochasticGene" begin h1, h2 = test_fit_trace_hierarchical() @test isapprox(h1, h2, rtol=0.5) h1, h2 = test_compare() @test isapprox(h1, h2, rtol=0.2) h1, h2 = test_fit_simrna() @test isapprox(h1, h2, rtol=0.05) h1, h2 = test_fit_rna() @test isapprox(h1, h2, rtol=0.1) h1, h2 = test_fit_rnaonoff() @test isapprox(h1, h2, rtol=0.3) h1, h2 = test_fit_rnadwelltime() @test isapprox(h1, h2, rtol=0.3) h1, h2 = test_fit_trace() @test isapprox(h1, h2, rtol=0.05) end
StochasticGene
https://github.com/nih-niddk-mbs/StochasticGene.jl.git
[ "MIT" ]
1.2.5
fc1bcee6037ea393ce28426929eff65c76a86779
docs
31285
# StochasticGene.jl Julia package to simulate and fit stochastic models of gene transcription to experimental data. The data acceptable include distributions of mRNA counts per cell (e.g. single molecule FISH (smFISH) or single cell RNA sequence (scRNA) data)), image intensity traces from live cell imaging, and dwell time distributions of reporters (e.g. MS2 or PP7) imaged in live cells. The transcription models considered are stochastic (continuous Markov systems) with an arbitrary number of G (gene) states, R (pre-RNA) steps, S splice sites (up to R), and reporter insertion step (insertstep). The gene always occupies one of the G states and there are random (user specified) transitions between G states. One of the G states is an active state where transcription can be initiated and the first R step becomes occupied. An irreversible forward transition can then occur to the next R step if that step is unoccupied mimicking elongation. An mRNA molecule is ejected from the final (termination) R step where it then decays stochastically. The model can account for multiple alleles of the gene in the same cell. The user can specify which R step is considered visible when occupied (i.e. contains a reporter). For example, if the pre-RNA MS2 construct is inserted into an intron that is transcribed early then you could make the reporter insertstep to be 1 and all R steps will be visible. But if the reporter is transcribed late then you could choose a later R step, like step 3, and only R steps at and after step 3 are considered visible. In the original model in Rodriguez et al. Cell (2018), the reporter was in an exon and was visible at all steps and then ejected. The alleles were also coupled; coupling between alleles and between genes is under construction. In Wan et al. Cell (2021), the reporter is inserted into an intron and thus can be spliced out before the polymerase reaches the final R step. Models are allowed to have no R steps (i.e. classic telegraph models but with arbitrary numbers of G states (rather thabn usual two)) where an mRNA molecule can be stochastically produced when the gene occupies the active G state. You can also specify reporters for G states (e.g. transcription factors) and more than one simultaneous reporter (e.g. reporters for introns and transcription factors). The package has functions to specify the models, prepare the data, compute the predicted data, apply a Metropolis-Hastings markov chain monte carlo (MCMC) algorithm to fit the parameters of the models to the data (i.e. compute Bayesian posterior distributions), explicitly simulate models, and analyze the results. Unfortunately, not all capabilities are documented so just send me a message if you have any questions. StochasticGene can run on small data sets on a laptop or large data sets on a multiprocessor cluster such as NIH Biowulf. There are functions that generate swarm files to be submitted and process and analyze the results. ### Installing StochasticGene The following assumes that Julia has already been installed. If not go to https://julialang.org/downloads/. Julia has already been installed on the NIH Biowulf system but StochasticGene must be installed by each individual user. To install StochasticGene on a local computer, open a terminal and type ``` $ julia ``` After Julia opens you will be in the interactive Julia REPL. Run the following: ``` julia> ] add StochasticGene ``` The command "]" brings you into the Julia Package environment, "Ctrl C" gets you out After the package has installed, you can check if it works by running ``` julia> ] test StochasticGene ``` (this could take 10 or more minutes) StochasticGene will be updated on Github periodically. To update to a new version type ``` julia> ] update StochasticGene ``` To install StochasticGene on Biowulf, log on and at the prompt type: ``` [username@biowulf ~]$ sinteractive --mem=64G ``` This generates an interactive session ``` [username@biowulf ~]$ module load julialang ``` This loads Julia for use. ``` [username@biowulf ~]$ julia - t 1 ``` Starts Julia (with a single thread). Then continue as before Note: Sometimes Julia has problems crashing on Biowulf if an update is made to StochasticGene. The best way to deal with this is to go to your home directory and delete the julia directory via: ``` [username@biowulf ~]$ rm -r --force .julia ``` Then start julia and add StochasticGene again. Also, Julia is periodically updated on Biowulf and StochasticGene will not carry forward to the latest version. You can still call previous versions when you allocated CPUs or reinstall StochasticGene in the new version. ### Creating folder structure to run StochasticGene StochasticGene requires a specific directory or folder structure where data are stored and results are saved. At the top is the `root` folder (e.g. "scRNA" or "RNAfits") with subfolders `data` and `results`. Inside `data` are two more folders `alleles` and `halflives`, containing allele numbers and half lives, respectively. The command ``` julia> using StochasticGene julia> rna_setup("scRNA") ``` will create the folder structure in the folder `scRNA` with the `data` and `results` subfolders, with some mock data in the `data` folder. Typing `rna_setup()` will assume the current folder is the root. Files for allele numbers and halflives for desired cell types can be added directly to the `data` folder. These files should be csv format and have the form `[cell name]_alleles.csv` or `[cell name]_halflife.csv`. Halflives for the then genes in Wan et al. for HBEC cells are built into the system. ### Fitting data with StochasticGene To fit a model, you need to load data and choose a model. Data currently accepted are stationary histograms (e.g. smFISH or scRNA), intensity time traces (e.g. trk files), nascent RNA data (e.g. from intronic FISH probes), and dwell time distributions. Different data types from the same experiment can also be fit simultaneously. For example, RNA histograms from smFISH can be fit together with multiple intensity traces or dwell time histograms from live cell recordings. Models are distringuished by the number of G states, the transition graph between G states (i.e. which G states can transitions to which other G states), number of R steps, the step where the reporter is inserted, and whether splicing occurs. For intensity traces and dwell time distributions, the sojourn or "on" states (i.e. R steps or G states where the reporter is visible) must also be specified. Multiple sets of on states are allowed. Data are fit using the `fit` function, which has named arguments (see API below) to determine the type of data to be fit, where it can be found, what model to be used, and what options to be set for the fitting algorithm. The default, run by typing `fit()`, will fit the mock rna histogram data installed by `rna_setup(root)` with a simple two state telegraph model (2 G stsates, no R steps). Data is in the folder "root/data/HCT116_testdata", where root is specified by the user. The default root is the folder in which julia was launched but can be specified using the named argument `root`. The `fit` function returns six variables. To fit on a single processor, type ``` julia> using StochasticGene julia> fits, stats, measures, data, model, options = fit(); 2023-10-24T10:22:10.782 Gene: MYC G: 2 Treatment: MOCK data: HCT116_testdata/ in: HCT116_test out: HCT116_test maxtime: 60.0 ./results/HCT116_test/rates_rna-HCT116_MOCK_MYC_2_2.txt does not exist [0.01, 0.01, 0.1, 0.032430525886402085] initial ll: 38980.680174070265 final max ll: 21755.280380669064 median ll: 21755.280645984076 Median fitted rates: [0.020960969159742875, 0.142016620787, 1.1015638965800167] ML rates: [0.020979229436880756, 0.1423818501792811, 1.10350961139495] Acceptance: 325538/613219 Deviance: 0.007326880506251085 rhat: 1.0105375337987144 2023-10-24T10:24:11.295 ``` The semicolon is not necessary but suppresses printing the returned variables. You only need to type `using StochasticGene` once per session. The data is fit using the function `run_mh(data,model,options,nchains)` (which runs a Metropolis-Hastings MCMC algorithm), where `data`, `model`, and `options` are structures (Julia types) constructed by `fit` and returned. `nchains` is the number of MCMC chains, each running on a separate processor. The three structures `fits`, `stats`, and `measures` (returned by `run_mh` and `fit`, give the fit results (Bayesian posteriors) and measures of the quality of the fit and are also saved to the folder "./results/HCT116_test", which is specified by the `resultfolder` argument. During the run, the `fit` function prints out some of the information in fits, stats, and measures structures. `fit` will look for previous results in the folder specified by the argument `infolder` as an initial condition to start the MCMC run. In this case, there were no previous runs and thus the default was used, which is the priors of the parameters. In this run three rates were fit (set by argument `fittedparams`); the median of the posterior and the maximum likelihood parameters of the resulting fits are printed. The run was capped to a maximum of 60 seconds of real time (set by the argument `maxtime`) and `Acceptance` shows that out of 613219 MCMC samples, 325538 were accepted by the MCMC algorithm. The positive number `Deviance` is the difference in likelihood between a perfect fit and the resulting fit (for histograms only). `rhat` is a measure of MCMC convergence with 1 being ideal. The two state telegraph model has 4 transition rates, which are stored in a single vector. The order is 1) G state transitions (in the order as specified by the transition vector), 2) eject rate, 3) decay rate. For general GRSM models, the order is 1) G state transitions 2) R transitions, 3) S transitions, 4) decay. If there is no splicing then the S transitions are left out. Not all the rates need to be fitted. In the above example, the decay rate is not fitted. This is specified by the fittedparams argument (see API). The posterior median, mean, standard deviations, and MADs will only be for the fitted params. In this particular run, only one chain was used so the measures are not very informative. To use more chains, specify more processors with ``` bash> julia -p 4 julia> @everywhere using StochasticGene julia> fits, stats, measures, data, model, options = fit(nchains=4); 2023-10-24T10:55:16.232 Gene: MYC G: 2 Treatment: MOCK data: HCT116_testdata/ in: HCT116_test out: HCT116_test maxtime: 60.0 [0.020960969159742875, 0.142016620787, 1.1015638965800167, 0.032430525886402085] initial ll: 21755.280645984076 final max ll: 21755.280378544387 median ll: 21755.282721546962 Median fitted rates: [0.020936177089260818, 0.14140674439592604, 1.0983188350949695] ML rates: [0.020970183926180535, 0.14229910450327884, 1.10310357519155] Acceptance: 713078/1342174 Deviance: 0.0073268798846403485 rhat: 1.0018023969479748 2023-10-24T10:56:31.337 ``` The `datatype` argument is a String that specifies the types of data to be fit. Currently, there are six choices: 1) "rna", which expects a single rna histogram file where the first column is the histogram; 2) "rnaonoff", which expects a rna histogram file and a three column dwelltime file with columns: bins, ON time distribution, and OFF time distribution; 3) "rnadwelltime", which fits an rna histogram together with multiple dwell time histograms specified by a vector of dwell time types, the choices being "ON","OFF" for R step reporters and "ONG", "OFFG" for G state reporters. Each dwelltime histogram is a two column file of the bins and dwell times and datapath is a vector of the paths to each; 4) "trace", which expects a folder of trace intensity (e.g. trk) files; 5) "tracenascent", the same with the nascent RNA input through the argument `nascent`; 6) "tracerna": trace files with RNA histogram. The data files are specified by the argument `datapath`. This can be a string pointing to a file or a folder containing the file. If it points to a folder then `fit` will use the arguments `gene` and `datacond` to identify the correct file. For datatypes that require more than one data file, `datapath` is a vector of paths. The path can include or not include the root folder. ### Example fitting traces Start Julia with multiple processors. ``` $ julia -p 4 ``` Using `sinteractive` on Biowulf, you may need to also declare a single thread with ``` $ julia -p 4 -t 1 ``` You can see how many processors have been called with ``` julia> nworkers() 4 julia @everywere using StochasticGene ``` You can create some simulated mock trace data with ``` julia> simulate_trace_data("data/testtraces/") ``` which generates 10 mock trk files in folder "data/testraces". See API below for the parameters used in the simulated data. ``` julia> fits, stats, measures, data, model, options = fit(datatype="trace",nchains=4,transitions=([1, 2], [2, 1], [2, 3], [3, 1]), G=3, R=2, S=2, insertstep=1, datapath="data/testtraces", gene="test", datacond="", decayrate=1.); 2023-10-28T15:39:16.955 Gene: test G R S insertstep: 3221 in: HCT116_test out: HCT116_test maxtime: 60.0 ./results/HCT116_test/rates_trace-HCT116__test_3221_2.txt does not exist [0.01, 0.01, 0.01, 0.01, 0.1, 0.1, 0.1, 0.1, 0.1, 1.0, 100.0, 100.0, 100.0, 100.0, 0.9] initial ll: 59437.54504442659 final max ll: 52085.58823772918 median ll: 55631.823149864926 Median fitted rates: [0.010164892707601266, 0.010415494521142342, 0.009888467865883247, 0.010565680996634689, 0.1051981476344431, 0.09544095249917071, 0.09473989790249088, 0.10045726361481444, 0.10418638776390472, 63.19680508738758, 56.794573780192, 119.72050615415071, 97.22874914820788, 0.9031904231186259] ML rates: [0.008648315183072212, 0.01105818085890487, 0.01104728099474845, 0.011437834075767405, 0.09527550344438158, 0.11007539741898248, 0.08145019422061348, 0.09898368400856507, 0.1051451404740429, 37.71078406511133, 29.49680612047366, 171.40544543928038, 100.94919964017241, 0.9036456980377264] Acceptance: 770/1525 rhat: 2.9216933196063533 2023-10-28T15:40:18.448 ``` In this run, `rhat` is close to 3 indicating that the number of samples was insufficient to obtain a good sampling of the posterior distributions. either `maxtime` or `samplesteps` needs to be increased. ### Batch fitting on Biowulf using `swarm`. (You made need to run a few times on Biowulf after installing or updating StochasticGene before it works as it sometimes takes too long to precompile on the first use) The data can also be fit in batch mode using swarm files. To do so, you create swarm files. For example, you can fit all the scRNA histogram of all the genes in folder called "data/HCT_testdata" (which should exist if you ran `setup`) on NIH Biowulf by running a swarmfile. First move into the root directory you created and launch julia: ``` [username@biowulf ~]$ cd scRNA [username@biowulf ~]$ julia - t 1 ``` Create swarm files using the command in the JULIA repl: ``` julia> using StochasticGene julia> makeswarm(["CENPL","MYC"],cell="HCT116",maxtime = 600.,nchains = 8,datatype = "rna",G=2,transitions = ([1,2],[2,1]),datacond = "MOCK",resultfolder ="HCT_scRNA",datapath = "HCT116_testdata/",root = ".") ``` The genes are listed as a vector of strings. You only need to type `using StochasticGene` once per session. This will create two files. The first will end in `.swarm` and the second will end in `.jl` To fit all the genes in the data folder use: ``` julia> using StochasticGene julia> makeswarm(cell="HCT116",maxtime = 600.,nchains = 8,datatype = "rna",G=2,transitions = ([1,2],[2,1]), datacond = "MOCK",resultfolder ="HCT_scRNA",datapath = "HCT116_testdata/",nsets=1,root = ".") ``` (for G = 3, use transitions = ([1,2],[2,1],[2,3],[3,2]), for 3 state Kinetic Proofreading model use transitions = ([1,2],[2,1],[2,3],[3,1])) To exit julia type: ``` julia> exit() ``` To run the swarm file, type at the command line: ``` [username@biowulf ~]$ swarm -f fit_HCT116-scRNA-ss_MOCK_2.swarm --time 12:00:00 -t 8 -g 24 --merge-output --module julialang ``` `-t` flag is for time `-g` flag is for memory (choose a time longer than maxtime (remember to convert seconds to hours), and make sure to allocate enough memory) This will submit a job into the Biowulf queue. To check the status of your job type: ``` [username@biowulf ~]$ sjobs ``` When the job finishes, Biowulf will create new swarm files in your folder. The fit results will be saved in the folder `results/HCT_scRNA`. There will be three result files for each gene and model. The file names will have the form `[filetype]_[label]_[condition]_[gene name]_[modeltype written as consecutive numbers GRS]_[number of alleles].txt` `_` (underscore) is a reserved character and should not be used in any of the file field such as `[label]`. filetypes are: `rates`, 4 lines: maximum likelihood rates, mean rates, median rates `measures`, information about the quality of the fits `param-stats`, detailed statistics of the parameter posteriors (the MCMC samples are not saved) `burst`, statistics on burst frequency, 7 lines: mean, sd, median, mad, quantiles at: .025,.5,.97.5 `optimized`, 3 lines: LBFGS optimized rates, negative log likelihood, convergence In our example the files `rates_HCT116-scRNA-ss_MOCK_CENPL_2_2.txt`,`measures_HCT116-scRNA-ss_MOCK_CENPL_2_2.txt`,`param-stats_HCT116-scRNA-ss_MOCK_CENPL_2_2.txt`, `burst_HCT116-scRNA-ss_MOCK_CENPL_2_2.txt`, `optimized_HCT116-scRNA-ss_MOCK_CENPL_2_2.txt` will be produced The output convention is that underscore `_` is used to separate the 4 fields of a result file and thus should not be used in any of the fields. A data frame of the results can be constructed in Julia using the write_dataframes(resultfolder,datafolder) function, e.g. ``` julia> using StochasticGene julia> write_dataframes_only("results/HCT_scRNAtest","data/HCT116_testdata") ``` The result will be a set of csv files collating the result files of all the genes along with a "Winners" file that lists which model performed best for a given measure (default is AIC but can be changed with a named argument, see API below) and a Summary file condensing the information of the other files. The Summary file can be supplemented with more information via the write_augmented(summaryfile,resultfolder) function, e.g. ``` julia> write_augmented("results/HCT_scRNAtest/Summary_HCT116-scRNA-ss_MOCK_2.csv","results/HCT_scRNAtest") ``` ### Example Use on Unix If not running on Biowulf, the same swarm files can be used, although they will not be run in parallel. e.g. in UNIX Bash, type: ``` Bash> chmod 744 fit_scRNA-ss-MOCK_2.swarm Bash> bash fit_scRNA-ss-MOCK_2.swarm & ``` This will execute each gene in the swarm file sequentially. To run several genes in parallel, you can break the run up into multiple swarm files and execute each swarm file separately. You can also trade off time with the number of chains, so if you have a large processor machine run each gene on many processors, e.g. 64, for a short amount of time, e.g. 15 min. ### Simulations Simulate any GRSM model using function simulator, which can produce steady state mRNA histograms, simulated intensity traces, and ON and OFF live cell histograms as selected. The following will simulate the steady state mRNA histogram, and ON and OFF dwelltime distributions, for an intron reporter inserted at the first R step, and for a transcription factor reporter visible in the G states 2 and 3. ``` julia> r=[0.038, 1.0, 0.23, 0.02, 0.25, 0.17, 0.02, 0.06, 0.02, 0.000231] 10-element Vector{Float64}: 0.038 1.0 0.23 0.02 0.25 0.17 0.02 0.06 0.02 0.000231 julia> transitions=([1, 2], [2, 1], [2, 3], [3, 1]) ([1, 2], [2, 1], [2, 3], [3, 1]) julia> h=simulator(r,transitions,3,2,2,1,nhist=150,bins=[collect(5/3:5/3:200),collect(.1:.1:20)],onstates=[Int[],[2,3]],nalleles=2) 5-element Vector{Vector}: [102.03717039741856, 142.59069980711823, 88.32384512491423, 5.3810781196239645, 11.34932791013432, 20.045265169892332, 98.28644192386656, 58.86668672945706, 84.28930404506343, 38.33804408987862 … 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] [729817, 620509, 530022, 456147, 397358, 349669, 315092, 284930, 261379, 241602 … 361, 369, 296, 300, 285, 266, 241, 216, 189, 190] [242326, 290704, 293370, 275618, 249325, 221256, 195222, 171730, 151167, 134806 … 18965, 18726, 18406, 18488, 18409, 18305, 17786, 17447, 17398, 17380] [2895640, 2557764, 2264680, 2001941, 1771559, 1567632, 1391091, 1228585, 1086723, 964156 … 7995, 7824, 7987, 7858, 8022, 7839, 7848, 7858, 7974, 7920] [116520, 116748, 115010, 115952, 114249, 114426, 114428, 113435, 113013, 112732 … 56077, 56462, 55967, 55863, 55710, 55549, 55092, 54988, 54984, 54528] ``` h is a vector containing 5 histograms. Although, not all data will include both ON and OFF time histograms, `simulator` automatically computes both. ### Units StochasticGene assumes all rates have units of inverse minutes and the half lives in the `halflives` file are in hours. When computing or fitting stationary mRNA distributions, the rate units are relative. Scaling all the rates by a constant will not affect the results. In these cases, it is sometimes convenient to scale all the rates by the mRNA decay time, which is the last entry of the rate array. The rate units matter when considering or evaluating traces and histograms of ON and OFF times. The code assumes that these dwell time histogram have units of minutes (i.e. the reciprocal of the rate units). ### API: ``` fit(; <keyword arguments> ) Fit steady state or transient GM model to RNA data for a single gene, write the result (through function finalize), and return nothing. #Arguments - `nchains::Int=2`: number of MCMC chains = number of processors called by Julia, default = 2 - `datatype::String=""`: String that desecribes data type, choices are "rna", "rnaonoff", "rnadwelltime", "trace", "tracenascent", "tracerna" - `dttype=String[]`: types are "OFF", "ON", for R states and "OFFG", "ONG" for G states - `datapath=""`: path to data file or folder or array of files or folders - `cell::String=""': cell type for halflives and allele numbers - `datacond=""`: string or vector of strings describing data treatment condition, e.g. "WT", "DMSO" or ["DMSO","AUXIN"] - `traceinfo=(1.0, 1., 240., .65)`: 4-tuple of frame interval of intensity traces, starting frame time in minutes, ending frame time (use -1 for last index), and fraction of active traces - `nascent=(1, 2)`: 2-tuple (number of spots, number of locations) (e.g. number of cells times number of alleles/cell) - `infolder::String=""`: result folder used for initial parameters - `resultfolder::String=test`: folder for results of MCMC run - `label::String=""`: label of output files produced - `inlabel::String=""`: label of files used for initial conditions - `fittedparam::Vector=Int[]`: vector of rate indices to be fit, e.g. [1,2,3,5,6,7] (applies to shared rates for hierarchical models) - `fixedeffects::Tuple=tuple()`: tuple of vectors of rates that are fixed where first index is fit and others are fixed to first, e.g. ([3,8],) means index 8 is fixed to index 3 (only first parameter should be included in fittedparam) (applies to shared rates for hierarchical models) - `transitions::Tuple=([1,2],[2,1])`: tuple of vectors that specify state transitions for G states, e.g. ([1,2],[2,1]) for classic 2 state telegraph model and ([1,2],[2,1],[2,3],[3,1]) for 3 state kinetic proof reading model - `G::Int=2`: number of gene states - `R::Int=0`: number of pre-RNA steps (set to 0 for classic telegraph models) - `S::Int=0`: number of splice sites (set to 0 for classic telegraph models and R - insertstep + 1 for GRS models) - `insertstep::Int=1`: R step where reporter is inserted - `Gfamily=""`: String describing type of G transition model, e.g. "3state", "KP" (kinetic proofreading), "cyclicory" - `root="."`: name of root directory for project, e.g. "scRNA" - `priormean=Float64[]`: mean rates of prior distribution - 'priorcv=10.`: (vector or number) coefficient of variation(s) for the rate prior distributions, default is 10. - `nalleles=2`: number of alleles, value in alleles folder will be used if it exists - `onstates::Vector{Int}=Int[]`: vector of on or sojourn states, e.g. [[2,3],Int[]], use empty vector for R states, do not use Int[] for R=0 models - `decayrate=1.0`: decay rate of mRNA, if set to -1, value in halflives folder will be used if it exists - `splicetype=""`: RNA pathway for GRS models, (e.g. "offeject" = spliced intron is not viable) - `probfn=prob_Gaussian`: probability function for hmm observation probability (i.e. noise distribution) - `noisepriors = []`: priors of observation noise (use empty set if not fitting traces), superceded if priormean is set - `hierarchical=tuple()`: empty tuple for nonhierarchical; for hierarchical model use 3 tuple of hierchical model parameters (pool.nhyper::Int,individual fittedparams::Vector,individual fixedeffects::Tuple) - `ratetype="median"`: which rate to use for initial condition, choices are "ml", "mean", "median", or "last" - `propcv=0.01`: coefficient of variation (mean/std) of proposal distribution, if cv <= 0. then cv from previous run will be used - `maxtime=Float64=60.`: maximum wall time for run, default = 60 min - `samplesteps::Int=1000000`: number of MCMC sampling steps - `warmupsteps=0`: number of MCMC warmup steps to find proposal distribution covariance - `annealsteps=0`: number of annealing steps (during annealing temperature is dropped from tempanneal to temp) - `temp=1.0`: MCMC temperature - `tempanneal=100.`: annealing temperature - `temprna=1.`: reduce rna counts by temprna compared to dwell times - `burst=false`: if true then compute burst frequency - `optimize=false`: use optimizer to compute maximum likelihood value - `writesamples=false`: write out MH samples if true, default is false - `method=1`: optional method variable, for hierarchical models method = tuple(Int,Bool) = (numerical method, true if transition rates are shared) Example: If you are in the folder where data/HCT116_testdata is installed, then you can fit the mock RNA histogram running 4 mcmc chains with $julia -p 4 julia> fits, stats, measures, data, model, options = fit(nchains = 4) ``` ``` makeswarm(;<keyword arguments>) write swarm and fit files used on biowulf #Arguments - 'nthreads::Int=1`: number of Julia threads per processesor, default = 1 - `swarmfile::String="fit"`: name of swarmfile to be executed by swarm - `juliafile::String="fitscript`: name of file to be called by julia in swarmfile - `src=""`: path to folder containing StochasticGene.jl/src (only necessary if StochasticGene not installed) and all keyword arguments of function fit(; <keyword arguments> ) see fit ``` ``` makeswarm_genes(genes::Vector{String}; <keyword arguments> ) write a swarmfile and fit files to run all each gene in vector genes # Arguments - `genes`: vector of genes - `batchsize=1000`: number of jobs per swarmfile, default = 1000 and all arguments in makeswarm(;<keyword arguments>) Examples julia> genes = ["MYC","SOX9"] julia> makeswarm(genes,cell="HBEC") ``` ``` makeswarm_genes(;<keyword arguments> ) @JuliaRegistrator register() #Arguments - `thresholdlow::Float=0`: lower threshold for halflife for genes to be fit - `threhsoldhigh::=Inf`: upper threshold and all keyword arguments in makeswarm(;<keyword arguments>) ``` ``` makeswarm(models::Vector{ModelArgs}; <keyword arguments> ) creates a run for each model #Arguments - `models::Vector{ModelArgs}`: Vector of ModelArgs structures and all keyword arguments in makeswarm(;<keyword arguments>) ``` ``` run_mh(data,model,options) returns fits, stats, measures Run Metropolis-Hastings MCMC algorithm and compute statistics of results -`data`: AbstractExperimentalData structure -`model`: AbstractGmodel structure with a logprior function -`options`: MHOptions structure model and data must have a likelihoodfn function ``` ``` write_dataframes(resultfolder::String, datapath::String; measure::Symbol=:AIC, assemble::Bool=true, fittedparams=Int[]) write_dataframes(resultfolder::String,datapath::String;measure::Symbol=:AIC,assemble::Bool=true) collates run results into a csv file Arguments - `resultfolder`: name of folder with result files - `datapath`: name of folder where data is stored - `measure`: measure used to assess winner - `assemble`: if true then assemble results into summary files ``` ``` simulator(r::Vector{Float64}, transitions::Tuple, G::Int, R::Int, S::Int, insertstep::Int; nalleles::Int=1, nhist::Int=20, onstates::Vector=Int[], bins::Vector=Float64[], traceinterval::Float64=0.0, probfn=prob_GaussianMixture, noiseparams::Int=5, totalsteps::Int=1000000000, totaltime::Float64=0.0, tol::Float64=1e-6, reporterfn=sum, splicetype="", verbose::Bool=false) Simulate any GRSM model. Returns steady state mRNA histogram. If bins not a null vector will return a vector of the mRNA histogram and ON and OFF time histograms. If traceinterval > 0, it will return a vector containing the mRNA histogram and the traces #Arguments - `r`: vector of rates - `transitions`: tuple of vectors that specify state transitions for G states, e.g. ([1,2],[2,1]) for classic 2 state telegraph model and ([1,2],[2,1],[2,3],[3,1]) for 3 state kinetic proof reading model - `G`: number of gene states - `R`: number of pre-RNA steps (set to 0 for classic telegraph models) - `S`: number of splice sites (set to 0 for G (classic telegraph) and GR models and R for GRS models) - `insertstep`: reporter insertion step #Named arguments - `nalleles`: Number of alleles - `nhist::Int`: Size of mRNA histogram - `onstates::Vector`: a vector of ON states (use empty set for any R step is ON) or vector of vector of ON states - `bins::Vector=Float64[]`: vector of time bins for ON and OFF histograms or vector of vectors of time bins - `probfn`=prob_GaussianMixture: reporter distribution - `traceinterval`: Interval in minutes between frames for intensity traces. If 0, traces are not made. - `totalsteps`::Int=10000000: maximum number of simulation steps (not usred when simulating traces) - `tol`::Float64=1e-6: convergence error tolerance for mRNA histogram (not used when simulating traces are made) - `totaltime`::Float64=0.0: total time of simulation - `splicetype`::String: splice action - `reporterfn`=sum: how individual reporters are combined - `verbose::Bool=false`: flag for printing state information #Example: julia> h=simulator(r,transitions,3,2,2,1,nhist=150,bins=[collect(5/3:5/3:200),collect(.1:.1:20)],onstates=[Int[],[2,3]],nalleles=2) ``` ``` simulate_trace_data(datafolder::String;ntrials::Int=10,r=[0.038, 1.0, 0.23, 0.02, 0.25, 0.17, 0.02, 0.06, 0.02, 0.000231,30,20,200,100,.8], transitions=([1, 2], [2, 1], [2, 3], [3, 1]), G=3, R=2, S=2, insertstep=1,onstates=Int[], interval=1.0, totaltime=1000.) create simulated trace files in datafolder ``` ``` predicted_trace(data::Union{AbstractTraceData,AbstractTraceHistogramData}, model) return predicted traces of fits using Viterbi algorithm ```
StochasticGene
https://github.com/nih-niddk-mbs/StochasticGene.jl.git
[ "MIT" ]
0.1.0
7cc6c28ac203660a43c44e7f4331148ff9542cb5
code
40
module ManyBody include("term.jl") end
ManyBody
https://github.com/tuwien-cms/ManyBody.jl.git
[ "MIT" ]
0.1.0
7cc6c28ac203660a43c44e7f4331148ff9542cb5
code
9135
export Term, creator, annihilator, occupation, vacancy """ Represent product of fermionic creation/annihilation operators. For a Fock space of flavours, this is an abstract representation of the product of an arbitrary number of creation and annihilation operators, not necessarily normal ordered. One can write each such product in a canonical form: t(v,i,j,k) = v * prod(x -> c[x]', i) * prod(x -> c[x], reverse(j)) * prod(x -> c[x]*c[x]', k) where `i`, `j` are tuples of flavours, each one ordered ascendingly, and `k` is a tuple of flavours disjoint from both `i` and `j`. Note that above expression is not a normal-ordered product either, but a "classification" of each flavour with respect to the term's effect. Instead of the `O(2^(2n))` dense or `O(2^n)` sparse storage required for the elements of such a product, this class stores only an `O(1)` set of bitfields allowing for fast on-the-fly computation. """ struct Term{T} mask::UInt64 left::UInt64 right::UInt64 change::UInt64 sign_mask::UInt64 value::T end """Conversion between terms types""" Term{T}(term::Term{U}) where {T, U} = Term(term, U(term.value)) """Convert term to itself""" Term{T}(term::Term{T}) where {T} = term """Create a term from template, but assign new value to it""" Term(term::Term, new_value) = Term(term.mask, term.left, term.right, term.change, term.sign_mask, new_value) """Constant term (energy shift)""" Term(value::Number) = Term(UInt64(0), UInt64(0), UInt64(0), UInt64(0), UInt64(0), value) """Make creation operator""" function creator(i::Integer; value=Int8(1), statmask::UInt64=~UInt64(0)) @boundscheck (i >= 1 && i <= 64) || throw(BoundsError(1:64, i)) mask = UInt64(1) << (i - 1) signmask = (mask - one(mask)) & statmask return Term(mask, mask, zero(mask), mask, signmask, value) end """Make annihilation operator""" function annihilator(i::Integer; value=Int8(1), statmask::UInt64=~UInt64(0)) @boundscheck (i >= 1 && i <= 64) || throw(BoundsError(1:64, i)) mask = UInt64(1) << (i - 1) signmask = (mask - one(mask)) & statmask return Term(mask, zero(mask), mask, mask, signmask, value) end """Make occupation (number) operator""" function occupation(i::Integer; value=Int8(1)) @boundscheck (i >= 1 && i <= 64) || throw(BoundsError(1:64, i)) mask = UInt64(1) << (i - 1) return Term(mask, mask, mask, zero(mask), zero(mask), value) end """Make vacancy (1 - number) operator""" function vacancy(i::Integer; value=Int8(1)) @boundscheck (i >= 1 && i <= 64) || throw(BoundsError(1:64, i)) mask = UInt64(1) << (i - 1) return Term(mask, zero(mask), zero(mask), zero(mask), zero(mask), value) end """Multiplies two terms""" function Base.:*(a::Term, b::Term) # Get value first, mainly to determine the type of result and ensure # type stability. We have to make sure to get a signed type here, as # the sign may flip later (this is handled in a specialization). value = a.value * b.value # First, take care of the Pauli principle. This is relatively easy, as # a.right and b.left are the "demands" of the two terms on their in-between # state, each confined to their mask. This means we simply have to fulfill # both demands whenever the masks intersect. intersect = a.mask & b.mask if xor(a.right, b.left) & intersect != 0 return Term(zero(value)) end # Now that we know that the term is valid, let us determine the left and # right outer states: a.left and b.right are again demands on those states, # each confined to their mask. Outside the mask, the other term may make # demands "through" the adjacent term. mask = a.mask | b.mask right = b.right | (a.right & ~b.mask) left = a.left | (b.left & ~a.mask) change = xor(left, right) # Each fundamental operator comes with a sign mask extending to the less # significant side of it. Ignoring the flavours affected by the term for # the moment, multiplying terms simply means xor'ing the masks. sign_mask = xor(a.sign_mask, b.sign_mask) # Note that here, the order matters: for a normal-ordered term, we assume # that: # # ψ_L = c[i[1]]' * ... * c[i[n]]' * c[j[n]] * ... * c[j[1]] ψ_R # # where both i and j are ordered ascendingly. This is because we can then # split this equation into two parts: # # ψ_L = c[i[1]]' * ... * c[i[n]]' ψ_0 # ψ_R = c[j[1]]' * ... * c[j[n]]' ψ_0 # # This means that for determining the sign, the intermediate state ψ_0 is # relevant, and so for a sign computation we must exclude any flavour in # ψ_L and ψ_R affected by the creators/annihilators. sign_mask &= ~mask # Finally we have to restore normal ordering by permuting operators. We # know this may only yield a global sign. So, we simply observe the # difference in effect of the product and normal-ordered product on a # single contributing "trial" state. We choose the trial to be `right`, # as we know the normal-ordered product contributes and does not produce # a sign. trial = right permute = trial & b.sign_mask trial = xor(trial, b.change) permute = xor(permute, trial & a.sign_mask) value = copy_parity(permute, value) return Term(mask, left, right, change, sign_mask, value) end # This ensures type-stability is observed. Base.:*(a::Term{A}, b::Term{B}) where {A <: Unsigned, B <: Unsigned} = Term(a, signed(a.value)) * Term(b, signed(b.value)) """Check if state is mapped when multiplied by term from the left""" is_mapped_right(t::Term, state) = state & t.mask == t.right """Check if state is mapped when multiplied by term from the right""" is_mapped_left(t::Term, state) = state & t.mask == t.left """Change sign of number if parity of a bit pattern is odd""" copy_parity(pattern::Integer, number) = (count_ones(pattern) & 1 != 0) ? -number : number # We use this to ensure type stability: otherwise, passing an unsigned # number would have to return a union, as -x converts it to a signed one. # We could silently use signed() here, but it is better to handle this # explicitly in application code. copy_parity(::Integer, ::Unsigned) = throw(DomainError("Cannot copy parity sign to unsigned number")) """Map a state through term, assuming that it is indeed mapped""" map_state_right(t::Term, state) = xor(state, t.change), copy_parity(state & t.sign_mask, t.value) """Map a state through term, assuming that it is indeed mapped""" map_state_left(t::Term, state) = map_state_right(t, state) """ Return the state shift through the term. Index of the side diagonal where the values of term are nonzero, or, equivalently, a state with index `i` is mapped by `term` to either nothing or a state with index `i + state_shift(term)`. """ state_shift(t::Term) = (t.left - t.right) % Int64 """Check if terms can be added and give one term""" addable(a::Term, b::Term) = a.mask == b.mask && a.right == b.right && a.left == b.left """Convert terms with values of one type to another""" Base.convert(::Type{Term{T}}, term::Term) where T = Term(term, convert(T, term.value)) """Promotion rules""" Base.promote_rule(::Type{Term{T}}, ::Type{Term{U}}) where {T, U} = Term{promote_type(T, U)} """Promotion rules""" Base.promote_rule(::Type{Term{T}}, ::Type{Term{U}}) where {T <: Unsigned, U <: Unsigned} = Term{promote_type(signed(T), signed(U))} """Explicit plus of term""" Base.:+(term::Term) = Term(term, +term.value) """Negate term""" Base.:-(term::Term) = Term(term, -term.value) """Scale term by a scalar factor""" Base.:*(factor::Number, term::Term) = Term(term, factor * term.value) """Scale term by a scalar factor""" Base.:*(term::Term, factor::Number) = Term(term, term.value * factor) """Add terms with the same operators""" Base.:+(a::Term, b::Term) = Term(_check_addable(a, b), a.value + b.value) """Subtract terms with the same operators""" Base.:-(a::Term, b::Term) = Term(_check_addable(a, b), a.value - b.value) """Check if terms are equal""" Base.:(==)(lhs::Term, rhs::Term) = addable(lhs, rhs) && lhs.value == rhs.value """Check if terms are approximately equal""" function Base.isapprox(lhs::Term, rhs::Term; atol::Real=0, rtol::Real=Base.rtoldefault(lhs.value, rhs.value, atol), nans::Bool=false) return addable(lhs, rhs) && isapprox(lhs.value, rhs.value; atol, rtol, nans) end """Get the transpose of a term""" Base.transpose(t::Term) = Term(t.mask, t.right, t.left, t.change, t.sign_mask, t.value) """Get the adjoint (conjugate transpose) of a term""" Base.adjoint(t::Term) = Term(t.mask, t.right, t.left, t.change, t.sign_mask, conj(t.value)) """Get term like template, but with zero value""" Base.zero(t::Term) = Term(t, zero(t.value)) """Check if the value of term is zero""" Base.iszero(t::Term) = iszero(t.value) function _check_addable(a::Term, b::Term) if !addable(a, b) throw(ArgumentError("can only add terms which have same operators")) end return a end
ManyBody
https://github.com/tuwien-cms/ManyBody.jl.git
[ "MIT" ]
0.1.0
7cc6c28ac203660a43c44e7f4331148ff9542cb5
code
63
using Test @testset "ManyBody" begin include("term.jl") end
ManyBody
https://github.com/tuwien-cms/ManyBody.jl.git
[ "MIT" ]
0.1.0
7cc6c28ac203660a43c44e7f4331148ff9542cb5
code
1207
using Test using ManyBody using LinearAlgebra @testset "Term" begin @testset "pauli" begin @test iszero(zero(Term(1.0))) @test iszero(creator(3) * creator(3)) @test iszero(creator(1) * annihilator(4) * annihilator(4)) end @testset "convert" begin @test Term(2.0) == Term(2) @test creator(3) == Term{Int64}(creator(3)) end @testset "normal ordering" begin c = annihilator cdag = creator t = cdag(7) * cdag(4) * c(2) * c(6) @test -t == cdag(4) * cdag(7) * c(2) * c(6) @test t == cdag(4) * cdag(7) * c(6) * c(2) t2 = c(9) * c(5) * c(3) @test t * t2 == +cdag(4) * cdag(7) * c(9) * c(6) * c(5) * c(3) * c(2) # Sign not sure @test t2 * t == +cdag(4) * cdag(7) * c(9) * c(6) * c(5) * c(3) * c(2) end @testset "vacancy" begin c = annihilator cdag = creator n = occupation v = vacancy t1 = 10 * n(2) @test t1 * t1 == 10 * t1 t1 = 4 * v(4) @test t1 * t1 == 4 * t1 t1 = 3 * c(3) * v(2) * cdag(1) @test t1 * v(2) == t1 end @testset "quadraticterm" begin t = 2.0 * creator(1) * annihilator(3) tprime = 2.0 * creator(3) * annihilator(1) @test t' == tprime @test transpose(t) == tprime end end
ManyBody
https://github.com/tuwien-cms/ManyBody.jl.git
[ "MIT" ]
0.1.0
7cc6c28ac203660a43c44e7f4331148ff9542cb5
docs
82
Tools for quantum many-body computations ========================================
ManyBody
https://github.com/tuwien-cms/ManyBody.jl.git
[ "MIT" ]
0.1.0
f69915b68a2fb7b5d0d41ff0584e6fa05a9853e5
code
5226
module ComplexOperations export complex_multiply export complex_divide export complex_vector_dot_product export complex_vector_cross_product export complex_matrix_inversion export complex_matrix_multiplication """ Multiplication of two vectors Z1 and Z2. We assume the first and second columns of each vector are the real and imaginary parts, respectively Each of Z1 and Z2 has two columns, and arbitrary number of rows. Multiplication algorithm for complex numbers can be found here: https://en.wikipedia.org/wiki/Multiplication_algorithm """ function complex_multiply(Z1, Z2) return vcat(complex_multiply.(Z1[:,1], Z1[:,2], Z2[:,1], Z2[:,2])...) end """ Multiplication of two vectors Z1=a+im*b and Z2=c+im*d. a, b, c, and d are all real numbers or arrays of real numbers. All shoud have the same size. Multiplication algorithm for complex numbers can be found here: https://en.wikipedia.org/wiki/Multiplication_algorithm """ function complex_multiply(a, b, c, d) # return hcat(a * c - b * d, b * c + a * d) return @fastmath @inbounds hcat(a .* c - b .* d, b .* c + a .* d) end """ Division of two vectors Z1 and Z2. We assume the first and second columns of each vector are the real and imaginary parts, respectively Each of Z1 and Z2 has two columns, and arbitrary number of rows. Division algorithm for complex numbers can be found here: https://en.wikipedia.org/wiki/Multiplication_algorithm """ function complex_divide(Z1, Z2) return vcat(complex_divide.(Z1[:,1], Z1[:,2], Z2[:,1], Z2[:,2])...) end """ Division of two vectors Z1=a+im*b and Z2=c+im*d. a, b, c, and d are all real numbers or arrays of real numbers. All shoud have the same size. Division algorithm for complex numbers can be found here: https://en.wikipedia.org/wiki/Multiplication_algorithm """ function complex_divide(a, b, c, d) return @fastmath @inbounds hcat((a .* c + b .* d) / (c.^2 + d.^2), (b .* c - a .* d) / (c.^2 + d.^2)) end """ Claculate dot product of two vectors Each is represented as 3x2 or 3x1 Array. The first and second columns represent the real and imag parts, respectively For real vectors, we can input them as 3x1 Array or 3-element Vector """ function complex_vector_dot_product(A, B) # TODO: how can I create two methods, rather than the if-statements? if size(A, 2) == 1; A = hcat(A, [0,0,0]); end # TODO: is there a better way to handle 3x2 and 3x1 vectors? if size(B, 2) == 1; B = hcat(B, [0,0,0]); end # TODO: is there a better way to handle 3x2 and 3x1 vectors? return complex_vector_dot_product(A[:,1], A[:,2], B[:,1], B[:,2]) end """ Claculate dot product of two vectors, inputs are real and imaginary parts of the two vectors Each is represented as 3-element array. """ function complex_vector_dot_product(A_r, A_i, B_r, B_i) return ( complex_multiply(A_r[1], A_i[1], B_r[1], B_i[1]) + complex_multiply(A_r[2], A_i[2], B_r[2], B_i[2]) + complex_multiply(A_r[3], A_i[3], B_r[3], B_i[3]) ) end """ Claculate cross product of two vectors Each is represented as 3x2 or 3x1 Array. The first and second columns represent the real and imag parts, respectively For real vectors, we can input them as 3x1 Array or 3-element Vector """ function complex_vector_cross_product(A, B) if size(A, 2) == 1; A = hcat(A, [0,0,0]); end # TODO: is there a better way to handle 3x2 and 3x1 vectors? if size(B, 2) == 1; B = hcat(B, [0,0,0]); end # TODO: is there a better way to handle 3x2 and 3x1 vectors? return complex_vector_cross_product(A[:,1], A[:,2], B[:,1], B[:,2]) end """ Claculate cross product of two vectors, inputs are real and imaginary parts of the two vectors Each is represented as 3-element array. """ function complex_vector_cross_product(A_r, A_i, B_r, B_i) vcat( complex_multiply(A_r[2], A_i[2], B_r[3], B_i[3]) - complex_multiply(A_r[3], A_i[3], B_r[2], B_i[2]), complex_multiply(A_r[3], A_i[3], B_r[1], B_i[1]) - complex_multiply(A_r[1], A_i[1], B_r[3], B_i[3]), complex_multiply(A_r[1], A_i[1], B_r[2], B_i[2]) - complex_multiply(A_r[2], A_i[2], B_r[1], B_i[1]), ) end """ Calculate the inverse of a complex matrix A+iB, where A and B are real matrices There are two possible versions: Version #1: This one preallocate. Faster and use more memory for 1M evaluations: 1.771474 seconds (14.18 M allocations: 4.510 GiB, 4.52% gc time, 6.40% compilation time) ` function complex_matrix_inversion(A, B) inv_A_B = inv(A) * B C = inv(A + B * inv_A_B) D = -inv_A_B * C return C, D end ` Version #2: No preallocation. Slower and use less memory for 1M evaluations: 2.330454 seconds (19.00 M allocations: 6.512 GiB, 2.71% gc time) ` function complex_matrix_inversion(A, B) C = inv(A + B * inv(A) * B) D = -1 .* inv(A) * B * C return C, D end ` """ function complex_matrix_inversion(A, B) @fastmath @inbounds inv_A_B = inv(A) * B @fastmath @inbounds C = inv(A + B * inv_A_B) @fastmath @inbounds D = -inv_A_B * C return C, D end """ Multiply two matrices A+iB and C+iD, where A,B,C,D are real matrices """ function complex_matrix_multiplication(A, B, C, D) return @fastmath @inbounds (A * C - B * D, A * D + B * C) end end # module
ComplexOperations
https://github.com/mhmodzoka/ComplexOperations.jl.git
[ "MIT" ]
0.1.0
f69915b68a2fb7b5d0d41ff0584e6fa05a9853e5
code
934
using ComplexOperations using LinearAlgebra # testing complex_matrix_inversion A = rand(3, 3); B = rand(3, 3) @time for i = 1:1e6; C, D = complex_matrix_inversion(A, B); end @time for i = 1:1e6; Z = inv(A + im * B); end C, D = complex_matrix_inversion(A, B) Z = inv(A + im * B) Z == complex.(C, D) # TODO: why there is a small difference? # testing complex_vector_cross_product A_r = [1,2,3]; A_i = [1, 20, 30] B_r = [10,2,30]; B_i = [1, 2, 3] @time AB = complex_vector_cross_product(A_r, A_i, B_r, B_i) @time AB_ = complex_vector_cross_product(hcat(A_r, A_i), hcat(B_r, B_i)) @time AB__ = cross(A_r + im * A_i, B_r + im * B_i) # testing complex_vector_dot_product A_r = [1,2,3]; A_i = [1, 20, 30] B_r = [10,2,30]; B_i = [1, 2, 3] @time AB = complex_vector_dot_product(A_r, A_i, B_r, B_i) @time AB_ = complex_vector_dot_product(hcat(A_r, A_i), hcat(B_r, B_i)) @time AB__ = Tmatrix.vector_dot_product(A_r + im * A_i, B_r + im * B_i)
ComplexOperations
https://github.com/mhmodzoka/ComplexOperations.jl.git
[ "MIT" ]
0.1.0
f69915b68a2fb7b5d0d41ff0584e6fa05a9853e5
docs
925
# ComplexOperations.jl Perform basic operations on complex numbers. Complex numbers are represented as 2-element vectors. Operations include: - complex scalar operations - scalar multiplications (`complex_multiply`) - scalar division (`complex_divide`) - complex vector operations - vector dot product (`complex_vector_dot_product`) - vector cross product (`complex_vector_cross_product`) - complex matrix operations - matrix multiplication (`complex_matrix_multiplication`) - matrix inversion (`complex_matrix_inversion`) # Installation The package should be registered, and can be installed by executing the following command: `using Pkg; Pkg.add(ComplexOperations)` If this fails (e.g., if registering the package didn't work), then you can install it by opening an interactive julia session, and type the following command: `using Pkg; Pkg.add(url="https://github.com/mhmodzoka/ComplexOperations.jl")`
ComplexOperations
https://github.com/mhmodzoka/ComplexOperations.jl.git
[ "MIT" ]
0.5.5
bb21a5a9b9f6234f367ba3d47d3b3098b3911788
code
2566
using Documenter, DemoCards, JSON using PlutoStaticHTML # add the docstring for Pluto notebooks # 1. generate demo files quickstart, postprocess_cb, quickstart_assets = makedemos("quickstart") themeless_demopage, themeless_cb, themeless_assets = makedemos(joinpath("theme_gallery", "themeless")) grid_demopage, grid_cb, grid_assets = makedemos(joinpath("theme_gallery", "grid")) list_demopage, list_cb, list_assets = makedemos(joinpath("theme_gallery", "list")) nocoverlist_demopage, nocoverlist_cb, nocoverlist_assets = makedemos(joinpath("theme_gallery", "nocoverlist")) bulmagrid_demopage, bulmagrid_cb, bulmagrid_assets = makedemos(joinpath("theme_gallery", "bulmagrid")) bokehlist_demopage, bokehlist_cb, bokehlist_assets = makedemos(joinpath("theme_gallery", "bokehlist")) assets = collect(filter(x->!isnothing(x), Set([quickstart_assets, themeless_assets, grid_assets, list_assets, nocoverlist_assets, bulmagrid_assets, bokehlist_assets]))) # 2. normal Documenter usage format = Documenter.HTML(edit_link = "master", prettyurls = get(ENV, "CI", nothing) == "true", assets = assets, size_threshold=1024 * 1024) makedocs(format = format, pages = [ "Home" => "index.md", quickstart, "Concepts" => "concepts.md", "Partial build" => "preview.md", "Structure manipulation" => "structure.md", "Pluto.jl support" => "pluto.md", "Theme Gallery" => [ themeless_demopage, grid_demopage, bulmagrid_demopage, list_demopage, nocoverlist_demopage, bokehlist_demopage, ], "Package References" => "references.md" ], sitename = "DemoCards.jl") # 3. postprocess after makedocs postprocess_cb() themeless_cb() bulmagrid_cb() bokehlist_cb() grid_cb() list_cb() nocoverlist_cb() # a workdaround to github action that only push preview when PR has "push_preview" labels # issue: https://github.com/JuliaDocs/Documenter.jl/issues/1225 function should_push_preview(event_path = get(ENV, "GITHUB_EVENT_PATH", nothing)) event_path === nothing && return false event = JSON.parsefile(event_path) haskey(event, "pull_request") || return false labels = [x["name"] for x in event["pull_request"]["labels"]] return "push_preview" in labels end # 4. deployment deploydocs(repo = "github.com/JuliaDocs/DemoCards.jl.git", push_preview = should_push_preview())
DemoCards
https://github.com/JuliaDocs/DemoCards.jl.git
[ "MIT" ]
0.5.5
bb21a5a9b9f6234f367ba3d47d3b3098b3911788
code
406
#--- #hidden: true #id: hidden_card #--- # # This is a hidden card # This card doesn't get displayed in [quickstart index page](@ref quickstart) page and can only be # viewed with relink `[hidden card](@ref hidden_card)`. # Note that hidden cards are still processed by DemoCards to get you necessary assets. using ImageCore, ImageTransformations, TestImages imresize(testimage("camera"); ratio=0.25)
DemoCards
https://github.com/JuliaDocs/DemoCards.jl.git