trainRBF_ARX.jl 24.6 KB
Newer Older
Fredrik Bagge Carlson's avatar
Fredrik Bagge Carlson committed
1
2
using Devectorize
using Clustering
3
4
5
# using Debug
include("levenberg_marquardt.jl")
include("../cuckooSearch.jl")
Fredrik Bagge Carlson's avatar
Fredrik Bagge Carlson committed
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

type RbfNonlinearParameters
    x::Vector{Float64}
    n_state::Integer
    n_centers::Integer
end


# for op = (:+, :*, :\, :/)
#     @eval ($op)(a::RbfNonlinearParameters,b) = ($op)(a.x,b)
#     @eval ($op)(b,a::RbfNonlinearParameters) = ($op)(b,a.x)
# end

Base.display(p::RbfNonlinearParameters) = println("RbfNonlinearParameters: Parameters = $(length(p.x)), n_state(x) = $(p.n_state), n_centers(x) = $(p.n_centers)")
Base.start(p::RbfNonlinearParameters) =  1
Base.done(p::RbfNonlinearParameters, state) = state > p.n_centers
Base.next(p::RbfNonlinearParameters, state) = (p.x[1+(state-1)*2*p.n_state:state*2p.n_state])::VecOrMat, state + 1
"""Train your RBF-ARX network.`trainRBF_ARX(y, na, nc; state = :A, liniters=3,nonliniters=50, normalized=false, initialcenters="equidistant", inputpca=false, outputnet = true, cuckoosearch = false)`\n
The number of centers is equal to `nc` if Kmeans is used to get initial centers, otherwise the number of centers is `nc^n_state`\n
`n_state` is equal to the state dimension, possibly reduced to `inputpca` if so desired.\n
The number of nonlinear parameters is `n_centers × n_state`\n
The number of linear parameters is `outputnet ? n_state × (n_centers+1) × (na)+1) : (na)×(n_centers+1)+1)`"""
Fredrik Bagge Carlson's avatar
Fredrik Bagge Carlson committed
28
function trainRBF_ARX(y, A, state, nc; liniters=3,nonliniters=50, normalized=false, initialcenters="equidistant", inputpca=false, outputnet = true, cuckoosearch = false, cuckooiter=100, timeout=60)
Fredrik Bagge Carlson's avatar
Fredrik Bagge Carlson committed
29
30
31
32
33
    n_points = length(y)
    na = isa(A,Matrix) ? size(A,2) : 1

    function predictionerror(z)
        znl = RbfNonlinearParameters(z,n_state,n_centers)
34
35
        psi = getΨ(Ψ, znl, state, n_points, n_state, normalized)
        getLinearRegressor(V,psi,A,state,outputnet,na,n_state,n_centers,n_points)
36
        zl = fitlinear(V,y);
37
        prediction = V*zl
Fredrik Bagge Carlson's avatar
Fredrik Bagge Carlson committed
38
39
40
41
42
43
        error = prediction-y
        return error
    end

    # Get initial centers ================================
    Znl::RbfNonlinearParameters
44
    state,n_state, TT = inputtransform(state, inputpca)
Fredrik Bagge Carlson's avatar
Fredrik Bagge Carlson committed
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

    if lowercase(initialcenters) == "equidistant"
        initialcenters = :equidistant
        n_centers = nc^n_state
    else
        initialcenters = :kmeans
        n_centers = nc
    end

    Ψ = Array(Float64,(n_points,n_centers+1))
    Ψ[:,end] = 1.0
    V = outputnet ? V = Array(Float64,(n_points, n_state* (n_centers+1)* (na)+1)) : V = Array(Float64,(n_points, (na)*(n_centers+1)+1))
    V[:,end] = 1.0
    if initialcenters == :equidistant
        Znl = getcentersEq(state,nc); debug("gotcentersEq")
    else
61
        Znl = getcentersKmeans(state, nc, predictionerror, n_state); debug("gotcentersKmeans")
Fredrik Bagge Carlson's avatar
Fredrik Bagge Carlson committed
62
    end
63
    getΨ(Ψ, Znl, state, n_points, n_state, normalized); debug("Got Ψ")
Fredrik Bagge Carlson's avatar
Fredrik Bagge Carlson committed
64
    @ddshow sum(!isfinite(Ψ))
65
    getLinearRegressor(V,Ψ,A,state,outputnet,na,n_state,n_centers,n_points); debug("Got linear regressor V")
Fredrik Bagge Carlson's avatar
Fredrik Bagge Carlson committed
66
67
    @ddshow size(V)
    @ddshow sum(!isfinite(V))
68
    Zl = fitlinear(V,y); debug("fitlinear")
Fredrik Bagge Carlson's avatar
Fredrik Bagge Carlson committed
69
70
71
72
    @ddshow sum(!isfinite(Zl))
    prediction = V*Zl
    error = y - prediction
    errors = zeros(liniters+1)
73
    Lb,Ub = getbounds(Znl, state, n_state, n_centers)
74

Fredrik Bagge Carlson's avatar
Fredrik Bagge Carlson committed
75
76
    # ============= Main loop  ================================================
    debug("Calculating initial error")
77
    errors[1] = rms(predictionerror(Znl.x))
Fredrik Bagge Carlson's avatar
Fredrik Bagge Carlson committed
78
    println("Training RBF_ARX Centers: $(Znl.n_centers), Nonlinear parameters: $(length(Znl.x)), Linear parameters: $(length(Zl))")
79
80
    function g(z)
        znl = RbfNonlinearParameters(z,n_state,n_centers)
81
        w = fitlinear(V,y)
82
        return outputnet ? jacobian_outputnet(znl,Ψ, w, V, state) : jacobian_no_outputnet(znl,Ψ, w, V, state)
83
    end
84
85
86
87
88
    function grad(z,range)
        znl = RbfNonlinearParameters(z,n_state,n_centers)
        w = fitlinear(V,y)
        return outputnet ? gradient_outputnet(znl,Ψ, V, state,A,y,w, range) : gradient_no_outputnet(znl,Ψ, V, state,A,y,w, range)
    end
89
90
    f(z) = predictionerror(z)
    X0 = deepcopy(Znl.x)
Fredrik Bagge Carlson's avatar
Fredrik Bagge Carlson committed
91
92
93
94
95
96
97
    for i = 1:liniters
        if i%2 == 1 || !cuckoosearch
            @time res = levenberg_marquardt(f, g, X0,
                                            maxIter = nonliniters,
                                            tolG = 1e-7,
                                            tolX = 1e-10,
                                            show_trace=true,
Fredrik Bagge Carlson's avatar
Fredrik Bagge Carlson committed
98
                                            timeout = timeout,
99
                                            n_state = n_state)
100
101
102
103
104
105
106
107
            #             @time res = stochastic_gradient_descent(f, grad, X0, n_points, n_state,
            #                                                     lambda = 0.001,
            #                                                     maxIter = 5,
            #                                                     tolG = 1e-7,
            #                                                     tolX = 1e-10,
            #                                                     show_trace=true,
            #                                                     timeout = 1000,
            #                                                     batch_size=50)
108
            X0 = deepcopy(res.minimum)
109
110
            DEBUG && assert(X0 == res.minimum)
            DEBUG && @show ff1 = rms(f(X0))
111
112
113
114
            if DEBUG
                _V = deepcopy(V)
                 = deepcopy(Ψ)
            end
115
116
            DEBUG && @show ff2 = rms(f(res.minimum))

117
            if DEBUG
118
                @assert ff1 == ff2
119
120
121
122
123
124
125
                @show res.minimum == X0
                @show _V == V
                @show  == Ψ
            end
            assert(X0 == res.minimum)
            #             Znl = RbfNonlinearParameters(saturatePrecision(copy(res.minimum),n_state),n_state,n_centers)
            Znl = RbfNonlinearParameters(deepcopy(res.minimum),n_state,n_centers)
Fredrik Bagge Carlson's avatar
Fredrik Bagge Carlson committed
126
127
128
129
            errors[i+1] = res.f_minimum
            # show(res.trace)
        else
            display("Using cuckoo search to escape local minimum")
130
131
            @time (bestnest,fmin) = cuckoo_search(x -> rms(f(x)),X0, Lb, Ub;
                                                  n=50,
Fredrik Bagge Carlson's avatar
Fredrik Bagge Carlson committed
132
133
                                                  pa=0.25,
                                                  Tol=1.0e-5,
134
                                                  max_iter = i < liniters-1 ? cuckooiter : 2cuckooiter,
Fredrik Bagge Carlson's avatar
Fredrik Bagge Carlson committed
135
                                                  timeout = 2timeout)
Fredrik Bagge Carlson's avatar
Fredrik Bagge Carlson committed
136
            debug("cuckoo_search done")
137
138
139
            X0 = deepcopy(bestnest)
            @ddshow rms(f(X0))
            Znl = RbfNonlinearParameters(deepcopy(bestnest),n_state,n_centers)
Fredrik Bagge Carlson's avatar
Fredrik Bagge Carlson committed
140
141
142
143
144
145
146
147
148
            errors[i+1] = fmin
        end
        if abs(errors[i+1]-errors[i]) < 1e-10
            display("No significant change in function value")
            break
        end
    end

    # Test ===============================================
149
150
    getΨ(Ψ, Znl, state, n_points, n_state, normalized)
    getLinearRegressor(V,Ψ,A,state,outputnet,na,n_state,n_centers,n_points)
151
    Zl = fitlinear(V,y); debug("fitlinear")
Fredrik Bagge Carlson's avatar
Fredrik Bagge Carlson committed
152
153
154
155
156
157
158
159
160
161
162
163
    prediction = V*Zl
    error = y - prediction
    if PYPLOT || WINSTON
        newplot(y,"k");
        plot(prediction,"b");
        plot(error,"r");title("Fitresult, RBF-ARX, n_a: $na, n_c: $(Znl.n_centers), Nonlin params: $(length(Znl.x)), Lin params: $(length(Zl)) RMSE = $(rms(error)) Fit = $(fit(y,prediction))")
        plotcenters(Znl)
        newplot(errors,"o"); title("Errors");
    end

    # Exit ===============================================
    println("tainRBF_ARX done. Centers: $(Znl.n_centers), Nonlinear parameters: $(length(Znl.x)), Linear parameters: $(length(Zl)), RMSE: $(rms(error))")
164
165
166
167
end



Fredrik Bagge Carlson's avatar
Fredrik Bagge Carlson committed
168
function trainRBF(y, state, nc; liniters=3,nonliniters=50, normalized=false, initialcenters="equidistant", inputpca=false, cuckoosearch = false, cuckooiter=100, timeout=60)
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
    n_points = length(y)
    function predictionerror(z)
        znl = RbfNonlinearParameters(z,n_state,n_centers)
        psi = getΨ(Ψ, znl, state, n_points, n_state, normalized)
        zl = fitlinear(Ψ,y);
        prediction = Ψ*zl
        error = prediction-y
        return error
    end

    # Get initial centers ================================
    Znl::RbfNonlinearParameters

    state, n_state, TT = inputtransform(state, inputpca)
    #     n_state = size(state,2)

    if lowercase(initialcenters) == "equidistant"
        initialcenters = :equidistant
        n_centers = nc^n_state
    else
        initialcenters = :kmeans
        n_centers = nc
    end
    Ψ = Array(Float64,(n_points,n_centers+1))
    Ψ[:,end] = 1.0
    if initialcenters == :equidistant
        Znl = getcentersEq(state,nc); debug("gotcentersEq")
    else
        Znl = getcentersKmeans(state, nc, predictionerror, n_state); debug("gotcentersKmeans")
    end
    #     Znl.x += 0.1*randn(size(Znl.x))
    @ddshow Znl
    getΨ(Ψ, Znl, state, n_points, n_state, normalized); debug("Got Ψ")
202
203
    #     matshow(deepcopy(Ψ));axis("tight"); colorbar()
    #     plotparams(Znl)
204
205
206
207


    @ddshow sum(!isfinite(Ψ))
    w = fitlinear(Ψ,y); debug("fitlinear")
208
    #     newplot(w,"o"); title("Linear parameters")
209
210
211
    @ddshow sum(!isfinite(Zl))
    prediction = Ψ*w
    error = y - prediction
212
    #     newplot([y prediction error]);title("inbetween")
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
    errors = zeros(liniters+1)
    Lb,Ub = getbounds(Znl, state, n_state, n_centers)

    # ============= Main loop  ================================================
    debug("Calculating initial error")
    errors[1] = rms(predictionerror(Znl.x))
    println("Training RBF_ARX Centers: $(Znl.n_centers), Nonlinear parameters: $(length(Znl.x)), Linear parameters: $(length(w))")
    function g(z)
        znl = RbfNonlinearParameters(z,n_state,n_centers)
        w = fitlinear(Ψ,y)
        return jacobian(znl,Ψ, w, state)
    end
    f(z) = predictionerror(z)
    X0 = deepcopy(Znl.x)
    for i = 1:liniters
        if i%2 == 1 || !cuckoosearch
            @time res = levenberg_marquardt(f, g, X0,
                                            maxIter = nonliniters,
                                            tolG = 1e-7,
                                            tolX = 1e-10,
                                            show_trace=true,
Fredrik Bagge Carlson's avatar
Fredrik Bagge Carlson committed
234
                                            timeout = timeout,
235
236
237
238
239
240
241
242
                                            n_state = n_state)
            X0 = deepcopy(res.minimum)
            DEBUG && assert(X0 == res.minimum)
            DEBUG && @show ff1 = rms(f(X0))
            if DEBUG
                 = deepcopy(Ψ)
            end
            DEBUG && @show ff2 = rms(f(res.minimum))
Fredrik Bagge Carlson's avatar
Fredrik Bagge Carlson committed
243

244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
            if DEBUG
                @assert ff1 == ff2
                @show res.minimum == X0
                @show  == Ψ
            end
            assert(X0 == res.minimum)
            #             Znl = RbfNonlinearParameters(saturatePrecision(copy(res.minimum),n_state),n_state,n_centers)
            Znl = RbfNonlinearParameters(deepcopy(res.minimum),n_state,n_centers)
            errors[i+1] = res.f_minimum
            # show(res.trace)
        else
            display("Using cuckoo search to escape local minimum")
            @time (bestnest,fmin) = cuckoo_search(x -> rms(f(x)),X0, Lb, Ub;
                                                  n=50,
                                                  pa=0.25,
                                                  Tol=1.0e-5,
                                                  max_iter = i < liniters-1 ? cuckooiter : 2cuckooiter,
Fredrik Bagge Carlson's avatar
Fredrik Bagge Carlson committed
261
                                                  timeout = 2timeout)
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
            debug("cuckoo_search done")
            X0 = deepcopy(bestnest)
            @ddshow rms(f(X0))
            Znl = RbfNonlinearParameters(deepcopy(bestnest),n_state,n_centers)
            errors[i+1] = fmin
        end
        if abs(errors[i+1]-errors[i]) < 1e-10
            display("No significant change in function value")
            break
        end
    end

    # Test ===============================================
    getΨ(Ψ, Znl, state, n_points, n_state, normalized)
    w = fitlinear(Ψ,y); debug("fitlinear")
    prediction = Ψ*w
    error = y - prediction
    if PYPLOT || WINSTON
        newplot(y,"k");
        plot(prediction,"b");
        plot(error,"r");title("Fitresult, RBF, n_a: $na, n_c: $(Znl.n_centers), Nonlin params: $(length(Znl.x)), Lin params: $(length(w)) RMSE = $(rms(error)) Fit = $(fit(y,prediction))")
        plotcenters(Znl)
        newplot(errors,"o"); title("Errors");
    end
Fredrik Bagge Carlson's avatar
Fredrik Bagge Carlson committed
286

287
288
289
290
    # Exit ===============================================
    println("tainRBF done. Centers: $(Znl.n_centers), Nonlinear parameters: $(length(Znl.x)), Linear parameters: $(length(w)), RMSE: $(rms(error))")
    return prediction
end
Fredrik Bagge Carlson's avatar
Fredrik Bagge Carlson committed
291

292
293
294
295
type InputTransform
    mean
    variance
    C
Fredrik Bagge Carlson's avatar
Fredrik Bagge Carlson committed
296
297
end

298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
function inputtransform(state, inputpca)
    n_points = size(state,1)
    m = mean(state,1)
    v = std(state,1)
    state-= repmat(m,n_points,1)
    state./= repmat(v,n_points,1)
    if isa(inputpca, Int)
        if inputpca > size(state,2)
            warn("inputpca must be <= n_state")
            inputpca = size(state,2)
        end
        C,score,latent,W0 = PCA(state,true)
        state = score[:,1:inputpca]
    else
        C = 1
    end
    n_state = size(state,2)
    #     newplot(state); title("State after transformation")
    return state, n_state, InputTransform(m,v,C)
Fredrik Bagge Carlson's avatar
Fredrik Bagge Carlson committed
317

318
end
Fredrik Bagge Carlson's avatar
Fredrik Bagge Carlson committed
319
320
321
322
323
324
325
326
327
328
329
330
331
332

function getcentersEq(state::VecOrMat, nc::Integer)
    n_points = size(state,1)
    n_state = typeof(state) <: Matrix ? size(state,2) : 1
    state_extrema = [minimum(state,1)' maximum(state,1)']
    statewidths = state_extrema[:,2] - state_extrema[:,1]
    Δc = statewidths/nc
    Z = zeros(nc, 2*n_state) # 2*n_state to fit center coordinates and scaling parameters
    # Fill initial centers
    for i = 1:n_state
        Z[:,i] = collect((state_extrema[i,1]+ Δc[i]/2):Δc[i]:state_extrema[i,2])
    end
    # add bandwidth parameters γ, give all centers the same bandwidth with Δc as a (hopefully) good initial guess
    #     display(Z)
Fredrik Bagge Carlson's avatar
Fredrik Bagge Carlson committed
333
    Z[:,n_state+1:end] = 1*repmat(4./(Δc.^2)',nc,1) # Spread the initial guess to all centers
Fredrik Bagge Carlson's avatar
Fredrik Bagge Carlson committed
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
    assert(all(Z[:,n_state+1:end].> 0))
    debug("Z done")
    n_centers::Int64 = nc^n_state # new number of centers wich considers gridding of 1D centers
    ZZ1 = zeros(n_state, n_centers)
    ZZ2 = zeros(n_state, n_centers)
    # Here comes the magic. Spread each one dimensional center onto a grid in n_state dimensions
    v = n_centers
    h = 1
    ii = 1
    for i = 1:n_state # For each iteration, v decreases and h increases by a factor of nc. If v and h are used in repmat(⋅,v,h) which is then vecotrized, the desired grid will be created. It's a bit tricky, but makes sense after a lot of thinking
        v = convert(Int64, v / nc)
        ZZ1[i,:] = vec(repmat(Z[:,i]',v,h))'
        ZZ2[i,:] = vec(repmat(Z[:,i+n_state]',v,h))'
        h *= nc
        ii += 1
    end
    debug("ZZ done")
    RbfNonlinearParameters(vec([ZZ1; ZZ2]), n_state, n_centers)
    #error("Bias parameter!")
end

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
function getcentersKmeans(state, nc::Int, f::Function, n_state::Int)
    iters = 21
    errorvec = zeros(iters)
    params = Array(Float64,(nc*2*n_state,iters))
    methods = [:rand;:kmpp]
    for iter = 1:iters
        clusterresult = kmeans(state', nc; maxiter=200, display=:none, init=iter<iters ? methods[iter%2+1] : :kmcen)
        for i = 1:nc
            si = 1+(i-1)n_state*2
            params[si:si+n_state-1,iter] = clusterresult.centers[:,i]
            C = cov(state[clusterresult.assignments .== i,:])
            C = cond(C) > 1e4 ? eye(C) : C
            params[si+n_state:si+2n_state-1,iter] = diag(inv(C))
            any(diag(inv(C)) .< 0) && show(C)
        end
        errorvec[iter] = rms(f(params[:,iter]))
    end
    println("Std in errors among initial centers: ", round(std(errorvec),6))
    ind = indmin(errorvec)
    return RbfNonlinearParameters(params[:,ind],n_state, nc)
end

function plotcenters(Z)
    X = zeros(Z.n_centers,2)
    for (i,Zi) in enumerate(Z)
        X[i,:] = Zi[1:2]'
    end
    newplot(X[:,1],X[:,2],"o"); title("Centers")
end

Fredrik Bagge Carlson's avatar
Fredrik Bagge Carlson committed
385
386
387



388
389
function getΨ(Ψ, Znl, state, n_points, n_state, normalized::Bool, range = 1:1)
    Ψ = normalized ? getΨnormalized(Ψ, Znl, state, n_points, n_state) :  getΨnonnormalized(Ψ, Znl, state, n_points, n_state, range)
390
391
392
393
394
395
396
    if DEBUG && sum(!isfinite(Ψ)) > 0
        @show sum(!isfinite(Ψ))
    end
    return Ψ
end

function getΨnormalized(Ψ, Znl, state, n_points, n_state)
397
    RBF(x, Znl::VecOrMat,n_state::Integer) = exp(-(sum((x-Znl[1:n_state]).^2.*Znl[n_state+1:end])))
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
    rowsum = ones(n_points)
    for (j,Zin) in enumerate(Znl)
        Zi = deepcopy(Zin)
        #         for i = n_state+1:2n_state
        #             Zi[i] = Zi[i] <= 0 ? 0.01 : Zi[i] # Reset to 1 if precision became negative
        #         end
        for i = 1:n_points
            statei = squeeze(state[i,:]',2)
            a = RBF(statei, Zi, n_state)
            Ψ[i,j] = a
            rowsum[i] += a
        end
    end
    for i = 1:n_points
        if rowsum[i] <= 1e-10
            continue
        end
        @devec Ψ[i,:] ./= rowsum[i]
    end
    return Ψ
end

420
421
function getΨnonnormalized(Ψ, Znl, state, n_points, n_state, range = 1:1)
    range = (range == 1:1) ? (1:size(state,1)) : range
422
423
    RBF(x, Z,n_state) = exp(-(sum(((x-Z[1:n_state]).^2).*Z[n_state+1:end])))
    for (j,Zi) in enumerate(Znl)
424
        for i = range
425
            statei = state[i,:]'
426
427
428
429
430
431
432
433
434
435
            #                     statei = slice(state,i,:)
            Ψ[i,j] = RBF(statei, Zi, n_state)
            if DEBUG && !isfinite(Ψ[i,j])
                @show i,j,statei, Zi, n_state, Ψ[i,j]
                @show (statei-Zi[1:n_state]).^2
                @show Zi[n_state+1:end]
                error("Stopping")
            end
        end
    end
436

437
438
439
    return Ψ
end

440
441
function getLinearRegressor(V,Ψ,A,state,outputnet,na,n_state,n_centers,n_points, range = 1:1)
    outputnet ? getLinearRegressor_outputnet(V,Ψ,A,state,na,n_state,n_centers,n_points, range) : getLinearRegressor_no_outputnet(V,Ψ,A,state,na,n_state,n_centers,n_points, range)
442
443
end

444
445
function getLinearRegressor_no_outputnet(V,Ψ,A,state,na,n_state,n_centers,n_points, range = 1:1)
    range = range == 1:1 ? 1:size(state,1) : range
446
447
448
    ii = 1
    for i = 1:na
        for k = 1:n_centers+1
449
            for l = range
450
                V[l,ii] = Ψ[l,k]*A[l,i]
451
            end
452
            ii = ii+1
453
        end
454
455
456
457
458
459
460
    end
    if DEBUG && sum(!isfinite(V)) > 0
        @show sum(!isfinite(V))
    end
    return V
end

461
462
function getLinearRegressor_outputnet(V,Ψ,A,state,na,n_state,n_centers,n_points, range = 1:1)
    range = (range == 1:1) ? (1:size(state,1)) : range
463
464
465
466
    ii = 1
    for i = 1:na
        for k = 1:n_centers+1
            for j = 1:n_state
467
                for l = range
468
                    V[l,ii] = Ψ[l,k]*A[l,i]*state[l,j]
469
470
471
472
473
474
475
476
477
478
                end
                ii = ii+1
            end
        end
    end
    if DEBUG && sum(!isfinite(V)) > 0
        @show sum(!isfinite(V))
    end
    return V
end
479
480


481

482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497

function getbounds(Znl, state, n_state, n_centers)
    Lb = zeros(Znl.x)
    Ub = zeros(Znl.x)
    mas = maximum(state,1)'
    mis = minimum(state,1)'
    for i = 1:2n_state:n_centers*2n_state
        Lb[i:i+n_state-1] = mis
        Ub[i:i+n_state-1] = mas
        Lb[i+n_state:i+2n_state-1] = 0.000001
        Ub[i+n_state:i+2n_state-1] = 10*Znl.x[n_state+1:2n_state]
    end
    return Lb,Ub
end


498
499


500
501

function jacobian_outputnet(Znl, Ψ, w, V, state)
502
503
504
    n_points = size(Ψ,1)
    n_state = Znl.n_state
    n_centers = Znl.n_centers
505
506
507
508
509
510

    n_batch = 100
    points = randperm(n_points)[1:n_batch]


    J = Array(Float64,(n_batch,length(Znl.x)))
511
512
513
514
515
    ii = 1
    for (k,Zi) in enumerate(Znl)
        μ = Zi[1:n_state] # slice?
        γ = Zi[n_state+1:end]
        i1 = ii-1
516
        for (l,li) = enumerate(points)
517
518
519
520
521
522
523
524
525
            Ψw = 1.0
            for i = 1:na
                for j = 1:n_state
                    ind = j + n_state*(k-1) + n_state*(n_centers+1)*(i-1)
                    Ψw  += V[l,ind]*w[ind]
                end
            end
            for p = 1:n_state
                x_μ = state[l,p]-μ[p]
526
527
                J[li,i1+p] = 2*Ψw*x_μ*γ[p]
                J[li,i1+n_state+p] = (-Ψw)*x_μ^2
528
529
530
531
532
533
534
            end
        end
        ii += 2n_state
    end
    return J
end

535
function jacobian_no_outputnet(Znl, Ψ, w,V, state)
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
    n_points = size(Ψ,1)
    n_state = Znl.n_state
    n_centers = Znl.n_centers
    J = Array(Float64,(n_points,length(Znl.x)))
    ii = 1
    for (k,Zi) in enumerate(Znl)
        μ = Zi[1:n_state] # slice?
        γ = Zi[n_state+1:end]
        i1 = ii-1
        for l = 1:n_points
            Ψw = 1.0
            for i = 1:na
                ind = k + (n_centers+1)*(i-1)
                Ψw  += V[l,ind]*w[ind]
            end
            for p = 1:n_state
                x_μ = state[l,p]-μ[p]
                J[l,i1+p] = 2*Ψw*x_μ*γ[p]
                J[l,i1+n_state+p] = (-Ψw)*x_μ^2
            end
        end
        ii += 2n_state
    end
    return J
end

562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631

function gradient_outputnet(Znl, Ψ, V, state, A,y,w, range)
    n_points = size(Ψ,1)
    n_state = Znl.n_state
    n_centers = Znl.n_centers
    na = size(A,2)

    #     znl = RbfNonlinearParameters(z,n_state,n_centers)
    #     psi = getΨ(Ψ, Znl, state, n_points, n_state, false, range)
    #     getLinearRegressor(V,psi,A,state,true,na,n_state,n_centers,n_points, range)
    #     w = fitlinear(V,y)

    J = zeros(length(Znl.x))
    ii = 1
    for (k,Zi) in enumerate(Znl)
        μ = Zi[1:n_state] # slice?
        γ = Zi[n_state+1:end]
        i1 = ii-1
        for l = range
            Ψw = 1.0
            for i = 1:na
                for j = 1:n_state
                    ind = j + n_state*(k-1) + n_state*(n_centers+1)*(i-1)
                    Ψw  += V[l,ind]*w[ind]
                end
            end
            for p = 1:n_state
                x_μ = state[l,p]-μ[p]
                J[i1+p] += 2*Ψw*x_μ*γ[p]
                J[i1+n_state+p] += (-Ψw)*x_μ^2
            end
        end
        ii += 2n_state
    end
    J /= length(range)
    return J
end

function gradient_no_outputnet(Znl, Ψ, V, state, A,y,w, range)
    n_points = size(Ψ,1)
    n_state = Znl.n_state
    n_centers = Znl.n_centers
    na = size(A,2)
    #     psi = getΨ(Ψ, Znl, state, n_points, n_state, false, range)
    #     getLinearRegressor(V,psi,A,state,true,na,n_state,n_centers,n_points, range)
    #     w = fitlinear(V,y)
    J = zeros(length(Znl.x))
    ii = 1
    for (k,Zi) in enumerate(Znl)
        μ = Zi[1:n_state] # slice?
        γ = Zi[n_state+1:end]
        i1 = ii-1
        for l = range
            Ψw = 1.0
            for i = 1:na
                ind = k + (n_centers+1)*(i-1)
                Ψw  += V[l,ind]*w[ind]
            end
            for p = 1:n_state
                x_μ = state[l,p]-μ[p]
                J[i1+p] += 2*Ψw*x_μ*γ[p]
                J[i1+n_state+p] += (-Ψw)*x_μ^2
            end
        end
        ii += 2n_state
    end
    J /= length(range)
    return J
end

632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
function jacobian(Znl, Ψ, w, state)
    n_points = size(Ψ,1)
    n_state = Znl.n_state
    n_centers = Znl.n_centers
    J = Array(Float64,(n_points,length(Znl.x)))
    ii = 1
    for (k,Zi) in enumerate(Znl)
        μ = Zi[1:n_state] # slice?
        γ = Zi[n_state+1:end]
        i1 = ii-1
        for l = 1:n_points
            Ψw = Ψ[l,k]*w[k]
            for p = 1:n_state
                x_μ = state[l,p]-μ[p]
                J[l,i1+p] = 2*Ψw*x_μ*γ[p]
                J[l,i1+n_state+p] = (-Ψw)*x_μ^2
            end
        end
        ii += 2n_state
    end
    return J
end

655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
function saturatePrecision(x,n_state)
    for i = 1:2n_state:length(x)
        range = i+n_state:i+2n_state-1
        x[range] = abs(x[range])
    end
    return x
end

function fitlinear(V,y)
    try
        DEBUG && assert(isa(V,Matrix))
        DEBUG && assert(isa(y,Vector))
        DEBUG && assert(!any(!isfinite(V)))
        DEBUG && assert(!any(!isfinite(y)))
        return V\y
    catch ex
        display(ex)
        error("Linear fitting failed")
    end
end
675
676
677
678
679
680
681
682
683

function Base.show(p::RbfNonlinearParameters)
    println(round(reshape(p.x,2p.n_state,p.n_centers),4))
end

function plotparams(p::RbfNonlinearParameters)
    newplot(reshape(p.x,2p.n_state,p.n_centers)',"o")
    title("Nonlinear parameters")
end