-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmodelfitting.jl
More file actions
executable file
·525 lines (488 loc) · 22 KB
/
modelfitting.jl
File metadata and controls
executable file
·525 lines (488 loc) · 22 KB
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
# functions to fit models to data
using NLopt, DataFrames, Random, Printf
const tnd_sd_scale = 0.1 # SD(tnd) = tnd_sd_scale * <tnd> (as in Palmer, Huk & Shadlen, 2005)
#const tnd_sd_scale = 0 # SD(tnd) = tnd_sd_scale * <tnd>
const simsrand = 0
###############################################################################
# objective functions for fitting model parameters
# Bernoulli likelihood
plogq(p, q) = 0 .<= p .< 1e-300 ? -500.0p : p .* log.(max.(pmin, q)) # ensure 0 * log 0 = 0
#bernllh(m_pr, d_pr, d_n) = d_n .* (plogq(d_pr, m_pr) + plogq(1 - d_pr, 1 - m_pr))
bernllh(m_pr, d_pr, d_n) = d_n .* (d_pr .* log.(max.(pmin, m_pr)) .+ (1 .- d_pr) .* log.(max.(pmin, 1-m_pr)))
# Gaussian likelihood for data drawn from N(m_tμ, m_tσ^2)
gaussfullllh(m_tμ, m_tσ, d_tμ, d_tσ, d_n) = d_n .* (-0.5logtwoπ .- log.(m_tσ) .-
(abs2.(d_tσ) .+ abs2.(d_tμ .- m_tμ)) ./ (2abs2.(m_tσ)))
# Gaussian likelihood for data mean drawn d_n times from N(m_tμ, d_tsem^2)
gausssemllh(m_tμ, d_tμ, d_tsem, d_n) = d_n .* (-0.5logtwoπ .- log.(d_tsem) .-
abs2.(d_tμ .- m_tμ)./(2abs2.(d_tsem)))
# the objective function
abstract type FittingObjective end
###############################################################################
# objective functions that don't model sequential choices
# - fit choices by Bernoulli likelihood
# - fit RTs with Gaussian likelihood for correct / incorrect choices combined
# - only fit a subset or both conditions (identified at initialization)
# - the RT variance is augmented by (tnd_sd_scale * tnd)^2
struct PsychChron1ObjFn <: FittingObjective
m::ModelBase
evidence::Matrix{Float64}
ids::Vector{Int}
uniqueids::Vector{Int}
burnin::Int
d_psych::Vector{DataFrame}
conditions::Vector{Int}
PsychChron1ObjFn(m, evidence, ids, burnin, d_ident, d_categ, datasets,
conds::AbstractVector{Symbol}) =
new(m, evidence, ids, sort(unique(ids)), burnin,
DataFrame[by(df, :stimid, df -> _tcstats(df, datasets))
for df in [d_ident, d_categ]],
map(x -> Dict(:ident => 1, :categ => 2)[x], conds))
# defaults to fitting both conditions simultaneously
PsychChron1ObjFn(m, evidence, ids, burnin, d_ident, d_categ, datasets) =
PsychChron1ObjFn(m, evidence, ids, burnin, d_ident, d_categ, datasets,
[:ident, :categ])
end
# function returns avg. llh across modeled trials
function llh(o::PsychChron1ObjFn, ϕ::Vector)
# simulate model and gather summary stats
Random.seed!(simsrand)
ms = simmodel(o.m, ϕ, o.evidence, o.ids)
tndvar = abs2(tnd_sd_scale * gettnd(o.m, ϕ))
# assemble likelihood
llh, n = 0.0, 0.0
for i in o.conditions
d = o.d_psych[i]
m = by(ms[i][(o.burnin+1):end, :], :stimid, _tcstats)
for id in o.uniqueids
m_prμ, m_tμ = Vector{Float64}(m[m[:stimid] .== id, [:prμ, :tμ]][1,:])
d_n, d_prμ, d_tμ, d_tsem =
Vector{Float64}(d[d[:stimid] .== id, [:n, :prμ, :tμ, :tsem]][1,:])
llh += bernllh(m_prμ, d_prμ, d_n) +
# we use d_n = 1, as we are already using the SEM
gausssemllh(m_tμ, d_tμ, √(abs2(d_tsem) + tndvar), 1)
n += d_n
end
end
return llh / n
end
# alternatives: fit single condition
PsychChron1IdentObjFn(m, evidence, ids, burnin, d_ident, d_categ, datasets) =
PsychChron1ObjFn(m, evidence, ids, burnin, d_ident, d_categ, datasets, [:ident])
PsychChron1CategObjFn(m, evidence, ids, burnin, d_ident, d_categ, datasets) =
PsychChron1ObjFn(m, evidence, ids, burnin, d_ident, d_categ, datasets, [:categ])
# - fit choices by Bernoulli likelihood
# - fit RTs for Gaussian likelihood for correct / incorrect choices separately
# - the RT variance is augmented by (tnd_sd_scale * tnd)^2
struct PsychChron2ObjFn <: FittingObjective
m::ModelBase
evidence::Matrix{Float64}
ids::Vector{Int}
uniqueids::Vector{Int}
burnin::Int
d_psych::Vector{DataFrame}
PsychChron2ObjFn(m, evidence, ids, burnin, d_ident, d_categ, datasets) =
new(m, evidence, ids, sort(unique(ids)), burnin,
DataFrame[by(df, :stimid, df -> _tcstats(df, datasets))
for df in [d_ident, d_categ]])
end
# function returns avg. llh across modeled trials
function llh(o::PsychChron2ObjFn, ϕ::Vector)
# simulate model
Random.seed!(simsrand)
ms = simmodel(o.m, ϕ, o.evidence, o.ids)
tndvar = abs2(tnd_sd_scale * gettnd(o.m, ϕ))
# assemble likelihood
llh, n = 0.0, 0.0
for i in [1, 2]
d = o.d_psych[i]
m = by(ms[i][(o.burnin+1):end, :], :stimid, _tcstats)
for id in o.uniqueids
m_prμ, m_tcorrμ, m_tincorrμ = Vector{Float64}(
m[m[:stimid] .== id, [:prμ, :tcorrμ, :tincorrμ]][1,:])
d_n, d_ncorr, d_prμ, d_tcorrμ, d_tincorrμ, d_tcorrsem, d_tincorrsem =
Vector{Float64}(
d[d[:stimid] .== id,
[:n, :ncorr, :prμ, :tcorrμ, :tincorrμ, :tcorrsem, :tincorrsem]][1,:])
llh += bernllh(m_prμ, d_prμ, d_n) +
# we use d_n = 1, as we are already using the SEM
gausssemllh(m_tcorrμ, d_tcorrμ, √(abs2(d_tcorrsem) + tndvar), 1) +
gausssemllh(m_tincorrμ, d_tincorrμ, √(abs2(d_tincorrsem) + tndvar), 1)
n += d_n
end
end
return llh / n
end
# - fit choices by Bernoulli likelihood
# - fit RTs with Gaussian SD likelihood for correct / incorrect choices combined
# - only fit a subset or both conditions (identified at initialization)
# (same as PsychChron2ObjFn, only that RTs are modelled by SD, not SEM)
struct PsychChron3ObjFn <: FittingObjective
m::ModelBase
evidence::Matrix{Float64}
ids::Vector{Int}
uniqueids::Vector{Int}
burnin::Int
d_psych::Vector{DataFrame}
conditions::Vector{Int}
PsychChron3ObjFn(m, evidence, ids, burnin, d_ident, d_categ, datasets,
conds::AbstractVector{Symbol}) =
new(m, evidence, ids, sort(unique(ids)), burnin,
DataFrame[by(df, :stimid, df -> _tcstats(df, datasets))
for df in [d_ident, d_categ]],
map(x -> Dict(:ident => 1, :categ => 2)[x], conds))
# defaults to fitting both conditions simultaneously
PsychChron3ObjFn(m, evidence, ids, burnin, d_ident, d_categ, datasets) =
PsychChron3ObjFn(m, evidence, ids, burnin, d_ident, d_categ, datasets,
[:ident, :categ])
end
# function returns avg. llh across modeled trials
function llh(o::PsychChron3ObjFn, ϕ::Vector)
# simulate model and gather summary stats
Random.seed!(simsrand)
ms = simmodel(o.m, ϕ, o.evidence, o.ids)
# assemble likelihood
llh, n = 0.0, 0.0
for i in o.conditions
d = o.d_psych[i]
m = by(ms[i][(o.burnin+1):end, :], :stimid, _tcstats)
for id in o.uniqueids
m_prμ, m_tμ, m_tσ =
Vector{Float64}(m[m[:stimid] .== id, [:prμ, :tμ, :tσ]][1,:])
d_n, d_prμ, d_tμ, d_tσ =
Vector{Float64}(d[d[:stimid] .== id, [:n, :prμ, :tμ, :tσ]][1,:])
llh += bernllh(m_prμ, d_prμ, d_n) +
gaussfullllh(m_tμ, m_tσ, d_tμ, d_tσ, d_n)
n += d_n
end
end
return llh / n
end
# alternatives: fit single condition
PsychChron3IdentObjFn(m, evidence, ids, burnin, d_ident, d_categ, datasets) =
PsychChron3ObjFn(m, evidence, ids, burnin, d_ident, d_categ, datasets, [:ident])
PsychChron3CategObjFn(m, evidence, ids, burnin, d_ident, d_categ, datasets) =
PsychChron3ObjFn(m, evidence, ids, burnin, d_ident, d_categ, datasets, [:categ])
###############################################################################
# objective functions that model sequential choices
# - after correct choices, fit choices by Bernoulli likelihood, condition on
# previous stimulus id
# - after incorrect choices, fit choices by Bernoulli likelihood, independent
# of pervious stimulus
# - fit RTs with Gaussian likelihood for correct / incorrect choices combined
# - the RT variance is augmented by (tnd_sd_scale * tnd)^2
struct PsychChronSeq1ObjFn <: FittingObjective
m::ModelBase
evidence::Matrix{Float64}
ids::Vector{Int}
uniqueids::Vector{Int}
burnin::Int
d_nonseq::Vector{DataFrame}
d_seq_corr::Vector{DataFrame}
d_seq_incorr::Vector{DataFrame}
PsychChronSeq1ObjFn(m, evidence, ids, burnin, d_ident, d_categ, datasets) =
new(m, evidence, ids, sort(unique(ids)), burnin,
DataFrame[by(df, :stimid, df -> _tcstats(df, datasets))
for df in [d_ident, d_categ]],
DataFrame[by(df[df[:prevrew] .== true, :], [:stimid, :previd],
df -> _tcstats(df, datasets)) for df in [d_ident, d_categ]],
DataFrame[by(df[df[:prevrew] .== false, :], :stimid,
df -> _tcstats(df, datasets)) for df in [d_ident, d_categ]])
end
function llh(o::PsychChronSeq1ObjFn, ϕ::Vector)
Random.seed!(simsrand)
ms = simmodel(o.m, ϕ, o.evidence, o.ids)
tndvar = abs2(tnd_sd_scale * gettnd(o.m, ϕ))
# assemble likelihood
llh, n = 0.0, 0.0
for i in [1, 2]
mi = ms[i][(o.burnin+1):end, :]
m = by(mi, :stimid, _tcstats)
mcorr = by(mi[mi[:prevrew] .== true, :], [:stimid, :previd], _tcstats)
if any(mi[:prevrew] .== false)
mincorr = by(mi[mi[:prevrew] .== false, :], :stimid, _tcstats)
else
# create dataframe that violates any(mincorr[:stimid] .== id) below
mincorr = DataFrame(stimid = Int[0])
end
d = o.d_nonseq[i]
dcorr = o.d_seq_corr[i]
dincorr = o.d_seq_incorr[i]
# in all cases, iterate over current stimulus id
for id in o.uniqueids
# reaction times
m_tμ = m[m[:stimid] .== id, :tμ][1]
d_n, d_tμ, d_tsem =
Vector{Float64}(d[d[:stimid] .== id, [:n, :tμ, :tsem]][1,:])
# we use d_n = 1, as we are already using the SEM
llh += gausssemllh(m_tμ, d_tμ, √(abs2(d_tsem) + tndvar), 1)
# choices after incorrect trials
if any(mincorr[:stimid] .== id)
m_prμ = mincorr[mincorr[:stimid] .== id, :prμ][1]
else
m_prμ = id > 4 ? 1.0 : 0.0 # can happen for too high 'gain'
end
d_nincorr, d_prμ =
Vector{Float64}(dincorr[dincorr[:stimid] .== id, [:n, :prμ]][1,:])
llh += bernllh(m_prμ, d_prμ, d_nincorr)
# choices after correct trials
d_ncorr = 0.0
for previd in o.uniqueids
m_prμ = mcorr[(mcorr[:previd] .== previd) .&
(mcorr[:stimid] .== id), :prμ][1]
d_ni, d_prμ = Vector{Float64}(
dcorr[(dcorr[:previd] .== previd) .&
(dcorr[:stimid] .== id), [:n, :prμ]][1,:])
llh += bernllh(m_prμ, d_prμ, d_ni)
d_ncorr += d_ni
end
# check if n is consistent
@assert d_n == d_ncorr + d_nincorr
n += d_n
end
end
return llh / n
end
# - after correct choices, fit choices by Bernoulli likelihood and RTs with
# Gaussian likelhood (indep. of corr/incorr), conditioned on previous stimid
# - after incorrect choices, do the same without conditioning on prev. stimid
# - the RT variance is augmented by (tnd_sd_scale * tnd)^2
#
# This model provides larger llh's than the above models, due to the scaling of
# the SEM with n. For this model, the SEM's will be unproportionally larger
# (based on less data) than for the above models, causing the llh's to be larger.
# Overall, this causes a stronger focus on p(choice) than RTs.
struct PsychChronSeq2ObjFn <: FittingObjective
m::ModelBase
evidence::Matrix{Float64}
ids::Vector{Int}
uniqueids::Vector{Int}
burnin::Int
d_seq_corr::Vector{DataFrame}
d_seq_incorr::Vector{DataFrame}
PsychChronSeq2ObjFn(m, evidence, ids, burnin, d_ident, d_categ, datasets) =
new(m, evidence, ids, sort(unique(ids)), burnin,
DataFrame[by(df[df[:prevrew] .== true, :], [:stimid, :previd],
df -> _tcstats(df, datasets)) for df in [d_ident, d_categ]],
DataFrame[by(df[df[:prevrew] .== false, :], :stimid,
df -> _tcstats(df, datasets)) for df in [d_ident, d_categ]])
end
function llh(o::PsychChronSeq2ObjFn, ϕ::Vector)
Random.seed!(simsrand)
ms = simmodel(o.m, ϕ, o.evidence, o.ids)
tndvar = abs2(tnd_sd_scale * gettnd(o.m, ϕ))
# assemble likelihood
llh, n = 0.0, 0.0
for i in [1, 2]
mi = ms[i][(o.burnin+1):end, :]
mcorr = by(mi[mi[:prevrew] .== true, :], [:stimid, :previd], _tcstats)
if any(mi[:prevrew] .== false)
mincorr = by(mi[mi[:prevrew] .== false, :], :stimid, _tcstats)
else
# create dataframe that violates any(mincorr[:stimid] .== id) below
mincorr = DataFrame(stimid = Int[0], tμ = Float64[mean(mcorr[:tμ])])
end
# llh for trials after correct choices
dcorr = o.d_seq_corr[i]
for previd in o.uniqueids
for id in o.uniqueids
m_prμ, m_tμ = Vector{Float64}(
mcorr[(mcorr[:previd] .== previd) .&
(mcorr[:stimid] .== id), [:prμ, :tμ]][1,:])
d_n, d_prμ, d_tμ, d_tsem = Vector{Float64}(
dcorr[(dcorr[:previd] .== previd) .&
(dcorr[:stimid] .== id), [:n, :prμ, :tμ, :tsem]][1,:])
llh += bernllh(m_prμ, d_prμ, d_n) +
# we use d_n = 1, as we are already using the SEM
gausssemllh(m_tμ, d_tμ, √(abs2(d_tsem) + tndvar), 1)
n += d_n
end
end
# llh for trials after incorrect choices
dincorr = o.d_seq_incorr[i]
for id in o.uniqueids
if any(mincorr[:stimid] .== id)
m_prμ, m_tμ = Vector{Float64}(
mincorr[mincorr[:stimid] .== id, [:prμ, :tμ]][1,:])
else
# for large p(correct), there might have been too few previous
# incorrect choices - in this case, take the average tμ, and the
# correct pr
m_prμ = id > 4 ? 1.0 : 0.0
m_tμ = mean(mincorr[:tμ])
end
d_n, d_prμ, d_tμ, d_tsem = Vector{Float64}(
dincorr[dincorr[:stimid] .== id, [:n, :prμ, :tμ, :tsem]][1,:])
llh += bernllh(m_prμ, d_prμ, d_n) +
# we use d_n = 1, as we are already using the SEM
gausssemllh(m_tμ, d_tμ, √(abs2(d_tsem) + tndvar), 1)
n += d_n
end
end
return llh / n
end
# - after correct choices, fit choices by Bernoulli likelihood, condition on
# previous stimulus id
# - after incorrect choices, fit choices by Bernoulli likelihood, independent
# of pervious stimulus
# - fit RTs with Gaussian likelihood for correct / incorrect choices combined
# (same as PsychChronSeq1ObjFn, only that RTs are modelled by SD, not SEM)
struct PsychChronSeq3ObjFn <: FittingObjective
m::ModelBase
evidence::Matrix{Float64}
ids::Vector{Int}
uniqueids::Vector{Int}
burnin::Int
d_nonseq::Vector{DataFrame}
d_seq_corr::Vector{DataFrame}
d_seq_incorr::Vector{DataFrame}
PsychChronSeq3ObjFn(m, evidence, ids, burnin, d_ident, d_categ, datasets) =
new(m, evidence, ids, sort(unique(ids)), burnin,
DataFrame[by(df, :stimid, df -> _tcstats(df, datasets))
for df in [d_ident, d_categ]],
DataFrame[by(df[df[:prevrew] .== true, :], [:stimid, :previd],
df -> _tcstats(df, datasets)) for df in [d_ident, d_categ]],
DataFrame[by(df[df[:prevrew] .== false, :], :stimid,
df -> _tcstats(df, datasets)) for df in [d_ident, d_categ]])
end
function llh(o::PsychChronSeq3ObjFn, ϕ::Vector)
Random.seed!(simsrand)
ms = simmodel(o.m, ϕ, o.evidence, o.ids)
# assemble likelihood
llh, n = 0.0, 0.0
for i in [1, 2]
mi = ms[i][(o.burnin+1):end, :]
m = by(mi, :stimid, _tcstats)
mcorr = by(mi[mi[:prevrew] .== true, :], [:stimid, :previd], _tcstats)
if any(mi[:prevrew] .== false)
mincorr = by(mi[mi[:prevrew] .== false, :], :stimid, _tcstats)
else
# create dataframe that violates any(mincorr[:stimid] .== id) below
mincorr = DataFrame(stimid = Int[0])
end
d = o.d_nonseq[i]
dcorr = o.d_seq_corr[i]
dincorr = o.d_seq_incorr[i]
# in all cases, iterate over current stimulus id
for id in o.uniqueids
# reaction times
m_tμ, m_tσ = Vector{Float64}(m[m[:stimid] .== id, [:tμ, :tσ]][1,:])
d_n, d_tμ, d_tσ = Vector{Float64}(d[d[:stimid] .== id, [:n, :tμ, :tσ]][1,:])
llh += gaussfullllh(m_tμ, m_tσ, d_tμ, d_tσ, d_n)
# choices after incorrect trials
if any(mincorr[:stimid] .== id)
m_prμ = mincorr[mincorr[:stimid] .== id, :prμ][1]
else
m_prμ = id > 4 ? 1.0 : 0.0 # can happen for too high 'gain'
end
d_nincorr, d_prμ =
Vector{Float64}(dincorr[dincorr[:stimid] .== id, [:n, :prμ]][1,:])
llh += bernllh(m_prμ, d_prμ, d_nincorr)
# choices after correct trials
d_ncorr = 0.0
for previd in o.uniqueids
m_prμ = mcorr[(mcorr[:previd] .== previd) .&
(mcorr[:stimid] .== id), :prμ][1]
d_ni, d_prμ = Vector{Float64}(
dcorr[(dcorr[:previd] .== previd) .&
(dcorr[:stimid] .== id), [:n, :prμ]][1,:])
llh += bernllh(m_prμ, d_prμ, d_ni)
d_ncorr += d_ni
end
# check if n is consistent
@assert d_n == d_ncorr + d_nincorr
n += d_n
end
end
return llh / n
end
###############################################################################
# objective functions for the interleaved dataset
# - fit choices by Bernoulli likelihood
# - fit RTs with Gaussian likelihood for correct / incorrect choices combined
# - only fit a subset or both conditions (identified at initialization)
# - the RT variance is augmented by (tnd_sd_scale * tnd)^2
struct PsychChron1ItlvdObjFn <: FittingObjective
m::ModelBase
evidence::Matrix{Float64}
ids::Vector{Int}
burnin::Int
d_psych::DataFrame
modeledids::Vector{Int}
PsychChron1ItlvdObjFn(m, evidence, ids, burnin, d_itlvd, datasets, modeledids) =
new(m, evidence, ids, burnin,
by(d_itlvd, :stimid, df -> _tcstats(df, datasets)), modeledids)
# defaults to fitting all stimulus ids simultaneously
PsychChron1ItlvdObjFn(m, evidence, ids, burnin, d_itlvd, datasets) =
PsychChron1ItlvdObjFn(m, evidence, ids, burnin, d_itlvd, datasets,
collect(1:32))
end
# function returns avg. llh across modeled trials
function llh(o::PsychChron1ItlvdObjFn, ϕ::Vector)
# simulate model and gather summary stats
Random.seed!(simsrand)
ms = simitlvdmodel(o.m, ϕ, o.evidence, o.ids)
tndvar = abs2(tnd_sd_scale * gettnd(o.m, ϕ))
# assemble likelihood
llh, n = 0.0, 0.0
d = o.d_psych
m = by(ms[(o.burnin+1):end, :], :stimid, _tcstats)
for id in o.modeledids
m_prμ, m_tμ = Vector{Float64}(m[m[:stimid] .== id, [:prμ, :tμ]][1,:])
d_n, d_prμ, d_tμ, d_tsem =
Vector{Float64}(d[d[:stimid] .== id, [:n, :prμ, :tμ, :tsem]][1,:])
#println("id $id : mprμ = $m_prμ dprμ = $d_prμ mtμ = $m_tμ dtμ = $d_tμ")
llh += bernllh(m_prμ, d_prμ, d_n) +
# we use d_n = 1, as we are already using the SEM
gausssemllh(m_tμ, d_tμ, √(abs2(d_tsem) + tndvar), 1)
n += d_n
end
return llh / n
end
###############################################################################
# model fitting function
# returns all tested and best-fitting model parameters and objective value for given model
function fitmodel(m::ModelBase, o::FittingObjective, ϕini::AbstractVector; verbose=true)
maxevals = 5000
ϕmin, ϕmax = minimumϕ(m), maximumϕ(m)
ϕn = length(ϕini)
# store tested parameters + LLHs
ϕs = Array{Float64}(undef, maxevals+1, ϕn+1)
# formats output vector of floats
fmtvec(x) = foldl((a, b) -> a * ", " * b, [@sprintf("%.2f", i) for i in x])
# verbose likelihood function
evalcount = -1 # start at -1 to not record first llhv(.) test call
function llhv(ϕ, g)
boundllh = llh(o, max.(ϕmin, min.(ϕmax, ϕ)))
if verbose && mod(evalcount, 20) == 0
@printf("%8d ϕ = [%s] llh = %f\n", evalcount, fmtvec(ϕ), boundllh)
end
evalcount += 1
if evalcount >= 1
ϕs[evalcount,:] = [ϕ; boundllh]
end
return boundllh
end
# Call the objective function once, to make sure it doesn't bug out.
# We do this here, as within NLopt.optimize, it doesn't generate an stack
# trace, which makes debugging impossible.
!verbose || print("Testing llh function...")
llhv(ϕini, Nothing)
!verbose || println(" passed")
# use subplex method, which is able to cope with noisy objective functions
opt = Opt(:LN_SBPLX, ϕn)
max_objective!(opt, llhv)
lower_bounds!(opt, ϕmin)
upper_bounds!(opt, ϕmax)
ftol_rel!(opt, 1e-8)
xtol_rel!(opt, 1e-32)
maxtime!(opt, 11 * 60 * 60) # 11h max
maxeval!(opt, maxevals) # max evaluations
!verbose || println(" iter result")
optllh, optϕ, ret = NLopt.optimize(opt, ϕini)
# add final value as last element
evalcount += 1
ϕs[evalcount,:] = [optϕ; optllh]
# return dataframe
return DataFrame(Any[ϕs[1:evalcount,i] for i in 1:ϕn+1], [ϕnames(m); :llh]), ret
end
fitmodel(m::ModelBase, o::FittingObjective; verbose=true) = fitmodel(m, o, initialϕ(m); verbose=verbose)