aboutsummaryrefslogtreecommitdiff
path: root/src/SeqSpace.jl
blob: ccb92f44016b6d7b53563b5bb0f9df2b657862d7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
module SeqSpace

using GZip
using BSON: @save
using LinearAlgebra: norm, svd, Diagonal
using Statistics: quantile, std
using Flux, Zygote
using ProgressMeter

import BSON

include("io.jl")
include("rank.jl")
include("model.jl")
include("voronoi.jl")
include("pointcloud.jl")
include("generate.jl")
include("normalize.jl")
include("manifold.jl")
include("infer.jl")
include("scrna.jl")

using .PointCloud, .DataIO, .SoftRank, .ML

export Result, HyperParams
export linearprojection, fitmodel, extendfit
export marshal, unmarshal

# ------------------------------------------------------------------------
# globals

# ------------------------------------------------------------------------
# types

"""
    mutable struct HyperParams
        dₒ :: Int
        Ws :: Array{Int,1}
        BN :: Array{Int,1}
        DO :: Array{Int,1}
        N  :: Int
        δ  :: Int
        η  :: Float64
        B  :: Int
        V  :: Int
        k  :: Int
        γₓ :: Float32
        γᵤ :: Float32
        g  :: Function
    end

HyperParams is a collection of parameters that specify the network architecture and training hyperparameters of the autoencoder.
`dₒ` is the desired output dimensionality of the encoding layer
`Ws` is a collection of the network layer widths. The number of entries controls the depth. The decoder is mirror-symmetric.
`BN` is the collection of layers that will be _followed_ by batch normalization.
`DO` is the collection of layers that will be _followed_ by dropout.
`N`  is the number of epochs to train against
`δ`  is the number of epochs that will be sampled for logging
`η`  is the learning rate
`B`  is the batch size
`V`  is the number of points to partition for validation purposes, i.e. won't be training against
`k`  is the number of neighbors to use to estimate geodesics
`γₓ` is the prefactor of distance soft rank loss
`γᵤ` is the prefactor of uniform density loss
`g ` is the metric given to latent space
"""
mutable struct HyperParams
    dₒ :: Int          # output dimensionality
    Ws :: Array{Int,1} # (latent) layer widths
    BN :: Array{Int,1} # (latent) layers followed by batch normalization
    DO :: Array{Int,1} # (latent) layers followed by drop outs
    N  :: Int          # number of epochs to run
    δ  :: Int          # epoch subsample factor for logging
    η  :: Float64      # learning rate
    B  :: Int          # batch size
    V  :: Int          # number of points to partition for validation
    k  :: Int          # number of neighbors to use to estimate geodesics
    γₓ :: Float32      # prefactor of distance soft rank loss
    γᵤ :: Float32      # prefactor of uniform density loss
    g  :: Function     # metric given to latent space
end

"""
    euclidean²(x)

Generate the matrix of pairwise distances between vectors `x`, assuming the Euclidean metric.
`x` is assumed to be ``d \times N`` where ``d`` denotes the dimensionality of the vector and ``N`` denotes the number.
"""
const euclidean²(x) = sum( (x[d,:]' .- x[d,:]).^2 for d in 1:size(x,1) )

"""
    cylinders²(x)

Generate the matrix of pairwise distances between vectors `x`, assuming the points are distributed on a cylinder.
`x` is assumed to be ``d \times N`` where ``d`` denotes the dimensionality of the vector and ``N`` denotes the number.
The first coordinate of `x` is assumed to be the polar coordinate.
"""
function cylinder²(x)
    c = cos.(π.*(x[1,:]))
    s = sin.(π.*(x[1,:]))

    return (c' .- c).^2 .+ (s' .- s).^2 .+ euclidean²(x[2:end,:])
end

HyperParams(; dₒ=2, Ws=Int[], BN=Int[], DO=Int[], N=200, δ=10, η=1e-3, B=64, V=1, k=12, γₓ=1, γᵤ=1e-1, g=euclidean²) = HyperParams(dₒ, Ws, BN, DO, N, δ, η, B, V, k, γₓ, γᵤ, g)

"""
    struct Result
        param :: HyperParams
        loss  :: NamedTuple{(:train, :valid), Tuple{Array{Float64,1},Array{Float64,1}} }
        model
    end

Store the output of a trained autoencoder.
`param` stores the input hyperparameters used to design and train the neural network.
`loss` traces the dynamics of the optimization found during training.
`model` represents the learned pullback and pushforward functions.
"""
struct Result
    param :: HyperParams
    loss  :: NamedTuple{(:train, :valid), Tuple{Array{Float64,1},Array{Float64,1}} }
    model
end

"""
    marshal(r::Result)

Serialize a trained autoencoder to binary format suitable for disk storage.
Store parameters of model as contiguous array
"""
function marshal(r::Result)
    # trainable parameters
    ω₁ = r.model.pullback    |> cpu |> Flux.params |> collect
    ω₂ = r.model.pushforward |> cpu |> Flux.params |> collect

    # untrainables
    β₁ = [ (μ=layer.μ,σ²=layer.σ²) for layer in r.model.pullback.layers    if isa(layer,Flux.BatchNorm) ]
    β₂ = [ (μ=layer.μ,σ²=layer.σ²) for layer in r.model.pushforward.layers if isa(layer,Flux.BatchNorm) ]

    return Result(r.param,r.loss,
            (
                pullback=(
                    params=ω₁,
                    batchs=β₁,
                ),
                pushforward=(
                    params=ω₂,
                    batchs=β₂,
                ),
                size=size(r.model.pullback.layers[1].weight,2)
            )
    )
end

"""
    unmarshal(r::Result)

Deserialize a trained autoencoder from binary format to semantic format.
Represents model as a collection of functors.
"""
function unmarshal(r)
    autoencoder = model(r.model.size, r.param.dₒ;
          Ws         = r.param.Ws,
          normalizes = r.param.BN,
          dropouts   = r.param.DO
    )

    Flux.loadparams!(autoencoder.pullback,    r.model.pullback.params)
    Flux.loadparams!(autoencoder.pushforward, r.model.pushforward.params)
    Flux.trainmode!(autoencoder.identity, false)

    i = 1
    for layer in autoencoder.pullback.layers
        if isa(layer, Flux.BatchNorm)
            layer.μ  = r.model.pullback.batchs[i].μ
            layer.σ² = r.model.pullback.batchs[i].σ²
            i += 1
        end
    end

    i = 1
    for layer in autoencoder.pushforward.layers
        if isa(layer, Flux.BatchNorm)
            layer.μ  = r.model.pushforward.batchs[i].μ
            layer.σ² = r.model.pushforward.batchs[i].σ²
            i += 1
        end
    end

    param = HyperParams(;
        dₒ = r.param.dₒ,
        Ws = r.param.Ws,
        BN = r.param.BN,
        DO = r.param.DO,
        N  = r.param.N,
        δ  = r.param.δ,
        η  = r.param.η,
        B  = r.param.B,
        V  = r.param.V,
        k  = r.param.k,
        γₓ = r.param.γₓ,
        γᵤ = r.param.γᵤ,
    )

    return Result(param, r.loss, autoencoder)
end

# ------------------------------------------------------------------------
# utility functions

# α := rescale data by
# δ := subsample data by
function pointcloud(;α=1, δ=1)
    verts, _ = open("$root/gut/mesh_apical_stab_000153.ply") do io
        read_ply(io)
    end

    return α*vcat(
        map(v->v.x, verts)',
        map(v->v.y, verts)',
        map(v->v.z, verts)'
    )[:,1:δ:end]
end

function expression(;raw=false)
    scrna, genes, _  = if raw
        GZip.open("$root/dvex/dge_raw.txt.gz") do io
            read_matrix(io; named_cols=false, named_rows=true)
        end
    else
        GZip.open("$root/dvex/dge_normalized.txt.gz") do io
            read_matrix(io; named_cols=true, named_rows=true)
        end
    end

    return scrna, genes
end

# ------------------------------------------------------------------------
# i/o

# assumes a BSON i/o
function load(io::IO)
    database = BSON.parse(io)
    result, input = database[:result], database[:in]
end

mean(x) = length(x) > 0 ? sum(x) / length(x) : 0
mean(x::Matrix;dims=1) = sum(x;dims=dims) / size(x,dims)

function cor(x, y)
    μ = (
        x=mean(x),
        y=mean(y)
    )
    var = (
       x=mean(x.^2) .- μ.x^2,
       y=mean(y.^2) .- μ.y^2
    )

    return (mean(x.*y) .- μ.x.*μ.y) / sqrt(var.x*var.y)
end

"""
    buildloss(model, D², param)

Return a loss function used to train a neural network `model` according to input hyperparameters `param`.
`model` is a object with three fields, `pullback`, `pushforward`, and `identity`.
`pullback` and `pushforward` refers to the encoder and decoder layers respectively, while the identity is the composition.
`D²` is a matrix of pairwise distances that will be used as a quenched hyperparameter in the distance soft rank loss.
"""
function buildloss(model, , param)
    return function(x, i::T, output::Bool) where T <: AbstractArray{Int,1}
        z = model.pullback(x)
        y = model.pushforward(z)

        # reconstruction loss
        ϵᵣ = sum(sum((x.-y).^2, dims=2)) / sum(sum(x.^2,dims=2))

        # distance softranks
        Dz² = param.g(z)
        Dx² = [i,i]

        dx, dz = PointCloud.upper_tri(Dx²), PointCloud.upper_tri(Dz²)
        rx, rz = softrank(dx ./ mean(dx)), softrank(dz ./ mean(dz))
        ϵₓ = 1 - cor(1 .- rx, 1 .- rz)
        #=
        ϵₓ = mean(
            let
                dx, dz = Dx²[:,j], Dz²[:,j]
                rx, rz = softrank(dx ./ mean(dx)), softrank(dz ./ mean(dz))
                1 - cor((1 .- rx).^2, (1 .- rz).^2)
            end for j ∈ 1:size(Dx²,2)
        )
        =#

        ϵᵤ = mean(
            let
                zₛ = sort(z[d,:])
                mean( ( (2*i/length(zₛ)-1) - s)^2 for (i,s) in enumerate(zₛ) )
            end for d  1:size(z,1)
        )
 
        #=
        ϵᵤ = let
            a = Voronoi.volumes(z)
            std(a) / mean(a)
        end
        =#

        if output
            println(stderr, "ϵᵣ=$(ϵᵣ), ϵₓ=$(ϵₓ), ϵᵤ=$(ϵᵤ)")
        end

        return ϵᵣ + param.γₓ*ϵₓ + param.γᵤ*ϵᵤ
    end
end

# ------------------------------------------------------------------------
# main functions

"""
    linearprojection(x, d; Δ=1, Λ=nothing)

Project an empirical distance matrix `x` onto `d` top principal components.
Centers the result to have zero mean.
Returns the projection, as well as a function to transform a projected vector back to the embedding space.
Ignores top `Δ` principal components.
If `Λ` is not nothing, assumes it is a precomputed SVD decomposition.
"""
function linearprojection(x, d; Δ=1, Λ=nothing)
    Λ = isnothing(Λ) ? svd(x) : Λ

    ι = (1:d) .+ Δ
    ψ = Diagonal(Λ.S[ι])*Λ.Vt[ι,:]
    μ = mean(ψ, dims=2)

    x₀ = (Δ > 0) ? Λ.U[:,1:Δ]*Diagonal(Λ.S[1:Δ])*Λ.Vt[1:Δ,:] : 0

    embed(x)   = (x₀ .+ (Λ.U[:,ι]*(x.+μ)))
    embed(x,i) = (x₀ .+ (Λ.U[:,ι]*(x.+μ[i])))

    return (
        embed      = embed,
        projection = (ψ .- μ),
    )
end

"""
    fitmodel(data, param; D²=nothing, chatty=true)

Train an autoencoder model, specified with `param` hyperparams, to fit `data`.
`data` is assumed to be sized ``d \times N`` where ``d`` and ``N`` are dimensionality and cardinality respectively.
If not nothing, `D²` is assumed to be a precomputed distance matrix of point cloud `data`.
If `chatty` is true, function will print to `stdout`.
Returns a `Result` type.
"""
function fitmodel(data, param; =nothing, chatty=true)
     = isnothing() ? geodesics(data, param.k).^2 : 

    M = model(size(data,1), param.dₒ;
          Ws         = param.Ws,
          normalizes = param.BN,
          dropouts   = param.DO
    )

    nvalid = size(data,2) - ((size(data,2)÷param.B)-param.V)*param.B
    batch, index = validate(data, nvalid)

    loss = buildloss(M, , param)
    E    = (
        train = Float64[],
        valid = Float64[]
    )

    progress = Progress(param.N; desc=">training model", output=stderr)
    log = (n) -> begin
        if (n-1) % param.δ == 0
            push!(E.train,loss(batch.train, index.train, chatty))
            push!(E.valid,loss(batch.valid, index.valid, chatty))
        end

        next!(progress)

        nothing
    end

    Flux.trainmode!(M.identity, true)
    train!(M, batch.train, index.train, loss;
        η   = param.η,
        B   = param.B,
        N   = param.N,
        log = log
    )
    Flux.trainmode!(M.identity, false)

    return Result(param, E, M), (batch=batch, index=index, =, log=log)
end

"""
    extendfit(result::Result, input, epochs)

Retrain model within `result` on `input` data for `epochs` more iterations.
Returns a new `Result`.
"""
function extendfit(result::Result, input, epochs)
    loss = buildloss(result.model, input., result.param)
    train!(result.model, input.y.train, input.index.train, loss; 
        η   = result.param.η,
        B   = result.param.B,
        N   = epochs,
        log = input.log
    )

    return result, input
end

end