-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalysis.py
More file actions
1668 lines (1308 loc) · 58.2 KB
/
Copy pathanalysis.py
File metadata and controls
1668 lines (1308 loc) · 58.2 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
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
# -*- coding:utf8 -*-
#
# ------> AUTHOR INFO <------------------------------------------------
#
# analysis module
# Author: Sergio García Pajares
# Mail me 'sergio.garcia.pajares @alumnos.uva.es' or
# 'sergiogarciapajares@gmail.com'
# last update: 05-01-2021
#
# ------> LICENSE <----------------------------------------------------
#
# Copyright 2019 Sergio G. Pajares <sergio@sergio-linux>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#=======================================================================
#==== INFO =============================================================
#=======================================================================
'''
This is an analysis module was originally developed for TEI (Experimetal
Techniques I), a compulsary course of Physics Degree at University of
Oviedo. But its development was kept as a hobby for his author.
Contains:
- Regresion tools that gets the fitting coeficients
- Some analytic basic function to work with raw labdata
- Plot special funtion that manage errorbars and fitting
- Some OS manage functions to automatize some common processes
- Some physical constants
Dependencies:
- NumPy
- SciPy
- Matplotlib
- OS
Author: Sergio García Pajares
Last update: 04-10-2020
Copyright: GNU General Public License either version 2 of the License,
or (at your option) any later version.
[INFO] Examples supposes that analysis has been imported as ana.
'''
__all__ = ['DataPlot','Fit','funplot','fun3plot','ponderated_mean','series_ponderated_mean',
'newDirectory','autoPathRenamer','skip_value','legend','xrad','yrad','setLatex',
'mean','seriesMean']
__version__ = '3.0.4'
'''
Versions history
2.1.0
---------------------------
- ponderated_mean: added
- series_ponderated_mean: added
2.0.1
---------------------------
- linear_origin_regresion: added
2.0.0
---------------------------
- general: inclusion of dynamic lambda use in regresion funtions and
data_plot
- data_plot: linear coeficientes has been substituided by a regresion
funtion so, now plot can be used with any function. New
np parameter added.
- data_plot: no longer plots grid
- data_plot: ecolor parameter is now set 'k' by default
- linear_ponderated: debuged
- data_multi_plots: disapears
- data_sin_plot: disapears
Previous
---------------------------
Not recorded
'''
#=======================================================================
#==== IMPORTS ==========================================================
#=======================================================================
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from scipy.stats import itemfreq, t
from scipy.optimize import curve_fit
import os
#=======================================================================
#==== DATA =============================================================
#=======================================================================
MARKERS = np.array(['bo','g^','rs','ch','m<','y>',])
#Temporal style modification
matplotlib.rc('lines',markersize=3,markeredgewidth=.5)
matplotlib.rc('savefig',transparent=True)
matplotlib.rc('errorbar',capsize=2)
#matplotlib.rcParams['ecolor']='k'
#print(matplotlib.rcParams.keys())
#=======================================================================
#==== FUNCTIONS ========================================================
#=======================================================================
#####################
# --- OPERATIVE SYSTEM ---
#
def newDirectory (directory_name, cwd = None):
'''
This func is thought to create new directories considering that info
could be overwriten if we choose an existing path. For example we have
used this dic in a privious execution. It will ask the user if the path
exist. If it doesn't will create it.
This func should work either on Linux or Windows.
PARAMETERS
directory_name, str: Is the name of the new directory
cwd = None, str: Is the path in which we want to create the
new directory. If not provided, the current
directory at which we are executing the file
will be used
RETUNRS
newpath, str: Is the full path to the new directory
'''
#--- Check inputs are valid ----------------------------------------
assert isinstance(directory_name,str), "directory_name must be an string"
if cwd == None: cwd = os.getcwd()
else:
assert isinstance(cwd,str), "The working directory must be an string"
assert os.path.exists(cwd), "The working directory must exist"
#--- Create the directory ------------------------------------------
newpath = os.path.join(cwd,directory_name)
if os.path.isdir(newpath): #check if the directory we want to create
#already exists
AskAgain = True
while AskAgain: #ask user if he wants to use the same directory
answer = input("%s already exists. If you continue all \
the info in %s could be overwritten. Do you want to continue? (y/N): "
%(directory_name,directory_name))
answer = answer.upper()
if answer == 'Y':
AskAgain = False
return(newpath)
elif answer == 'N' or answer == '':
AskAgain = False
else:
print("\nSorry, I couldn't understand you")
# --- Change dir option ---
AskAgain2 = True #second question
while AskAgain2:
answer = input("Do you want to enter a new directory name? (Y/n): ").upper()
if answer == 'Y' or answer == '':
AskAgain2 = False
directory_name = input("\nPlease introduce the new directory name\n ")
newDirectory(directory_name,cwd)
elif answer == 'N':
exit(0) #end execution
else:
print("\nSorry, I couldn't understand you")
else: #Directory doesn't exist create it
os.mkdir(newpath)
return(newpath)
def autoPathRenamer(path,log=False):
'''
Adds an autonumber to the end of a file to path in case
the file already exist. In case the file has an extension
format is expected to be .aaa at the end of the filename.
PARAMETERS:
path, str: path to the file
log = False, bool: print or not in terminal info
RETURNS:
newpath, str
'''
if os.path.isfile(path):
if log: print('[WARN] file <{}> already exist'.format(path))
counter=1
if path[-4] == '.': #case there's extension
extension = path[-4:]
path = path[:-4]+str(counter)+extension
while os.path.isfile(path):
counter += 1
digits = np.ceil(np.log10(counter))
if log: print('[WARN] file <{}> already exist'.format(path))
path = path[:-(digits+4)]+str(counter)+extension
else:# case there is no extension
path = path[:-1]+str(counter)+extension
while os.path.isfile(path):
counter += 1
digits = np.ceil(np.log10(counter))
if log: print('[WARN] file <{}> already exist'.format(path))
path = path[:-digits]+str(counter)+extension
if log: print("[INFO] Path has been changed to <{}>".format(path))
return path
#####################
# --- STATISTICS ---
#
def mean(x,confidence=None):
'''
Get mean and it's error
PARAMETERS
x, 1D array-like: data
norm, bool: True indecates errors are
assumed normal and t-student pivot is
used
confidence, float (0,1): confidence level
for error estimation
Note: nan values are skipped
RETURNS
mean and it's error
_ _
(x , dx)
'''
#--- Prepare input ---
x = np.asarray(x)
N = len(x)
whereNotNaN = ~np.isnan(x)
if not whereNotNaN.any():
print("[WARN] Some nan values were ignored")
x = x[whereNotNaN]
#--- Get calc ---
mean = x.mean()
dmean = np.sqrt(((x-mean)**2).sum()/(N*(N-1)))
if confidence != None:
dmean = t.ppf((1+confidence)/2,df=N-1) * dmean
return ( mean , dmean )
def ponderated_mean (x,dx):
'''
Calculates ponderated mean
PARAMETERS:
x, 1D-array-like: x values
dx, 1D-array-like: x error values
RETURNS:
_ _
(x,dx ) tuple
_
x, number: mean
_
dx, number: error of the mean
'''
x=np.asarray(x,dtype=float)
dx=np.asarray(dx,dtype=float)
w=1/(dx**2)
sw=np.sum(w)
swx=np.sum(w*x)
return((swx/sw),(1/np.sqrt(sw)))
def series_ponderated_mean(x,y,dy):
'''
Calculates the ponderated mean of a secuence
PARAMETERS:
x, 1d-array like: x values
y, 1d-array like: y values in which ponderated mean is
going to be calculated
dy, 1d-array like: precision of the y values
RETURNS:
_ _
(x-unique , y , dy )
x-unique, 1d-array: unique values in the original data sheet
_
y, 1d-array: mean of the elements with same x value
_
dy, 1d-array: error of the mean of the same x elements
EXAMPLE
GIVEN: RETURNED:
-------------- _ _
| x y dy | X-unique y dy
|------------|
| 1 5.1 .2 | 1 5.02 11.01
| 1 4.9 .1 |
|------------| 2 0.04 0.08
| 2 10 .3 |
|------------|
| 1 5.2 .1 |
|------------|
| 2 11 .1 |
| 2 12 .2 |
| 2 8 .5 |
|------------|
| 1 5.0 .05 |
--------------
'''
x=np.asarray(x)
y=np.asarray(y)
dy=np.asarray(dy)
assert len(x.shape) == 1, "x must be a 1d array like object"
#unique flatten arrays if axis is not specified
assert len(y.shape) == 1, "y must be a 1d array like object"
assert len(dy.shape) == 1, "dy must be a 1d array like object"
assert np.size(x) == np.size (y), "x and y mus have the same number of elemnts"
assert np.size(y) == np.size(y), "y and dy must have the same number of elements"
x_values = np.unique(x) #get unique values of x
y_values = np.ones_like(x_values,dtype=float) # create an array in which store y means
dy_values = np.ones_like(x_values,dtype=float) # create an array in which store dy of means
i = 0 #initialice #it's the counter of x-values elements
for value in x_values:
indices = np.where (x == value) #get indices of x original array
y_values[i] , dy_values[i] = ponderated_mean(y[indices],dy[indices])
#calculate for chosen values
i += 1 #next x_value
return x_values , y_values , dy_values
def seriesMean(x,y,confidence=None):
'''
Calculates the mean of a secuence
PARAMETERS:
x, 1d-array like: x values
y, 1d-array like: y values in which mean is
going to be calculated
confidence = None, number 0<confidence<1:
if specified dy returns confidence t-student interval
RETURNS:
_ _
(x-unique , y , dy )
x-unique, 1d-array: unique values in the original data sheet
_
y, 1d-array: mean of the elements with same x value
_
dy, 1d-array: error of the mean of the same x elements
EXAMPLE
GIVEN: RETURNED:
-------------- _ _
| x y dy | X-unique y dy
|------------|
| 1 5.1 .2 | 1 5.02 11.01
| 1 4.9 .1 |
|------------| 2 0.04 0.08
| 2 10 .3 |
|------------|
| 1 5.2 .1 |
|------------|
| 2 11 .1 |
| 2 12 .2 |
| 2 8 .5 |
|------------|
| 1 5.0 .05 |
--------------
'''
#prepare input
x=np.asarray(x)
y=np.asarray(y)
assert len(x.shape) == 1, "x must be a 1d array like object"
#unique flatten arrays if axis is not specified
assert len(y.shape) == 1, "y must be a 1d array like object"
assert np.size(x) == np.size (y), "x and y mus have the same number of elemnts"
assert np.size(y) == np.size(y), "y and dy must have the same number of elements"
# clasify
x_values, x_values_indices = np.unique(x,return_index=True) #get unique values of x
x_values_indices = np.sort(x_values_indices)
y_values = np.empty_like(x_values,dtype=float) # create an array in which store y means
dy_values = np.empty_like(x_values,dtype=float) # create an array in which store dy of means
for i in np.arange(len(x_values)):
indices = np.where(x == x[x_values_indices[i]])
y_values[i] , dy_values[i] = mean(y[indices],confidence=confidence)
return x[x_values_indices] , y_values , dy_values
#####################
# --- REGRESION ---
#
def linear_regresion(x,y,confidence=None,**kwargs):
'''
Calculates the linear regresion.
PARAMETERS:
x, 1D-array-like: x points
y, 1D-array-like: y points
norm, bool: True indecates errors are
assumed normal and t-student pivot is
used
confidence, float (0,1): confidence level
for error estimation
RETURNS:
For y = a x + b
a, float: a coeficient
b, float: b coeficient
da, float: a error
db, float: b error
f, funtion: f(x)=ax+b
( (a,b) , (da,db) , r2 , f ) tuple
DETAILS:
For more details about it's meaning and
calculation see: Introducción al Análisis
de errores, Johon R. Taylor (Reverté 2014)
'''
#--- preparing inputs ---------------
x=np.asarray(x) #turn them into arrays
y=np.asarray(y)
#x=skip_value(x) #skip None
#y=skip_value(y)
#--- checking -----------------------
assert len(x.shape) == 1, 'x must be a vector'
assert len(y.shape) == 1, 'y must be a vector'
assert np.size(x) == np.size(y), 'x and y must have the same number of elements'
#--- calculate twice used values ----
N=np.size(x) #number of elements
sx=np.sum(x) #x sumation
sx2=np.sum(x*x) #x square sumation
sy=np.sum(y) #y sumation
sy2=np.sum(y*y) #y square sumation
sxy=np.sum(x*y) # xy sumation
delta=float(N*sx2-sx**2) #common denominator for both paramenteres
#--- getting linear coeficients -----
#ax+b
a=(N*sxy-(sx*sy))/(delta)
b=((sx2*sy)-(sx*sxy))/(delta)
#--- getting error ------------------
sigmay=np.sqrt((1./(N-2))*np.sum((y-b-a*x)**2))
r2 = ( sxy - (sx*sy/N) )**2 / ( ( sx2-(sx**2/N))*(sy2 - (sy**2/N)) ) #correlation squared coeficient
da=sigmay*np.sqrt(N/delta)
db=sigmay*np.sqrt(sx2/delta)
if confidence != None:
# In case t-student is supposed to be used
# Case normal errors are assumed instead of
# general pivot based on central limit theorem
assert 0. < confidence and confidence < 1., '0 < confidence < 1, but {} was provided'.format(confidence)
tstudent = t.ppf((1+confidence)/2,df=N-2)
da = tstudent * confidence
db = tstudent * confidence
f = lambda x: a*x+b #Define regresion func
return( np.array([a,b]) ,np.array([da,db]) ,r2, f )
def linear_ponderated_regresion(x,y,dy,**kwargs):
'''
Calculates the linear ponderated regresion.
PARAMETERS:
x, 1D-array-like: x points
y, 1D-array-like: y points
dy, 1D-array-like: y error values
RETURNS:
For y = a x + b
a, float: a coeficient
b, float: b coeficient
da, float: a error
db, float: b error
f, funtion: f(x)=ax+b
( (a,b) , (da,db) , r2 , f )
'''
#--- preparing inputs ---------------
x = np.asarray(x) #turn them into arrays
y = np.asarray(y)
dy = np.asarray(dy)
#x = skip_value(x) #skip None
#y = skip_value(y)
#dy = skip_value(dy)
#--- checking -----------------------
assert len(x.shape) == 1, 'x must be a vector'
assert len(y.shape) == 1, 'y must be a vector'
assert len(dy.shape) == 1, 'dy must be a vector'
assert np.size(x)==np.size(y), 'x and y must have the same number of elements'
assert np.size(y)==np.size(dy), 'y and dy must have the same number of elements'
#--- calculate twice used values ----
w=1/(dy**2)
sw=np.sum(w)
swx=np.sum(w*x) #x sumation
swx2=np.sum(w*x*x) #x square sumation
wy=w*y
swy=np.sum(wy) #y sumation
swxy=np.sum(w*x*y) # xy sumation
delta=float(sw*swx2-(swx)**2) #common denominator for both paramenteres
#--- getting linear coeficients -----
#ax+b
a=(sw*swxy-(swx*swy))/(delta)
b=(swx2*swy-(swx*swxy))/(delta)
#--- getting error ------------------
da=np.sqrt(sw/delta)
db=np.sqrt(swx2/delta)
r2 = None #<----------------------------------------------------------------------------------------------------
f=lambda x: a*x+b #Define regresion func
ymean = y.mean()
r2 = (w*(f(x)-ymean)**2).sum() / (w*(y-ymean)**2).sum() #REVISAR
#r2 = ((f(x)-ymean)**2).sum() / ((y-ymean)**2).sum()
return( np.array([a,b]) , np.array([da,db]), r2 , f )
def linear_origin_regresion(x,y,**kwargs):
'''
Calculates the linear regresion.
PARAMETERS:
x, 1D-array-like: x points
y, 1D-array-like: y points
RETURNS:
For y = a x
a, float: a coeficient
da, float: a error
f, funtion: f(x)=ax+b
( (a) , (da) , r , f )
'''
#--- preparing inputs ---------------
x=np.asarray(x) #turn them into arrays
y=np.asarray(y)
#x=skip_value(x) #skip None
#y=skip_value(y)
#--- checking -----------------------
assert len(x.shape)== 1, 'x must be a vector'
assert len(y.shape)== 1, 'y must be a vector'
assert np.size(x)==np.size(y), 'x and y must have the same number of elements'
#--- calculate twice used values ----
N=np.size(x) #number of elements
sx2=np.sum(x*x) #x square sumation
sxy=np.sum(x*y) # xy sumation
#--- getting linear coeficients -----
#ax+b
a=sxy/sx2
#--- getting error ------------------
sigmay=np.sqrt((1./(N-1))*np.sum((y-a*x)**2))
da=sigmay/np.sqrt(sx2)
r2 = None #<-----------------------------------------------------------------------------------------------------
f=lambda x: a*x #Define regresion func
return( np.array([a]) , np.array([da]) , r2 , f)
def quadratic_regresion(x,y,**kwargs):
'''
Calculates the quadratic regresion.
PARAMETERS:
x, 1D-array-like: x points
y, 1D-array-like: y points
RETURNS:
For y = ax^2 + bx +c
a, float: a coeficient
da, float: a error
b, float: a coeficient
db, float: a error
c, float: a coeficient
dc, float: a error
f, funtion: f(x)=ax^2+bx+c
( (a,b,c) , (da,db,dc) , r2 , f )
'''
# Prepare input
x = np.asarray(x)
y = np.asarray(y)
# Checking input
assert len(x.shape)== 1, 'x must be a vector'
assert len(y.shape)== 1, 'y must be a vector'
assert np.size(x)==np.size(y), 'x and y must have the same number of elements'
# calculate twice used values
p, V = np.polyfit(x,y,deg=2,cov=True) #V is the covariance matrix
dp = np.sqrt(np.diag(V))
#define lambda function
f = lambda x: p[2] + (p[1] + p[0]*x)*x
ymean = y.mean()
r2 = ((f(x)-ymean)**2).sum() / ((y-ymean)**2).sum()
return p , dp, r2, f
def auto_linear(x,y,dx,dy):
'''
Choose which regresion between linear and linear ponderated is
needed considering the type of dy.
If dy is an array like
PARAMETERS:
x, 1D-array-like: x points
y, 1D-array-like: y points
dx, number or array-like: x error
dy, number or array-like: y error
RETURNS:
For y = a x + b
a, float: a coeficient
b, float: b coeficient
da, float: a error
db, float: b error
f, funtion: f(x)=ax+b
( (a,b) , (da,db) , r2 , f )
'''
if len(dy)==1 or len(dy)==0: #It's a number
print("[INFO] linear regresion used")
return linear_regresion(x,y)
else: #It's an array like object
print("[INFO] linear ponderated regresion used")
return linear_ponderated_regresion(x,y,dy)
def custom_fitting (x,y,dy,func,p0=None):
'''
Automated calling of scipy.optimeze.curve_fit
'''
if dy == [] or isinstance(dy,(int,float)): dy = None #solve some implementation issue due to diference in DataPlot dy=[]
#default argument and curve_fitting sigma = None expected
p, pcov, infodict, _, _ = curve_fit(func, x, y,sigma=dy,p0=p0, full_output=True)
#pcov is the covariance matrix of the parameters
dp = np.sqrt(np.diag(pcov)) # errores estándar de los parámetros
return (p,dp,1-(infodict['fvec']**2).sum()/((y-y.mean())**2).sum(),lambda t: func(t,*p))
def noFit(**kwargs):
'''
No fitting function to allow use of ref=False in DataPlot func
'''
return ((),(),None,None)
def sinusoidal(x,y,dy,p0=None,**kwargs):
return custom_fitting(x,y,dy,lambda t, A, phi, B: A*np.sin(x + phi) + B,p0=p0)
def amortiguado_lineal(x,y,dy,p0=None,**kwargs):
return custom_fitting(x,y,dy, lambda t, A,B,w,phi,C : (A*t+B)*np.sin(w*t+phi) + C,p0=p0)
def amortiguado_exponencial(x,y,dy,p0=None,**kwargs):
return custom_fitting(x,y,dy, lambda t, A,B,w,phi,gamma : A*np.exp(-gamma*t)*np.sin(w*t+phi) + B ,p0=p0)
def fit_gauss(x,y,dy,p0=None,**kwargs):
return custom_fitting(x,y,dy, lambda x, mu,sigma2: np.exp(-.5*((x-mu)**2/sigma2)/np.sqrt(2*np.pi*sigma2)) , p0=p0)
# ======================== FITTING CLASS ============================= #
class Fit (object):
'''
This class aims to make easier fitting problems solution.
It's a wrapper around all fitting functions for easier use.
'''
regfuncs={
#This dict is used by fit class builder to calc regresion from
#the different regresion functions. Add here a regresion function
#and in fit.dict and fit.help and it will be implemented.
False : (noFit,('No fitting',[],[])),
1 : (auto_linear,('f(x)=ax+b',['a','b'] , ['da','db'])),
'auto_linear' : (auto_linear,('f(x)=ax+b, auto linear',['a','b'] , ['da','db'])),
2 : (linear_regresion, ('f(x)=ax+b',['a','b'] , ['da','db'])),
'linear' : (linear_regresion, ('f(x)=ax+b, linear',['a','b'] , ['da','db'])),
3 : (linear_ponderated_regresion,('f(x)=ax+b',['a','b'] , ['da','db'])),
'linear_ponderated': (linear_ponderated_regresion,('f(x)=ax+b, linear ponderated',['a','b'] , ['da','db'])),
4 : (linear_origin_regresion,('f(x)=ax',['a'],['da'])),
'linear_origin' : (linear_origin_regresion,('f(x)=ax',['a'],['da'])),
5 : (sinusoidal,('f(x)=Asin(x+phi)+B',['A','phi','B'],['dA','dphi','dB'])),
'sinusoidal' : (sinusoidal,('f(x)=Asin(x+phi)+B',['A','phi','B'],['dA','dphi','dB'])),
'quadratic' : (quadratic_regresion,('f(x)=ax^2+bx+c, quadratic',['a','b','c'],['da','db','dc'])),
'amortiguado_lineal':(amortiguado_lineal,('f(t) = (A·t+B)·sin(wt+phi) + C, amortiguado lineal',['A','B','w','phi','C'],['dA','dB','dw','dphi','dC'])),
'amortiguado_exponencial':(amortiguado_exponencial,('f(t) = Ae^{-gamma·t}sin(wt+phi) + B, amortiguado exponencial',['A','B','w','phi','gamma'],['dA','dB','dw','dphi','dgamma'] )),
'gauss' : (fit_gauss, ('N(mu,sigma2)',['mu','sigma2'],['dmu','dsigma2']))
}
def __init__ (self,x,y,dx=[],dy=[],reg=True,p0=None,confidence=None):
'''
PARAMETERS
x, array-like:
y, array-like:
Note: Nan, values are skiped in calc
OPTIONAL
dx, number or array-like:
dy, number or array-like:
reg: type of fitting (see below)
confidence, float (0,1): confidence level
for error estimation. If not specified t-student
is not applied.
ATTRIBUTES
p, numpy.array: array containing the fitting parameters
dp, numpy.array: array containing the estimated error on
fitting paramenters
r2, float: squared correlation coeficient R²
f, lambda.function: function f(x) representing the
fitted curve.
type: reg type provided by user
data, list [x,y,dx,dy]: original data provided by the user
dict, dictionary: This dictionary provides a user-friendly
way to acces all info stored by the user. Including
parameters in a human redable way.
KEYS:
x : x original data
dx: x error original data
y : y original data
dy: y error original data
f : fitted lambda.function
r2: squared correlation coeficient R²
Also all the keys of the parameters depending
on the type of reg. To check such parameters
see the regfuncs dictionary
REGRESION POSIBILITIES
=====================================================
| REGRESION POSIBILITIES |
|===================================================|
| KEY | TYPE |
|---+-----------------------------------------------|
| 0 | False | No regresion drawn |
|---+----------------------+------------------------|
| 1 | auto_linear | linear or linear pon- |
| | | derated depending on |
| | | dy type (number or |
| | | array like) |
|---+----------------------+------------------------|
| 2 | linear | linear |
|---+----------------------+------------------------|
| 3 | linear_ponderated | linear ponderated |
|---+----------------------+------------------------|
| 4 | linear_origin | linear crossing origin |
|---+----------------------+------------------------|
| 5 | sinusoidal | sinusoidal |
|---+----------------------+------------------------|
| | | |
+--------------------------+------------------------|
| Function f(x) specififed by the user |
=====================================================
Note: In case of user specified function format must
be f(x,params) where params are the value we want to
estimate
EXAMPLES
>>> import numpy, analysis
>>> x = [1,2,3,4]
>>> y = [2.8,3.9,6.1,7.9]
>>>
>>> dx = [.02,.15,.10,.05]
>>> dy = [.9,.15,.2,.3]
>>>
>>> myfit = analysis.Fit(x,y,dx,dy,reg='linear_ponderated')
>>>
>>> # We can acces to all parameters
>>> print(myfit.p) #show parameters
numpy.array([ 2.0101029 , -0.05116932 ])
>>> print(myfit.dp) #show error on parameters
numpy.array([ 0.14936723 , 0.39837133 ])
>>>
>>> # We can also use a friendly way of getting parameters by
>>> # naming them (names depends on reg type)
>>> print(myfit['a']," +- ",myfit['da'])
2.0101029 +- 0.14936723
>>>
>>> # We can acces all the info of the fit printting it
>>> print(myfit)
Reg type: f(x)=ax+b, linear ponderated
---------------------------------------------------
a: 2.0101028999064585 +- 0.14936723411362335
b: -0.051169317118803945 +- 0.3983713335117016
r2 = 0.9915962515987549
'''
if reg == False:
self.p , self.dp , self.r2, self.f = None, None, None, None
#--- Prepare data ---
x = np.asarray(x,dtype=float) #work with arrays
y = np.asarray(y,dtype=float)
assert np.size(x) == np.size(y), "x and y must have the same number of elements"
#--- Skip nans ---
whereNotNaN = ~(np.isnan(x) + np.isnan(y))
if not whereNotNaN.all():
print("[WARN] Some nan values were ignored")
x = x[whereNotNaN]
y = y[whereNotNaN]
if not isinstance(dy,(int,float)):
if len(dy) != 1 or len(dy)!= 0:
dy = dy[whereNotNaN]
#--- Customize instance ---
self.type = reg #reg type
self.data = [x,y,dx,dy] #original data provided
#--- Get regresion ---
if isinstance(reg,(int,str)):
self.p , self.dp , self.r2 ,self.f = self.regfuncs[reg][0](x=x,y=y,dx=dx,dy=dy,p0=p0)
else: #Case of custom function instead of reg type
self.p , self.dp , self.r2 ,self.f = custom_fitting(x,y,dy,func=reg,p0=p0)
# <- WHERE ->
# self.p: params of fitting
# self.dp: error of params of fitting
# self.r2 square of correlation coeficient
# self.f lambda func containing the fitted function
#--- Dictionary ---
self.dict = {
'x' : self.data[0],
'y' : self.data[1],
'dx' : self.data[2],
'dy' : self.data[3],
'type': self.type, #change to human readable
'r2' : self.r2,
'f' : self.f,
}
#Defining parameters and error of parameters in terms of parameters name
#stored in regfuncs dictinary
human_names = self.regfuncs.get(self.type)#returns None if key is not avaible,
# the case of user specified function
if human_names == None: #case user define function
for i in np.arange(len(self.p)):
self.dict.update(
{
'p'+str(i+1) : self.p[i],
'dp'+str(i+1): self.dp[i]
}
)
else:
human_names = human_names[1] #choose tuple of names
# params
for i in np.arange(len(human_names[1])):
self.dict.update( {human_names[1][i] : self.p[i]} )
self.dict.update( {human_names[2][i] : self.dp[i]} )
def __str__(self):
'''
Show all the information relevant about the fit, including type and
'''
try: #case not lambda
string = " Reg type: {} \n---------------------------------------------------\n".format(self.regfuncs[self.type][1][0])
except:
string = " Reg type: custom fitting\n---------------------------------------------------\n"
for i in np.arange(len(self.p)):
string = string + "{}: {} +- {}\n".format(self.regfuncs[self.type][1][1][i],self.p[i],self.dp[i])
string = string + " r2 = {}".format(self.r2)
return string
def __len__(self):
'''
Return the number of paramenters that the fit has
'''
return len(self.p)
def __getitem__(self,item):