-
Notifications
You must be signed in to change notification settings - Fork 0
/
curve-fitting.jl
2142 lines (1780 loc) · 73.3 KB
/
curve-fitting.jl
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
526
527
528
529
530
531
532
533
534
535
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
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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
### A Pluto.jl notebook ###
# v0.19.40
using Markdown
using InteractiveUtils
# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).
macro bind(def, element)
quote
local iv = try Base.loaded_modules[Base.PkgId(Base.UUID("6e696c72-6542-2067-7265-42206c756150"), "AbstractPlutoDingetjes")].Bonds.initial_value catch; b -> missing; end
local el = $(esc(element))
global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)
el
end
end
# ╔═╡ 393b2f5e-6556-11eb-2119-cf7309ee7392
begin
using Chain
using CSV
using DataFrames
using HTTP
using LsqFit
using Measurements
using Plots
using PlutoUI
using Statistics
using Unitful
using URIs
end
# ╔═╡ 412eedac-658a-11eb-2326-93e5bf3d1a2c
md"""
# Fitting of equilibrium binding data
This notebook plots an equilibrium binding dataset (with error bars, for datasets containing replicates) and performs non-linear curve fitting of a model to the data.
The following reference explains very well the theory of equilibrium binding experiments, as well as many important practical considerations:
> Jarmoskaite I, AlSadhan I, Vaidyanathan PP & Herschlag D (2020) How to measure and evaluate binding affinities. *eLife* **9**: e57264 <https://doi.org/10.7554/eLife.57264>
"""
# ╔═╡ 270cc0cc-660f-11eb-241e-b75746a39cc7
md"""
## Load data
The data file must be in CSV format. The first row is assumed to contain column names. The first column is assumed to be the $X$ values, all other columns are assumed to be replicate $Y$ values that will be averaged (fitting will be done against the mean values, weighted by their standard deviations). In addition, there must not be any row with an $X = 0$ value (this would result in an error when attempting to plot with a logarithmic scale). I always perform two measurements at $X = 0$, and I always sort rows by descending $X$ values, so this notebook automatically skips the last two rows of the CSV file; adjust accordingly if you don't measure at $X = 0$ and want to keep all rows (see section [Data processing](#1884912a-6aeb-11eb-2b4a-d14d4a321dc5) below). The data does *not* need to be scaled such that $Y$ takes values between $0$ and $1$: the binding models can account for arbitrary minimum and maximum $Y$ values (see section [Model functions](#663a4cae-658a-11eb-382f-cf256c08c9d1) below). Scaling data will hide differences in signal change between datasets, while these differences may tell you something about the system under study, so scaling should never be done "blindly"; always look at the raw data.
Indicate below which data files to process:
- if the path given is not absolute, it is assumed to be relative to the notebook file (wherever the notebook is located)
- a list of files can be provided with one file path per line and separated by commas
- files can be located by local path or URL, but each type of location should be in the dedicated list
"""
# ╔═╡ a2c02fcf-9402-4938-bc3d-819b45a66afa
dataURLs = [
"https://raw.githubusercontent.com/Guillawme/julia-curve-fitting/main/datasets/dataset_006.csv",
"https://raw.githubusercontent.com/Guillawme/julia-curve-fitting/main/datasets/dataset_007.csv"
]
# ╔═╡ 14baf100-660f-11eb-1380-ebf4a860eed8
dataFiles = [
"datasets/dataset_008.csv",
"datasets/dataset_009.csv"
]
# ╔═╡ 2ce72e97-0133-4f15-bf1d-7fd04ccf3102
md"""
**Number of rows to ignore at the end of files:** $(@bind footerRows PlutoUI.NumberField(0:30, default = 2))
"""
# ╔═╡ 77316a92-425a-4902-9828-52a7c4a74f27
md"""
**Unit of your concentration values ($X$ axis):** $(
@bind chosenConcUnit PlutoUI.Select(
[
"pM" => "pM",
"nM" => "nM",
"μM" => "μM",
"mM" => "mM"
],
default = "nM"
))
"""
# ╔═╡ 214acce6-6ae8-11eb-3abf-492e50140317
md"""
Your data should appear below shortly, check that it looks normal. In addition to the columns present in your CSV file, you should see four columns named `mean`, `std`, `measurement` and `conc` (these values will be used for fitting and plotting).
"""
# ╔═╡ d5b0e2a1-865c-489c-9d0d-c4ae043828fb
# By defaults, use file names and URLs to identify datasets.
datasetNames = vcat(dataURLs, dataFiles)
# But one can also use custom names.
#datasetNames = ["Monday", "Tuesday", "Wednesday", "Thursday"]
# ╔═╡ 5c5e0392-658a-11eb-35be-3d940d4504cb
md"""
## Visualizations
Your data and fit should appear below shortly. Take a good look at the [data and fit](#3dd72c58-6b2c-11eb-210f-0b547bf38ebe), make sure you check the [residuals](#4f4000b4-6b2c-11eb-015f-d76a0adda0a0). Once you're happy with it, check the [numerical results](#be17b97e-663a-11eb-2158-a381c19ece3f).
"""
# ╔═╡ 3dd72c58-6b2c-11eb-210f-0b547bf38ebe
md"""
### Data and fit
Select binding model:
"""
# ╔═╡ 3da83f72-6a11-11eb-1a74-49b66eb39c96
@bind chosenModel PlutoUI.Radio(
[
"Hill" => :Hill,
"Hyperbolic" => :Hyperbolic,
"Quadratic" => :Quadratic
],
default = "Hill"
)
# ╔═╡ d15cba72-6aeb-11eb-2c80-65702b48e859
md"""
Show fit line with initial parameters?
$@bind showInitialFit PlutoUI.CheckBox(default = false)
"""
# ╔═╡ 01b59d8a-6637-11eb-0da0-8d3e314e23af
md"""
For the quadratic model, indicate receptor concentration (the receptor is the binding partner kept at constant, low concentration across the titration series).
Parameter $R_0 =$
$@bind R0 PlutoUI.Slider(0.01:0.1:500.0, default = 5.0, show_value = true)
"""
# ╔═╡ 4f4000b4-6b2c-11eb-015f-d76a0adda0a0
md"""
### Residuals
"""
# ╔═╡ c50cf18c-6b11-11eb-07d3-0b8e332ec5bc
md"""
The fit residuals should follow a random normal distribution around $0$. If they show a systematic trend, it means the fit systematically deviates from your data, and therefore the model you chose might not be justified (but be careful when considering alternative models: introducing more free parameters will likely get the fit line closer to the data points and yield a lower [sum of squared residuals](#124c4f94-6b99-11eb-2921-d7c2cd00b893), but this is not helpful if these additional parameters don't contribute to explaining the physical phenomenon being modeled). Another possibility is a problem with your data. The most common problems are:
- the data does not cover the proper concentration range
- the concentration of receptor is too high relative to the $K_D$
In either case, your best option is to design a new experiment and collect new data.
"""
# ╔═╡ 5a36fc3f-ce74-42c8-8284-19321e0d687f
md"""
#### Scatter plot
"""
# ╔═╡ 5392d99b-70f9-48cd-90b4-58cba5fc9681
md"""
#### Histogram
"""
# ╔═╡ be17b97e-663a-11eb-2158-a381c19ece3f
md"""
## Numerical results
### Model parameters
The parameter $K_D$ is in unit of $(chosenConcUnit).
"""
# ╔═╡ 124c4f94-6b99-11eb-2921-d7c2cd00b893
md"""
### Sum of squared residuals
"""
# ╔═╡ 7e7a9dc4-6ae8-11eb-128d-83544f01b78b
md"""
## Code
The code doing the actual work is in this section. Do not edit unless you know what you are doing.
"""
# ╔═╡ 512e3028-6ae9-11eb-31b4-1bc9fc66b322
md"### Necessary packages and notebook setup"
# ╔═╡ abc03f64-6a11-11eb-0319-ed7cea455cb5
PlutoUI.TableOfContents()
# ╔═╡ 1884912a-6aeb-11eb-2b4a-d14d4a321dc5
md"### Data processing"
# ╔═╡ c94ef72d-bd12-4434-935e-01e94d5a4588
md"""
#### Concentration unit selection
"""
# ╔═╡ 54272681-dfeb-4034-b127-7e68c19fd576
md"""
First, we need an alias of M (molar) for mol/L, since this is the notation most widely used in the field:
"""
# ╔═╡ 731492c6-95c7-449f-8c19-53e22ab438b8
begin
Unitful.register(@__MODULE__)
@unit M "M" Molar 1u"mol/L" true
end
# ╔═╡ 93ef0431-643b-4f6f-8c09-beabff59e0c6
md"""
Check that our alias works:
"""
# ╔═╡ 1c10231d-3bea-4468-a2d8-886c05c6474c
typeof(M)
# ╔═╡ 730b693d-cca8-46de-8382-c151b5f63352
1u"nM" == 1u"nmol/l"
# ╔═╡ 24152a84-523b-4027-9b5a-7e3524b9c659
dimension(1u"nM") == dimension(1u"mol/l")
# ╔═╡ 97f73ee4-3db7-43ba-93eb-17025b485f4f
md"""
This dictionary maps dropdown menu options (in section [Load data](#270cc0cc-660f-11eb-241e-b75746a39cc7) above) to their corresponding unit:
"""
# ╔═╡ 8f2d959e-5e61-48a9-bbf0-538bc1d478a8
concUnits = Dict(
"pM" => u"pM",
"nM" => u"nM",
"μM" => u"μM",
"mM" => u"mM"
)
# ╔═╡ c866d213-4680-4b08-8ecc-1faefc8661a4
md"""
The following cells simply check which unit is selected in section [Load data](#008f4f8c-9d21-11eb-0fea-f3b2e58957d1) above.
"""
# ╔═╡ 8e9cd30f-1722-4f2f-a26b-2f558805d4a1
chosenConcUnit
# ╔═╡ 13417555-be95-4662-ad11-eca4dece81b5
concUnits[chosenConcUnit]
# ╔═╡ 9c7e922e-c82f-41a4-9513-4462a0559c3f
md"""
#### Processing
"""
# ╔═╡ 4f4b580d-507c-4ad0-b1d5-5967c8ed829e
md"""
The `commonProcessing()` function computes the mean and standard deviation of replicates, defines measurements as mean ± std, and returns a DataFrame containing all the data. It is used by all methods of the following `processData()` function, which handle various inputs (path to a local file, URL to a remote file, loaded CSV file, loaded DataFrame).
"""
# ╔═╡ 5eb607c7-172b-4a6c-a815-acbc195108f0
function commonProcessing(data::DataFrame)
df = @chain data begin
# Rename column 1, so we can always call it by the
# same name regardless of its name in the input file.
rename(1 => :concentration)
@aside cols = ncol(_)
transform(
# Calculate mean and stddev of replicates
# (all columns in input except first one).
AsTable(2:cols) => ByRow(mean) => :mean,
AsTable(2:cols) => ByRow(std) => :std
)
transform(
# Mean and stddev together define a measurement
# (this is only for plotting; fitting uses the two
# original columns separately).
[:mean, :std] => ByRow(measurement) => :measurement
)
transform(
# Assign unit to concentration column, store as
# a new column callec conc (only for plotting).
:concentration => ByRow(x -> x * concUnits[chosenConcUnit]) => :conc
)
end
return df
end
# ╔═╡ 992c86a2-6b13-11eb-1e00-95bdff2736d0
md"""
The `processData()` function loads one data file, computes the mean and standard deviation of replicates, defines measurements as mean ± std, and returns a DataFrame containing all the data.
"""
# ╔═╡ 1fe4d112-6a11-11eb-37a6-bf95fbe032b1
function processData(dataFile::String)
df = @chain dataFile begin
CSV.read(footerskip=footerRows, DataFrame)
commonProcessing()
end
return df
end
# ╔═╡ 5cc812af-4f8e-444b-9652-fb063cc6be06
md"""
This functions should also work if passed an URL to a remote file:
"""
# ╔═╡ 7c2af794-a0ed-4827-bc8e-1f15ad205eca
function processData(dataFile::URI)
df = @chain dataFile begin
HTTP.get(_).body
CSV.read(footerskip=footerRows, DataFrame)
commonProcessing()
end
return df
end
# ╔═╡ a08d1b29-fa5e-4312-977c-39b050de4516
md"""
This functions should also work if passed an already loaded CSV file:
"""
# ╔═╡ 0181a0b1-ec6c-4325-8b3a-851a3fe33846
function processData(dataFile::CSV.File)
df = @chain dataFile begin
DataFrame()
commonProcessing()
end
return df
end
# ╔═╡ 247c2416-6c67-11eb-01df-8dac01cdbf8f
md"""
This functions should also work if passed an already loaded data frame (for example, if the user wants to load data and pre-process it in a different way before averaging replicates):
"""
# ╔═╡ 36ebe112-6c66-11eb-11f0-7fdb946865e4
function processData(data::DataFrame)
return commonProcessing(data)
end
# ╔═╡ d904fd76-6af1-11eb-2352-837e03072137
begin
allData = vcat(URI.(dataURLs), dataFiles)
dfs = [ processData(df) for df in allData ]
end
# ╔═╡ 0e8af3be-7ae7-4ec2-8d7a-670878cd52ee
md"""
We will need to keep track of dataset names. You can edit them here if you want to use something more meaningful than the file name or URL; changes will propagate to plot legends. This list **must** contain the same number of elements as you have datasets: **$(length(allData))** in the present case.
"""
# ╔═╡ 8e105fae-6aec-11eb-1471-83aebb776241
md"### Plotting"
# ╔═╡ 97c5020c-6aec-11eb-024b-513b1e603d98
md"The `initMainPlot()` function initializes a plot, the `plotOneDataset!()` function plots one dataset (call it repeatedly to plot more datasets on the same axes)."
# ╔═╡ caf4a4a2-6aec-11eb-2765-49d67afa47dd
function initMainPlot()
plot(
xlabel = "Concentration",
ylabel = "Signal",
xscale = :log10,
legend = :topleft
)
end
# ╔═╡ fc194672-6aed-11eb-0a06-2d967ec094b1
md"The `initResidualPlot()` function initializes a plot, the `plotOneResiduals!()` function plots the fit residuals from one dataset (call it repeatedly to plot more datasets on the same axes)."
# ╔═╡ 14db987c-6aee-11eb-06cf-a11987b98f1e
function initResidualPlot()
plot(
xlabel = "Concentration",
ylabel = "Fit residual",
xscale = :log10,
legend = :topleft
)
hline!([0], label = nothing, color = :red)
end
# ╔═╡ 7f83b838-6a11-11eb-3652-bdff24f3473e
function plotOneResiduals!(plt, df, fit, filePath)
title = split(filePath, "/")[end]
scatter!(
plt,
df.concentration,
fit.resid,
label = "$title: $chosenModel fit residual"
)
end
# ╔═╡ 9020fa5d-7408-4161-a52f-df37b3c2e6f5
md"The `initResidualHistogram()` function initializes a histogram, the `plotOneResidualsHistogram!()` function plots a histogram of the fit residuals from one dataset (call it repeatedly to plot more datasets on the same axes)."
# ╔═╡ 3184d209-1cc9-40ed-a9ec-9f094c5c94b5
function initResidualHistogram()
histogram(
xlabel = "Fit residual",
ylabel = "Count",
legend = :topleft
)
vline!([0], label = nothing, color = :red)
end
# ╔═╡ b38cd229-64e2-4ca4-a78b-8881ec166b09
function plotOneResidualsHistogram!(plt, df, fit, filePath)
title = split(filePath, "/")[end]
histogram!(
plt,
fit.resid,
bins = length(fit.resid),
label = "$title: $chosenModel fit residual"
)
end
# ╔═╡ 663a4cae-658a-11eb-382f-cf256c08c9d1
md"### Model functions"
# ╔═╡ 594e7534-6aeb-11eb-1254-3b92b71877ed
md"#### Model selection"
# ╔═╡ 32dce844-6aee-11eb-3cf2-3ba420d311d3
md"""
This dictionary maps radio button options (in section [Visualizations](#5c5e0392-658a-11eb-35be-3d940d4504cb) above) to their corresponding model function:
"""
# ╔═╡ a1f56b0a-6aeb-11eb-0a44-556fad58f368
md"""
The remaining cells in this section are only meant to check that the model selection buttons work. This first cell should return the name of the selected binding model (corresponding to the active radio button in section [Visualizations](#5c5e0392-658a-11eb-35be-3d940d4504cb) above):
"""
# ╔═╡ 5be2e5d2-6a11-11eb-1421-492f5af16f9c
chosenModel
# ╔═╡ 58617378-6aee-11eb-23e8-c13d89b4c57f
md"""
This other cell should return the model function corresponding to the selected binding model (the active radio button in section [Visualizations](#5c5e0392-658a-11eb-35be-3d940d4504cb) above):
"""
# ╔═╡ 88d941e6-658a-11eb-08a2-0f021e5ae3a4
md"""
#### Hill model
This is the [Hill equation](https://en.wikipedia.org/wiki/Hill_equation_(biochemistry)):
$S = S_{min} + (S_{max} - S_{min}) \times \frac{L^h}{{K_D}^h + L^h}$
In which $S$ is the measured signal ($Y$ value) at a given value of ligand concentration $L$ ($X$ value), $S_{min}$ and $S_{max}$ are the minimum and maximum values the observed signal can take, respectively, $K_D$ is the equilibrium dissociation constant and $h$ is the Hill coefficient."""
# ╔═╡ e9fc3d44-6559-11eb-2da7-314e8fc76ee9
@. hill(conc, p) = p[1] + (p[2] - p[1]) * conc^p[4] / (p[3]^p[4] + conc^p[4])
# ╔═╡ 9d1f24cc-6a0f-11eb-3b16-35f89aff5d4a
md"""
#### Hyperbolic model
The hyperbolic equation is a special case of the Hill equation, in which $h = 1$:
"""
# ╔═╡ 78e664d0-6618-11eb-135b-5574bb05ddef
@. hyperbolic(conc, p) = p[1] + (p[2] - p[1]) * conc / (p[3] + conc)
# ╔═╡ b0b17206-6a0f-11eb-2f5e-5fc8fa06cd36
md"""
#### Quadratic model
Unlike the Hill and hyperbolic models, the quadratic model does not make the approximation that the concentration of free ligand at equilibrium is equal to the total ligand concentration:
$S = S_{min} + (S_{max} - S_{min}) \times \frac{(K_{D} + R_{tot} + L_{tot}) - \sqrt{(- K_{D} - R_{tot} - L_{tot})^2 - 4 \times R_{tot} \times L_{tot}}}{2 \times R_{tot}}$
Symbols have the same meaning as in the previous equations, except here $L_{tot}$ is the total concentration of ligand, not the concentration of free ligand at equilibrium. $R_{tot}$ is the total concentration of receptor.
In principle, $R_{tot}$ could be left as a free parameter to be determined by the fitting procedure, but in general it is known accurately enough from the experimental set up, and one should replicate the same experiment with different concentrations of receptor to check its effect on the results. $R_{tot}$ should be set in the experiment to be smaller than $K_D$, ideally, or at least of the same order of magnitude than $K_D$. It might take a couple experiments to obtain an estimate of $K_D$ before one can determine an adequately small concentration of receptor at which to perform a definite experiment.
"""
# ╔═╡ 5694f1da-6636-11eb-0fed-9fee5c48b114
@. quadratic(conc, p) = p[1] + (p[2] - p[1]) * ( (p[3] + R0 + conc) - sqrt((- p[3] - R0 - conc) ^ 2 - 4 * R0 * conc) ) / (2 * R0)
# ╔═╡ 605f06ae-6a11-11eb-0b2f-eb81f6526829
bindingModels = Dict(
"Hill" => hill,
"Hyperbolic" => hyperbolic,
"Quadratic" => quadratic
)
# ╔═╡ 7c03fcbe-6a11-11eb-1b7b-cbad863156a6
function plotOneDataset!(plt, df, fit, filePath, showInitial = false, initialValues = nothing)
title = split(filePath, "/")[end]
scatter!(
plt,
df.conc,
df.measurement,
label = "$title: data"
)
if showInitial
plot!(
plt,
df.conc,
bindingModels[chosenModel](df.concentration, initialValues),
label = "$title: $chosenModel fit (initial)",
color = :grey
)
plot!(
plt,
df.conc,
bindingModels[chosenModel](df.concentration, fit.param),
label = "$title: $chosenModel fit (converged)",
color = :red
)
else
plot!(
plt,
df.conc,
bindingModels[chosenModel](df.concentration, fit.param),
label = "$title: $chosenModel fit",
color = :red
)
end
end
# ╔═╡ 6668c49a-6a11-11eb-2abf-5feecaee8972
bindingModels[chosenModel]
# ╔═╡ 0f960a8a-6a0f-11eb-04e2-b543192f6354
md"### Parameters and their initial values"
# ╔═╡ 2eb890a4-658c-11eb-1fc4-af645d74109d
md"""
The `findInitialValues()` function takes the measured data and returns an array containing initial values for the model parameters (in this order): $S_{min}$, $S_{max}$, $K_D$ and $h$ (for the Hill model only, so the function needs to know which model was selected).
Initial values for $S_{min}$ and $S_{max}$ are simply taken as the minimal and maximal values found in the data. The initial estimate for $K_D$ is the concentration of the data point that has a signal closest to halfway between $S_{min}$ and $S_{max}$ (if the experiment was properly designed, this is a reasonable estimate and close enough to the true value for the fit to converge). The initial estimate of $h$ is $1.0$, meaning we assume no cooperativity.
"""
# ╔═╡ ca2d2f12-6a1a-11eb-13ca-1f93df2b8e4a
function findInitialValues(df, model)
halfSignal = minimum(df.mean) + (maximum(df.mean) - minimum(df.mean)) / 2
if model == "Hill"
params = [
minimum(df.mean),
maximum(df.mean),
df.concentration[findmin(abs.(halfSignal .- df.mean))[2]],
1.0
]
else
params = [
minimum(df.mean),
maximum(df.mean),
df.concentration[findmin(abs.(halfSignal .- df.mean))[2]]
]
end
end
# ╔═╡ 9be41e32-6af0-11eb-0904-d1cf3c288cab
md"Determine initial values of the selected model's parameters from the currently loaded datasets:"
# ╔═╡ 67b538f6-6a1b-11eb-3004-2d89c2f941e8
initialParams = [ findInitialValues(df, chosenModel) for df in dfs ]
# ╔═╡ 213e8ffa-6a0f-11eb-357e-638146193c5d
md"### Fitting"
# ╔═╡ babcb896-6af0-11eb-194a-15922bc2df83
md"Perform fit of the selected model to the measurements' mean values using initial values for the model parameters determined previously. If the dataset contains replicates, the fit will be weighted by the measurements' standard deviations."
# ╔═╡ 47426056-6af2-11eb-17f8-6d27d35003ca
begin
fits = Vector{LsqFit.LsqFitResult}(undef, length(allData))
for (df, initialValues, i) in zip(dfs, initialParams, 1:length(allData))
if ncol(df) > 5
# If the dataset has more than 5 columns, it means it has
# replicate Y values, so we weight the fit by their stddev.
fits[i] = curve_fit(bindingModels[chosenModel],
df.concentration,
df.mean,
df.std,
initialValues)
else
# If the dataset has only 5 columns, it means it doesn't have
# replicate Y values, so there are no stddev we can use as weights.
fits[i] = curve_fit(bindingModels[chosenModel],
df.concentration,
df.mean,
initialValues)
end
end
fits
end
# ╔═╡ 264bf9ec-6af5-11eb-1ffd-79fb3466f596
begin
dataPlot = initMainPlot()
for (df, fit, title, initialVals) in zip(dfs, fits, datasetNames, initialParams)
plotOneDataset!(dataPlot, df, fit, title, showInitialFit, initialVals)
end
dataPlot
end
# ╔═╡ a951b5dc-6af7-11eb-2401-5d11a14e3067
begin
residualPlot = initResidualPlot()
for (df, fit, title) in zip(dfs, fits, datasetNames)
plotOneResiduals!(residualPlot, df, fit, title)
end
residualPlot
end
# ╔═╡ 7625d41a-dab1-4b10-947c-3667c03f85aa
begin
residualHistogram = initResidualHistogram()
for (df, fit, title) in zip(dfs, fits, datasetNames)
plotOneResidualsHistogram!(residualHistogram, df, fit, title)
end
residualHistogram
end
# ╔═╡ 2109f516-6b99-11eb-05a0-99b9ecfd0f9d
PlutoUI.with_terminal() do
println("Dataset\t\t\t\tSum of squared residuals")
for (dataset, fit) in zip(datasetNames, fits)
println(
split(dataset, "/")[end],
"\t\t",
round(sum(fit.resid.^2), digits = 2)
)
end
end
# ╔═╡ 799680d0-6af1-11eb-321d-b7758a40f931
md"Degrees of freedom:"
# ╔═╡ 1f0384de-659b-11eb-043e-5b86fcdd36e6
dof.(fits)
# ╔═╡ 54501a10-6b9c-11eb-29de-77afc3772fb7
md"Best fit parameters:"
# ╔═╡ 5ed3ab64-6b9c-11eb-149e-43a1ef12ac7d
coef.(fits)
# ╔═╡ 8643b03c-6af1-11eb-0aa7-67acee28d2c0
md"Standard errors of best-fit parameters:"
# ╔═╡ a74998b4-659c-11eb-354d-09ff62710b87
paramsStdErrors = stderror.(fits)
# ╔═╡ 090347fc-6b8e-11eb-0e17-9d9d45749c0b
PlutoUI.with_terminal() do
if length(initialParams[1]) == 3
# No Hill coefficient to report.
println("Dataset\t\t\t\tKd\t\t\t\tSmin\t\t\tSmax")
for (dataset, fit, stderr) in zip(datasetNames, fits, paramsStdErrors)
println(
split(dataset, "/")[end],
"\t\t",
round(fit.param[3], digits = 1),
" ± ",
round(stderr[3], digits = 1),
"\t\t",
round(fit.param[1], digits = 1),
" ± ",
round(stderr[1], digits = 1),
"\t\t",
round(fit.param[2], digits = 1),
" ± ",
round(stderr[2], digits = 1)
)
end
elseif length(initialParams[1]) == 4
# There is a Hill coefficient to report.
println("Dataset\t\t\t\tKd\t\t\t\tSmin\t\t\tSmax\t\t\th")
for (dataset, fit, stderr) in zip(datasetNames, fits, paramsStdErrors)
println(
split(dataset, "/")[end],
"\t\t",
round(fit.param[3], digits = 1),
" ± ",
round(stderr[3], digits = 1),
"\t\t",
round(fit.param[1], digits = 1),
" ± ",
round(stderr[1], digits = 1),
"\t\t",
round(fit.param[2], digits = 1),
" ± ",
round(stderr[2], digits = 1),
"\t\t",
round(fit.param[4], digits = 1),
" ± ",
round(stderr[4], digits = 1),
)
end
else
# Other number of values in the parameters array make no sense.
println("Error.")
end
end
# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
CSV = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b"
Chain = "8be319e6-bccf-4806-a6f7-6fae938471bc"
DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
HTTP = "cd3eb016-35fb-5094-929b-558a96fad6f3"
LsqFit = "2fda8390-95c7-5789-9bda-21331edee243"
Measurements = "eff96d63-e80a-5855-80a2-b1b0885c5ab7"
Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80"
PlutoUI = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
URIs = "5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4"
Unitful = "1986cc42-f94f-5a68-af5c-568840ba703d"
[compat]
CSV = "~0.10.10"
Chain = "~0.5.0"
DataFrames = "~1.5.0"
HTTP = "~1.9.1"
LsqFit = "~0.13.0"
Measurements = "~2.9.0"
Plots = "~1.38.11"
PlutoUI = "~0.7.51"
URIs = "~1.4.2"
Unitful = "~1.13.1"
"""
# ╔═╡ 00000000-0000-0000-0000-000000000002
PLUTO_MANIFEST_TOML_CONTENTS = """
# This file is machine-generated - editing it directly is not advised
julia_version = "1.10.2"
manifest_format = "2.0"
project_hash = "dd9257f271393279d2df66772802cc6ad2786177"
[[deps.AbstractPlutoDingetjes]]
deps = ["Pkg"]
git-tree-sha1 = "8eaf9f1b4921132a4cff3f36a1d9ba923b14a481"
uuid = "6e696c72-6542-2067-7265-42206c756150"
version = "1.1.4"
[[deps.Adapt]]
deps = ["LinearAlgebra", "Requires"]
git-tree-sha1 = "cc37d689f599e8df4f464b2fa3870ff7db7492ef"
uuid = "79e6a3ab-5dfb-504d-930d-738a2a938a0e"
version = "3.6.1"
weakdeps = ["StaticArrays"]
[deps.Adapt.extensions]
AdaptStaticArraysExt = "StaticArrays"
[[deps.ArgTools]]
uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f"
version = "1.1.1"
[[deps.ArrayInterface]]
deps = ["Adapt", "LinearAlgebra", "Requires", "SnoopPrecompile", "SparseArrays", "SuiteSparse"]
git-tree-sha1 = "38911c7737e123b28182d89027f4216cfc8a9da7"
uuid = "4fba245c-0d91-5ea0-9b3e-6abc04ee57a9"
version = "7.4.3"
[deps.ArrayInterface.extensions]
ArrayInterfaceBandedMatricesExt = "BandedMatrices"
ArrayInterfaceBlockBandedMatricesExt = "BlockBandedMatrices"
ArrayInterfaceCUDAExt = "CUDA"
ArrayInterfaceGPUArraysCoreExt = "GPUArraysCore"
ArrayInterfaceStaticArraysCoreExt = "StaticArraysCore"
ArrayInterfaceTrackerExt = "Tracker"
[deps.ArrayInterface.weakdeps]
BandedMatrices = "aae01518-5342-5314-be14-df237901396f"
BlockBandedMatrices = "ffab5731-97b5-5995-9138-79e8c1846df0"
CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba"
GPUArraysCore = "46192b85-c4d5-4398-a991-12ede77f4527"
StaticArraysCore = "1e83bf80-4336-4d27-bf5d-d5a4f845583c"
Tracker = "9f7883ad-71c0-57eb-9f7f-b5c9e6d3789c"
[[deps.Artifacts]]
uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33"
[[deps.Base64]]
uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"
[[deps.BitFlags]]
git-tree-sha1 = "43b1a4a8f797c1cddadf60499a8a077d4af2cd2d"
uuid = "d1d4a3ce-64b1-5f1a-9ba4-7e7e69966f35"
version = "0.1.7"
[[deps.Bzip2_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "19a35467a82e236ff51bc17a3a44b69ef35185a2"
uuid = "6e34b625-4abd-537c-b88f-471c36dfa7a0"
version = "1.0.8+0"
[[deps.CSV]]
deps = ["CodecZlib", "Dates", "FilePathsBase", "InlineStrings", "Mmap", "Parsers", "PooledArrays", "PrecompileTools", "SentinelArrays", "Tables", "Unicode", "WeakRefStrings", "WorkerUtilities"]
git-tree-sha1 = "ed28c86cbde3dc3f53cf76643c2e9bc11d56acc7"
uuid = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b"
version = "0.10.10"
[[deps.Cairo_jll]]
deps = ["Artifacts", "Bzip2_jll", "CompilerSupportLibraries_jll", "Fontconfig_jll", "FreeType2_jll", "Glib_jll", "JLLWrappers", "LZO_jll", "Libdl", "Pixman_jll", "Pkg", "Xorg_libXext_jll", "Xorg_libXrender_jll", "Zlib_jll", "libpng_jll"]
git-tree-sha1 = "4b859a208b2397a7a623a03449e4636bdb17bcf2"
uuid = "83423d85-b0ee-5818-9007-b63ccbeb887a"
version = "1.16.1+1"
[[deps.Calculus]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "f641eb0a4f00c343bbc32346e1217b86f3ce9dad"
uuid = "49dc2e85-a5d0-5ad3-a950-438e2897f1b9"
version = "0.5.1"
[[deps.Chain]]
git-tree-sha1 = "8c4920235f6c561e401dfe569beb8b924adad003"
uuid = "8be319e6-bccf-4806-a6f7-6fae938471bc"
version = "0.5.0"
[[deps.CodecZlib]]
deps = ["TranscodingStreams", "Zlib_jll"]
git-tree-sha1 = "9c209fb7536406834aa938fb149964b985de6c83"
uuid = "944b1d66-785c-5afd-91f1-9de20f533193"
version = "0.7.1"
[[deps.ColorSchemes]]
deps = ["ColorTypes", "ColorVectorSpace", "Colors", "FixedPointNumbers", "PrecompileTools", "Random"]
git-tree-sha1 = "be6ab11021cd29f0344d5c4357b163af05a48cba"
uuid = "35d6a980-a343-548e-a6ea-1d62b119f2f4"
version = "3.21.0"
[[deps.ColorTypes]]
deps = ["FixedPointNumbers", "Random"]
git-tree-sha1 = "eb7f0f8307f71fac7c606984ea5fb2817275d6e4"
uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f"
version = "0.11.4"
[[deps.ColorVectorSpace]]
deps = ["ColorTypes", "FixedPointNumbers", "LinearAlgebra", "SpecialFunctions", "Statistics", "TensorCore"]
git-tree-sha1 = "600cc5508d66b78aae350f7accdb58763ac18589"
uuid = "c3611d14-8923-5661-9e6a-0046d554d3a4"
version = "0.9.10"
[[deps.Colors]]
deps = ["ColorTypes", "FixedPointNumbers", "Reexport"]
git-tree-sha1 = "fc08e5930ee9a4e03f84bfb5211cb54e7769758a"
uuid = "5ae59095-9a9b-59fe-a467-6f913c188581"
version = "0.12.10"
[[deps.CommonSubexpressions]]
deps = ["MacroTools", "Test"]
git-tree-sha1 = "7b8a93dba8af7e3b42fecabf646260105ac373f7"
uuid = "bbf7d656-a473-5ed7-a52c-81e309532950"
version = "0.3.0"
[[deps.Compat]]
deps = ["UUIDs"]
git-tree-sha1 = "7a60c856b9fa189eb34f5f8a6f6b5529b7942957"
uuid = "34da2185-b29b-5c13-b0c7-acf172513d20"
version = "4.6.1"
weakdeps = ["Dates", "LinearAlgebra"]
[deps.Compat.extensions]
CompatLinearAlgebraExt = "LinearAlgebra"
[[deps.CompilerSupportLibraries_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae"
version = "1.1.0+0"
[[deps.ConcurrentUtilities]]
deps = ["Serialization", "Sockets"]
git-tree-sha1 = "96d823b94ba8d187a6d8f0826e731195a74b90e9"
uuid = "f0e56b4a-5159-44fe-b623-3e5288b988bb"
version = "2.2.0"
[[deps.ConstructionBase]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "738fec4d684a9a6ee9598a8bfee305b26831f28c"
uuid = "187b0558-2788-49d3-abe0-74a17ed4e7c9"
version = "1.5.2"
[deps.ConstructionBase.extensions]
ConstructionBaseIntervalSetsExt = "IntervalSets"
ConstructionBaseStaticArraysExt = "StaticArrays"
[deps.ConstructionBase.weakdeps]
IntervalSets = "8197267c-284f-5f27-9208-e0e47529a953"
StaticArrays = "90137ffa-7385-5640-81b9-e52037218182"
[[deps.Contour]]
git-tree-sha1 = "d05d9e7b7aedff4e5b51a029dced05cfb6125781"
uuid = "d38c429a-6771-53c6-b99e-75d170b6e991"
version = "0.6.2"
[[deps.Crayons]]
git-tree-sha1 = "249fe38abf76d48563e2f4556bebd215aa317e15"
uuid = "a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f"
version = "4.1.1"
[[deps.DataAPI]]
git-tree-sha1 = "e8119c1a33d267e16108be441a287a6981ba1630"
uuid = "9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a"
version = "1.14.0"
[[deps.DataFrames]]
deps = ["Compat", "DataAPI", "Future", "InlineStrings", "InvertedIndices", "IteratorInterfaceExtensions", "LinearAlgebra", "Markdown", "Missings", "PooledArrays", "PrettyTables", "Printf", "REPL", "Random", "Reexport", "SentinelArrays", "SnoopPrecompile", "SortingAlgorithms", "Statistics", "TableTraits", "Tables", "Unicode"]
git-tree-sha1 = "aa51303df86f8626a962fccb878430cdb0a97eee"
uuid = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
version = "1.5.0"
[[deps.DataStructures]]
deps = ["Compat", "InteractiveUtils", "OrderedCollections"]
git-tree-sha1 = "d1fff3a548102f48987a52a2e0d114fa97d730f0"
uuid = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8"
version = "0.18.13"
[[deps.DataValueInterfaces]]
git-tree-sha1 = "bfc1187b79289637fa0ef6d4436ebdfe6905cbd6"
uuid = "e2d170a0-9d28-54be-80f0-106bbe20a464"
version = "1.0.0"
[[deps.Dates]]
deps = ["Printf"]
uuid = "ade2ca70-3891-5945-98fb-dc099432e06a"
[[deps.DelimitedFiles]]
deps = ["Mmap"]
git-tree-sha1 = "9e2f36d3c96a820c678f2f1f1782582fcf685bae"
uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab"
version = "1.9.1"
[[deps.DiffResults]]
deps = ["StaticArraysCore"]
git-tree-sha1 = "782dd5f4561f5d267313f23853baaaa4c52ea621"
uuid = "163ba53b-c6d8-5494-b064-1a9d43ac40c5"
version = "1.1.0"
[[deps.DiffRules]]
deps = ["IrrationalConstants", "LogExpFunctions", "NaNMath", "Random", "SpecialFunctions"]
git-tree-sha1 = "a4ad7ef19d2cdc2eff57abbbe68032b1cd0bd8f8"
uuid = "b552c78f-8df3-52c6-915a-8e097449b14b"
version = "1.13.0"
[[deps.Distributed]]
deps = ["Random", "Serialization", "Sockets"]
uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b"
[[deps.Distributions]]
deps = ["FillArrays", "LinearAlgebra", "PDMats", "Printf", "QuadGK", "Random", "SparseArrays", "SpecialFunctions", "Statistics", "StatsAPI", "StatsBase", "StatsFuns", "Test"]
git-tree-sha1 = "eead66061583b6807652281c0fbf291d7a9dc497"
uuid = "31c24e10-a181-5473-b8eb-7969acd0382f"
version = "0.25.90"
[deps.Distributions.extensions]
DistributionsChainRulesCoreExt = "ChainRulesCore"
DistributionsDensityInterfaceExt = "DensityInterface"
[deps.Distributions.weakdeps]
ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
DensityInterface = "b429d917-457f-4dbc-8f4c-0cc954292b1d"
[[deps.DocStringExtensions]]
deps = ["LibGit2"]
git-tree-sha1 = "2fb1e02f2b635d0845df5d7c167fec4dd739b00d"
uuid = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae"
version = "0.9.3"
[[deps.Downloads]]
deps = ["ArgTools", "FileWatching", "LibCURL", "NetworkOptions"]
uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6"
version = "1.6.0"
[[deps.DualNumbers]]
deps = ["Calculus", "NaNMath", "SpecialFunctions"]
git-tree-sha1 = "5837a837389fccf076445fce071c8ddaea35a566"
uuid = "fa6b7ba4-c1ee-5f82-b5fc-ecf0adba8f74"
version = "0.6.8"
[[deps.EpollShim_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "8e9441ee83492030ace98f9789a654a6d0b1f643"
uuid = "2702e6a9-849d-5ed8-8c21-79e8b8f9ee43"
version = "0.0.20230411+0"
[[deps.Expat_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "bad72f730e9e91c08d9427d5e8db95478a3c323d"
uuid = "2e619515-83b5-522b-bb60-26c02a35a201"
version = "2.4.8+0"
[[deps.FFMPEG]]
deps = ["FFMPEG_jll"]
git-tree-sha1 = "b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8"
uuid = "c87230d0-a227-11e9-1b43-d7ebe4e7570a"
version = "0.4.1"
[[deps.FFMPEG_jll]]
deps = ["Artifacts", "Bzip2_jll", "FreeType2_jll", "FriBidi_jll", "JLLWrappers", "LAME_jll", "Libdl", "Ogg_jll", "OpenSSL_jll", "Opus_jll", "PCRE2_jll", "Pkg", "Zlib_jll", "libaom_jll", "libass_jll", "libfdk_aac_jll", "libvorbis_jll", "x264_jll", "x265_jll"]
git-tree-sha1 = "74faea50c1d007c85837327f6775bea60b5492dd"
uuid = "b22a6f82-2f65-5046-a5b2-351ab43fb4e5"
version = "4.4.2+2"
[[deps.FilePathsBase]]
deps = ["Compat", "Dates", "Mmap", "Printf", "Test", "UUIDs"]
git-tree-sha1 = "e27c4ebe80e8699540f2d6c805cc12203b614f12"
uuid = "48062228-2e41-5def-b9a4-89aafe57970f"
version = "0.9.20"