-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstatistics.py
More file actions
1253 lines (1199 loc) · 53.7 KB
/
Copy pathstatistics.py
File metadata and controls
1253 lines (1199 loc) · 53.7 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
#!/home/msahil/anaconda3/bin/python
try:
import numpy as np
import scipy.stats as sct
import sys
import getopt
import os.path
from termcolor import colored
import copy
from difflib import get_close_matches
from tqdm import tqdm
except:
print('Required libraries not found')
print('Basic libraries required: ')
print(' numpy, scipy, sys, getopt, os, copy, termcolor, tqdm')
exit()
#=====================================================================================
#=====================================================================================
# f:input_file1, x:column in f, w:operation, c:comments, b:bootstrap value, s:starting point, e:ending point, r:operation over r values
# t:time column (default=0), o:output_file, m:values in output
# p:operation_type1 {{can be different for different subcommands}}
#
# INPUT TYPES:
# Integer inputs:
# -x |
# -t |
# -y |
# -m | integer 1 (noutput)
# -r | integer 2 (operational_value1)
# -b | integer 3 (operational_value2)
# Numeric inputs:
# -s |
# -e |
# -v | numeric 1 (value1)
# -u | numeric 2 (value2)
# String inputs:
# -p | string 1 (operation_type1)
# -q | string 2 (operation_type2)
# Others:
# -f |
# -c |
# -o |
# -a |
#=====================================================================================
#=====================================================================================
def not_string(x):
try:
values=float(x)
ans=True
except ValueError:
ans=False
return ans
#-------------------------------------------------------------------------------------
def extra_args(given,required):
extras=[]
for i in given:
if (i not in required):
extras.append(i)
if len(extras) > 0:
print('The following arguments are not required for the given commands::')
print(' ',extras)
print(' ',colored('WILL BE IGNORED','red',attrs=['underline']),'\n')
#-------------------------------------------------------------------------------------
def which_duplicates(x):
duplicates=[]
uniques=[]
if len(x) == len(set(x)):
return duplicates
else:
for i in x:
if (i not in uniques):
uniques.append(i)
else:
duplicates.append(i)
return set(duplicates)
#-------------------------------------------------------------------------------------
def zero_divide_error():
print('Cannot divide by zero..')
print(colored(' ERROR','red',attrs=['bold']))
exit()
#=====================================================================================
#========================================================================================
arguments=sys.argv[2:]
if len(arguments) == 0:
print('No input arguments')
print(colored(' ERROR','red',attrs=['bold']))
exit()
#=====================================================================================
#========================================================================================
try:
args,vals=getopt.getopt(arguments,'f:g:c:x:y:b:t:s:e:v:m:o:a:p:q:r:u:')
except getopt.error as err:
print(str(err))
print(colored(' ERROR','red',attrs=['bold']))
sys.exit(2)
comments=['@','#']
column1=1
column2=2
tc=0
noutput=1
output_status='w'
flags=[]
for arg,val in args:
flags.append(arg)
if arg == '-f':
input_file1=val
if os.path.exists(input_file1):
continue
else:
print('input_file_1 not found')
print(colored(' ERROR','red',attrs=['bold']))
exit()
elif arg == '-g':
input_file2=val
if os.path.exists(input_file2):
continue
else:
print('input_file_2 not found')
print(colored(' ERROR','red',attrs=['bold']))
exit()
elif arg == '-o':
output_file=val
elif arg == '-x':
if val.isdigit() == True :
column1=int(val)
else:
print('option -x requires integer value')
print(colored(' ERROR','red',attrs=['bold']))
exit()
elif arg == '-y':
if val.isdigit() == True :
column2=int(val)
else:
print('option -y requires integer value')
print(colored(' ERROR','red',attrs=['bold']))
exit()
elif arg == '-c':
comments=list(val)
elif arg == '-b':
if val.isdigit() == True :
def bootstrap(x):
means=[]
for i in range(int(val)):
means.append(np.nanmean(np.array([x[j] for j in np.random.randint(len(x),size=len(x))])))
return means
operational_value2=int(val)
else:
print('option -b requires integer value')
print(colored(' ERROR','red',attrs=['bold']))
exit()
elif arg == '-t':
if val.isdigit() == True :
tc=int(val)
else:
print('option -t requires integer value')
print(colored(' ERROR','red',attrs=['bold']))
exit()
elif arg == '-s':
if not_string(val) == True :
start=float(val)
else:
print('Option -s requires numeric value')
print(colored(' ERROR','red',attrs=['bold']))
exit()
elif arg == '-e':
if not_string(val) == True:
last=float(val)
else:
print('Option -e requires numeric value (default end)')
print(colored(' ERROR','red',attrs=['bold']))
exit()
elif arg == '-v':
if not_string(val) == True :
value1=float(val)
else:
print('Option -v requires numeric value')
print(colored(' ERROR','red',attrs=['bold']))
exit()
elif arg == '-u':
if not_string(val) == True :
value2=float(val)
else:
print('Option -u requires numeric value')
print(colored(' ERROR','red',attrs=['bold']))
exit()
elif arg == '-m':
if val.isdigit() == True:
noutput=int(val)
else:
print('option -m requires integer value')
print(colored(' ERROR','red',attrs=['bold']))
exit()
elif arg == '-a':
if val.upper()=='YES':
output_status='a'
elif val.upper() =='NO':
output_status='w'
else:
print('Unrecognized argument for append.')
print(colored(' -a yes/no','green',attrs=['bold']))
print(colored(' ERROR','red',attrs=['bold']))
exit()
elif arg == '-p':
operation_type1=val
elif arg == '-q':
operation_type2=val
elif arg == '-r':
if val.isdigit() == True:
operational_value1=int(val)
else:
print('option -r requires integer value')
print(colored(' ERROR','red',attrs=['bold']))
exit()
#========================================================================================
#========================================================================================
duplicates = which_duplicates(flags)
if len(duplicates) > 0:
for i in duplicates:
print('Flag provided more than once: ',i)
print(colored(' Each flag should be provided only once','green',attrs=['bold']))
print(colored(' ERROR','red',attrs=['bold']))
exit()
#========================================================================================
#========================================================================================
what=sys.argv[1]
what=what.upper()
if what[0] == '-':
print('Syntax error::')
print(colored(' Looks like no command is provided:','green',attrs=['bold']))
print(' ')
print(colored('syntax:: statistics command_name -f input_file1 -arguments input_values','cyan',attrs=['bold']))
print(' ')
print(colored(' ERROR','red',attrs=['bold']))
exit()
all_functions=['MIN','MINAT','ROW-MIN','MAX','MAXAT','ROW-MAX','VALUEAT','NEARESTVALUE','MEDIAN','MEAN','WEIGHTED-MEAN','BMEAN','STD','SEM','BSTD','ROW-MEAN','ROW-MEDIAN','NORMALIZE','CORRELATION','BINDING-TIME']
if (what not in all_functions)==True:
print('Unknown Command: ',what)
close_matches=get_close_matches(what,all_functions)
if len(close_matches) > 0:
print(colored(' Did you mean any of the following:','green',attrs=['bold']))
for i in close_matches:
print(' ',i)
print('')
print(colored(' ERROR','red',attrs=['bold']))
exit()
#========================================================================================
#========================================================================================
if ( '-f' in arguments):
pass
else:
print('No input file provided (-f option)')
print(colored(' ERROR','red',attrs=['bold']))
exit()
try:
raw_data1=np.loadtxt(input_file1,comments=comments)
except ValueError:
print('The input data file could not be read::..!')
print(colored(' Look for comment lines in file (-c option)','green',attrs=['bold']))
print(colored(' ERROR','red',attrs=['bold']))
exit()
if len(raw_data1) == 0:
print('')
print(colored(' check the input file','green',attrs=['bold']))
print('No data in the input file (-f option)')
print(colored(' ERROR','red',attrs=['bold']))
exit()
if raw_data1.ndim == 1:
data1=copy.deepcopy(raw_data1)
times1=np.array(range(1,len(data1)+1))
stacked_data1=np.column_stack((times1,data1))
#--------------------------------------------------------------------------
elif raw_data1.ndim == 2:
if ('-s' in arguments):
start_index=(np.abs(raw_data1[:,tc]-start)).argmin()
else:
start_index=0
if ('-e' in arguments):
end_index=(np.abs(raw_data1[:,tc]-last)).argmin() + 1
else:
end_index=len(raw_data1)
raw_data1=raw_data1[start_index:end_index]
try:
tried=len(raw_data1[1])
except:
print('No data remains in input-file1 after shortlisting')
print(colored(' check your -s / -e options','green',attrs=['bold']))
print(colored(' ERROR','red',attrs=['bold']))
exit()
#----------------------------------------------------------------------
times1=raw_data1[:,tc]
rest_data1=np.delete(raw_data1,tc,axis=1)
if len(raw_data1[1]) < column1+1 :
print('Column-index1 out of range')
print(colored(' ERROR','red',attrs=['bold']))
exit()
else:
data1=raw_data1[:,column1]
stacked_data1=np.column_stack((times1,data1))
else:
print('Unreadable data')
print(' ',colored('This programs works for time series data, i.e., either 1D or 2D','green',attrs=['bold']))
if np.isnan(np.sum(raw_data1)) == True:
print('Undefined Values in the input-data1')
print(colored(' Check the input_file1 for NaN values','green',attrs=['bold']))
print(colored(' This program ignore NaN values','green',attrs=['bold']))
print(colored(' CAN BE A POSSIBLE ERROR','red',attrs=['blink']))
#========================================================================================
#========================================================================================
if ('-g' in arguments):
try:
raw_data2=np.loadtxt(input_file2,comments=comments)
except:
print('The input-file2 could not be read::..!')
print(colored(' Look for comment lines in file (-c option)','green',attrs=['bold']))
print(colored(' ERROR','red',attrs=['bold']))
exit()
if len(raw_data2) == 0:
print('')
print(colored(' check the input-file2','green',attrs=['bold']))
print('No data in the input-file2 (-g option)')
print(colored(' ERROR','red',attrs=['bold']))
exit()
if raw_data2.ndim == 1:
data2=copy.deepcopy(raw_data2)
times2=np.array(range(1,len(data2)+1))
stacked_data2=np.column_stack((times2,data2))
elif raw_data2.ndim == 2:
if ('-s' in arguments):
start_index=(np.abs(raw_data2[:,tc]-start)).argmin()
else:
start_index=0
if ('-e' in arguments):
end_index=(np.abs(raw_data2[:,tc]-last)).argmin() + 1
else:
end_index=len(raw_data2)
raw_data2=raw_data2[start_index:end_index]
try:
tried=len(raw_data2[1])
except:
print('No data remains in input-file2 after shortlisting')
print(colored(' check your -s / -e options','green',attrs=['bold']))
print(colored(' ERROR','red',attrs=['bold']))
exit()
#----------------------------------------------------------------------
times2=raw_data2[:,tc]
rest_data2=np.delete(raw_data2,tc,axis=1)
if len(raw_data2[1]) < column2+1 :
print('Column-index2 out of range')
print(colored(' Use -y column-number','green',attrs=['bold']))
print(colored(' ERROR','red',attrs=['bold']))
exit()
else:
data2=raw_data2[:,column2]
stacked_data2=np.column_stack((times2,data2))
else:
print('Unreadable data')
print(' ',colored('This programs works for time series data, i.e., either 1D or 2D','green',attrs=['bold']))
if np.isnan(np.sum(raw_data2)) == True:
print('Undefined Values in the input-data2')
print(colored(' Check the input_file2 for NaN values','green',attrs=['bold']))
print(colored(' This program ignore NaN values','green',attrs=['bold']))
print(' ',colored('CAN BE A POSSIBLE ERROR','red',attrs=['blink']))
if len(raw_data1) != len(raw_data2):
print(colored('NOTE: ','cyan',attrs=['bold']),'input-data1 and input-data2 have different lengths of data')
print(' ',colored('CAN BE A POSSIBLE ERROR','red',attrs=['blink']))
#========================================================================================
#========================================================================================
if ('-o' in arguments): #opening output file in provided status
if os.path.exists(output_file):
if ('-a' not in arguments) == True :
rename_number=0
while True:
rename_number=rename_number+1
new_name='#'+output_file+'.'+str(rename_number)+'#'
if os.path.exists(new_name):
pass
else:
os.rename(output_file,new_name)
break
print('output_file exist:: Renamed to ',new_name)
print(colored(' Use append (-a option) to append/overwrite','green',attrs=['bold']))
outputfile=open(output_file,output_status)
#========================================================================================
#========================================================================================
#Overall, the following datas are available to operate on:
# data1
# times1
# rest_data1 | not for 1d data
# stacked_data1
# raw_data1
# Same for data2
#========================================================================================
#========================================================================================
#========================================================================================
if what == 'MIN':
all_flags=['-f','-x','-c','-t','-s','-e','-y']
extra_args(flags,all_flags)
print(what,': ',np.nanmin(data1))
#========================================================================================
#---------------------------------------------------------------------------------------
#========================================================================================
elif what == 'MINAT':
all_flags=['-f','-x','-c','-t','-s','-e','-y']
extra_args(flags,all_flags)
if raw_data1.ndim < 2:
print('MINAT operation requires 2-D data')
print(colored(' ERROR','red',attrs=['bold']))
exit()
else:
print('MIN ',np.nanmin(data1),' AT ',times1[np.where(data1 == np.nanmin(data1))])
#========================================================================================
#---------------------------------------------------------------------------------------
#========================================================================================
elif what == 'ROW-MIN':
all_flags=['-f','-x','-c','-t','-s','-e','-y','-o','-a']
extra_args(flags,all_flags)
if ('-o' in arguments):
outfile=output_file
else:
outfile='sahil.out'
print('No output file is provided. Output in file: ',outfile)
print(colored(' Use -o outfile','green',attrs=['bold']))
if raw_data1.ndim == 1:
print('The input data has only one column.')
print(colored(' ERROR','red',attrs=['bold']))
exit()
elif raw_data1.ndim == 2:
if len(raw_data1[1]) == 2:
out=[]
for i in range(len(raw_data1)):
out.append(np.nanmin(raw_data1[i]))
with open(outfile,'a') as f:
print('#The input data has only two columns... Using both of them.\n')
np.savetxt(f,out,fmt='%1.4f')
elif len(raw_data1[1]) > 2:
if ('-p' in arguments):
if operation_type1.upper() == 'ALL-COLS':
print('Using all rows:')
data_to_use=raw_data1
elif operation_type1.upper() == 'EXCEPT-REF-COL':
data_to_use=rest_data1
outs='stacked'
print('Using all except ref column')
else:
print('Invalid argument for -p')
print(colored(' -p all-cols / except-ref-col','green',attrs=['bold']))
exit()
else:
data_to_use=rest_data1
outs='stacked'
out=[]
for i in range(len(data_to_use)):
out.append(np.nanmin(data_to_use[i]))
if outs == 'stacked':
out=np.column_stack((times1,out))
with open(outfile,'a') as f:
np.savetxt(f,out,fmt='%1.4f')
#========================================================================================
#---------------------------------------------------------------------------------------
#========================================================================================
elif what == 'MAX':
all_flags=['-f','-x','-c','-t','-s','-e','-y']
extra_args(flags,all_flags)
print(what,': ',np.nanmax(data1))
#========================================================================================
#---------------------------------------------------------------------------------------
#========================================================================================
elif what == 'MAXAT':
all_flags=['-f','-x','-c','-t','-s','-e','-y']
extra_args(flags,all_flags)
if raw_data1.ndim < 2:
print('MAXAT operation requires 2-D data')
print(colored(' ERROR','red',attrs=['bold']))
exit()
else:
print('MAX ',np.nanmax(data1),' AT ',times1[np.where(data1 == np.nanmax(data1))])
#========================================================================================
#---------------------------------------------------------------------------------------
#========================================================================================
elif what == 'ROW-MAX':
if ('-o' in arguments):
outfile=output_file
else:
outfile='sahil.out'
print('No output file is provided. Output in file: ',outfile)
print(colored(' Use -o outfile','green',attrs=['bold']))
if raw_data1.ndim == 1:
print('The input data has only one column.')
print(colored(' ERROR','red',attrs=['bold']))
exit()
elif raw_data1.ndim == 2:
if len(raw_data1[1]) == 2:
out=[]
for i in range(len(raw_data1)):
out.append(np.nanmax(raw_data1[i]))
with open(outfile,'a') as f:
print('#The input data has only two columns... Using both of them.\n')
np.savetxt(f,out,fmt='%1.4f')
elif len(raw_data1[1]) > 2:
if ('-p' in arguments):
if operation_type1.upper() == 'ALL-COLS':
print('Using all rows:')
data_to_use=raw_data1
elif operation_type1.upper() == 'EXCEPT-REF-COL':
data_to_use=rest_data1
outs='stacked'
print('Using all except ref column')
else:
print('Invalid argument for -p')
print(colored(' -p all-cols / except-ref-col','green',attrs=['bold']))
exit()
else:
data_to_use=rest_data1
outs='stacked'
out=[]
for i in range(len(data_to_use)):
out.append(np.nanmax(data_to_use[i]))
if outs == 'stacked':
out=np.column_stack((times1,out))
with open(outfile,'a') as f:
np.savetxt(f,out,fmt='%1.4f')
#========================================================================================
#---------------------------------------------------------------------------------------
#========================================================================================
elif what == 'VALUEAT':
all_flags=['-f','-x','-c','-t','-s','-e','-y','-v']
extra_args(flags,all_flags)
if raw_data1.ndim < 2:
print('VALUEAT operation requires 2-D data')
print(colored(' ERROR','red',attrs=['bold']))
exit()
else:
if ( '-v' not in arguments) == True:
print('Argument value not provided (-v option)')
print(colored(' ERROR','red',attrs=['bold']))
exit()
else:
pos=np.where(data1 == value1)
if np.shape(pos)[1] == 0:
print('No matching results with the given value: ',value1)
print(colored(' Look for nearestvalue...!! ','green',attrs=['bold']))
else:
print('Value ',value1,' AT ',times1[pos])
#========================================================================================
#---------------------------------------------------------------------------------------
#========================================================================================
elif what == 'NEARESTVALUE':
all_flags=['-f','-x','-c','-t','-s','-e','-y','-v','-m']
extra_args(flags,all_flags)
if ( '-v' not in arguments) == True:
print('Argument value1 not provided (-v option)')
print(colored(' ERROR','red',attrs=['bold']))
exit()
elif noutput > len(data1):
print('Required number of outputs are more than data')
print(colored(' ERROR','red',attrs=['bold']))
exit()
else:
if raw_data1.ndim == 1:
data_to_use=copy.deepcopy(data1)
vvs=[]
for i in range(noutput):
ind=(np.abs(data_to_use - value1)).argmin()
vvs.append(data_to_use[ind])
data_to_use=np.delete(data_to_use,ind)
print(vvs)
elif raw_data1.ndim == 2:
data_to_use=np.column_stack((times1,data1))
vvs=[]
for i in range(noutput):
ind=(np.abs(data_to_use[:,1] - value1)).argmin()
vvs.append(list(data_to_use[ind]))
data_to_use=np.delete(data_to_use,ind,axis=0)
print(vvs)
else:
print('The program is for 2-D time series only')
print(colored(' ERROR','red',attrs=['bold']))
exit()
#========================================================================================
#---------------------------------------------------------------------------------------
#========================================================================================
elif what == 'MEDIAN':
if ('-p' not in arguments) == True :
print(what,': ',np.nanmedian(data1))
else:
if operation_type1.upper() == 'CUMULATIVE':
def cumulative_median(x):
av=[]
av.append(x[0])
for i in range(1,len(x)):
av.append(np.nanmedian(x[:i+1]))
return av
out=cumulative_median(data1)
tout=times1
final_out=np.column_stack((tout,out))
cline='#REF-COLUMN CUMULATIVE-MEDIAN \n'
else:
if ('-r' not in arguments) == True:
print('Operational value not provided')
print(colored(' Use -r option','green',attrs=['bold']))
exit()
else:
if operational_value1 > len(data1):
print('Operational value is greater than total length of input_data1')
print(' ',colored('CAN BE A SOURCE OF ERROR','red',attrs=['underline']))
if (operation_type1.upper() in ['RUNNING','ROLLING']):
def running_median(x,r):
av=[]
for i in range(0,len(x)-r+1):
av.append(np.nanmedian(x[i:i+r-1]))
return av
out=running_median(data1,operational_value1)
tout=times1[operational_value1-1:]
final_out=np.column_stack((tout,out))
cline='#REF-COLUMN RUNNING-MEDIAN \n'
elif operation_type1.upper() == 'BLOCK':
def block_median(x,r,times1):
i=0
j=r-1
av=[]
tav=[]
while j < len(x):
av.append(np.nanmedian(x[i:j]))
tav.append([times1[i],times1[j]])
i=i+r
j=j+r
if j-r < len(x):
av.append(np.nanmedian(x[i:]))
tav.append([times1[i],times1[-1]])
return tav, av
tout,out=block_average(data1,operational_value1,times1)
final_out=np.column_stack((tout,out))
cline='#FROM TO BLOCK-MEDIAN \n'
else:
print('Invalid Operation type (-p option)')
print(colored(' Use -p cumulative/running|rolling/block','green',attrs=['bold']))
print(colored(' ERROR','red',attrs=['bold']))
exit()
if ('-o' in arguments):
outfile=output_file
else:
outfile='sahil.out'
print('No output file is provided. Output in file: ',outfile)
print(colored(' Use -o outfile','green',attrs=['bold']))
with open(outfile,'a') as f:
f.write(cline)
np.savetxt(f,final_out,fmt='%1.4f')
#========================================================================================
#---------------------------------------------------------------------------------------
#========================================================================================
elif what == 'MEAN':
if ('-p' not in arguments) == True :
print(what,': ',np.nanmean(data1))
else:
if operation_type1.upper() == 'CUMULATIVE':
def cumulative_average(x):
av=[]
av.append(x[0])
for i in range(1,len(x)):
av.append(np.nanmean(x[:i+1]))
return av
out=cumulative_average(data1)
tout=times1
final_out=np.column_stack((tout,out))
cline='#REF-COLUMN CUMULATIVE-MEAN \n'
elif operation_type1.upper() == 'REVERSE-CUMULATIVE':
def cumulative_average(x):
av=[]
av.append(x[0])
for i in range(1,len(x)):
av.append(np.nanmean(x[:i+1]))
return av
out=cumulative_average(np.flip(data1))
tout=np.flip(times1)
final_out=np.column_stack((tout,out))
cline='#REF-COLUMN CUMULATIVE-MEAN \n'
else:
if ('-r' not in arguments) == True:
print('Operational value not provided')
print(colored(' Use -r option','green',attrs=['bold']))
exit()
else:
if operational_value1 > len(data1):
print('Operational value is greater than total length of input_data1')
print(' ',colored('CAN BE A SOURCE OF ERROR','red',attrs=['underline']))
if (operation_type1.upper() in ['RUNNING','ROLLING']):
def running_average(x,r):
av=[]
for i in tqdm(range(0,len(x)-r+1),desc='RUNNING'):
av.append(np.nanmean(x[i:i+r-1]))
return av
out=running_average(data1,operational_value1)
tout=times1[operational_value1-1:]
final_out=np.column_stack((tout,out))
cline='#REF-COLUMN RUNNING-AVERAGE \n'
elif operation_type1.upper() == 'BLOCK':
def block_average(x,r,times1):
i=0
j=r-1
av=[]
tav=[]
while j < len(x):
av.append(np.nanmean(x[i:j]))
tav.append([times1[i],times1[j]])
i=i+r
j=j+r
if j-r+1 < len(x):
av.append(np.nanmean(x[i:]))
tav.append([times1[i],times1[-1]])
return tav, av
tout,out=block_average(data1,operational_value1,times1)
final_out=np.column_stack((tout,out))
cline='#FROM TO BLOCK-AVERAGE \n'
elif operation_type1.upper() == 'WEIGHTED':
print('Invalid Operation type (-p option)')
print(colored(' Looking for weighted-average:: Use weighted-mean','green',attrs=['bold']))
print(colored(' ERROR','red',attrs=['bold']))
exit()
elif operation_type1.upper() == 'BOOTSTRAP':
print('Invalid Operation type (-p option)')
print(colored(' Looking for mean by bootstrapping:: Use bmean','green',attrs=['bold']))
print(colored(' ERROR','red',attrs=['bold']))
exit()
else:
print('Invalid Operation type (-p option)')
print(colored(' Use -p cumulative/running|rolling/block','green',attrs=['bold']))
print(colored(' ERROR','red',attrs=['bold']))
exit()
if ('-o' in arguments):
outfile=output_file
else:
outfile='sahil.out'
print('No output file is provided. Output in file: ',outfile)
print(colored(' Use -o outfile','green',attrs=['bold']))
with open(outfile,'a') as f:
f.write(cline)
np.savetxt(f,final_out,fmt='%1.4f')
#========================================================================================
#---------------------------------------------------------------------------------------
#========================================================================================
elif what == 'WEIGHTED-MEAN':
if ('-g' in arguments):
weights=data2
else:
try:
weights=raw_data1[:,column2]
except:
print('Weights couldnot be read from input-file1')
print(colored(' Use -y to define weights column','green',attrs=['bold']))
print(colored(' ERROR','red',attrs=['bold']))
exit()
if len(data1) != len(weights) :
print('input-data1 and weights data are of different length')
print(colored(' ERROR','red',attrs=['bold']))
exit()
if ('-q' in arguments):
operation_type2=operation_type2.upper()
if operation_type2 == 'MEAN-DIVIDE':
if np.nanmean(weights) != 0:
weights=weights/np.nanmean(weights)
else:
print('Mean of weights is zero. Cannot divide by zero')
print(colored(' ERROR','red',attrs=['bold']))
exit()
elif operation_type2 == 'MEAN-SUBTRACT':
weights=weights - np.nanmean(weights)
elif operation_type2 == 'MEDIAN-DIVIDE':
if np.nanmedian(weights) != 0:
weights=weights/np.nanmedian(weights)
else:
print('Median of weights is zero. Cannot divide by zero')
print(colored(' ERROR','red',attrs=['bold']))
exit()
elif operation_type2 == 'MEDIAN-SUBTRACT':
weights=weights - np.nanmedian(weights)
elif operation_type2 == 'MIN-DIVIDE':
if np.nanmin(weights) != 0:
weights=weights/np.nanmin(weights)
else:
print('Min of weights is zero. Cannot divide by zero')
print(colored(' ERROR','red',attrs=['bold']))
exit()
elif operation_type2 == 'MIN-SUBTRACT':
weights=weights - np.nanmin(weights)
elif operation_type2 == 'MAX-DIVIDE':
if np.nanmax(weights) != 0:
weights=weights/np.nanmax(weights)
else:
print('Max of weights is zero. Cannot divide by zero')
print(colored(' ERROR','red',attrs=['bold']))
exit()
elif operation_type2 == 'MAX-SUBTRACT':
weights=weights - np.nanmax(weights)
elif operation_type2 == 'SUM-DIVIDE':
if np.nansum(weights) != 0:
weights=weights/np.nansum(weights)
else:
print('SUM of weights is zero. Cannot divide by zero')
print(colored(' ERROR','red',attrs=['bold']))
exit()
elif operation_type2 == 'SUM-SUBTRACT':
weights=weights - np.nansum(weights)
elif operation_type2 == 'FACTOR-DIVIDE':
if ('-v' not in arguments)==True:
print('Input factor not given (-v option)')
print(colored(' ERROR','red',attrs=['bold']))
exit()
else:
if value1 != 0:
weights=weights/value1
else:
zero_divide_error()
elif operation_type2 == 'FACTOR-SUBTRACT':
if ('-v' not in arguments)==True:
print('Input factor not given (-v option)')
print(colored(' ERROR','red',attrs=['bold']))
exit()
else:
weights=weights - value1
else:
print('Operation-type2 not recognized')
print(colored(' ERROR','red',attrs=['bold']))
exit()
weighted_data=data1*weights
total_weights=np.nansum(weights)
if ('-p' not in arguments)==True:
if total_weights == 0:
print('Total weights equal zero.. Cannot divide by zero')
print(colored(' ERROR','red',attrs=['bold']))
exit()
print(what,': ',np.nansum(weighted_data)/total_weights)
else:
operation_type1=operation_type1.upper()
if operation_type1 == 'BOOTSTRAP':
if ('-b' not in arguments)==True:
print('Bootstrap Value not provided (-b option)')
print(colored(' ERROR','red',attrs=['bold']))
exit()
else:
def weighted_bootstrap(wx,w,btv):
means=[]
for i in range(btv):
random_array=np.random.randint(len(wx),size=len(wx))
random_data=np.array([wx[j] for j in random_array])
random_weights=np.array([w[j] for j in random_array])
if np.nansum(random_weights) == 0:
print('Weights has zero values: Cannot divide by zero')
print(colored(' ERROR','red',attrs=['bold']))
exit()
means.append(np.nansum(random_data)/np.nansum(random_weights))
return means
print('WEIGHTED-BOOTSTRAPED-MEAN: ',np.nanmean(weighted_bootstrap(weighted_data,weights,operational_value2)))
else:
if operation_type1 == 'CUMULATIVE':
def weighted_cumulative(wx,w):
av=[]
av.append(wx[0])
for i in range(1,len(wx)):
if np.nansum(w[:i+1]) == 0:
print('Weights has zero values: Cannot divide by zero')
print(colored(' ERROR','red',attrs=['bold']))
exit()
av.append(np.nansum(wx[:i+1])/np.nansum(w[:i+1]))
return av
out=weighted_cumulative(weighted_data,weights)
tout=times1
final_out=np.column_stack((tout,out))
cline='#REF-COLUMN WEIGHTED-CUMULATIVE-MEAN \n'
elif (operation_type1 not in ['CUMULATIVE','RUNNING','ROLLIN','BLOCK'])==True:
print('Operation-type1 not recognized (-p option)')
print(colored(' Use -p bootstrap/cumulative/running/rolling/block','green',attrs=['bold']))
print(colored(' ERROR','red',attrs=['bold']))
exit()
else:
if ('-r' not in arguments)==True:
print('Operational-value not provided')
print(colored(' Use -r option','green',attrs=['bold']))
exit()
else:
if operational_value1 > len(weighted_data):
print('Operational-value is greater than total length of input-data1')
print(' ',colored('CAN BE A SOURCE OF ERROR','red',attrs=['underline']))
if (operation_type1 in ['RUNNING','ROLLING']):
def weighted_running(wx,w,r):
av=[]
for i in range(0,len(wx)-r+1):
if np.nansum(w[i:i+r-1]) == 0 :
print('Weights has zero values: Cannot divide by Zero')
print(colored(' ERROR','red',attrs=['bold']))
exit()
av.append(np.nansum(wx[i:i+r-1])/np.nansum(w[i:i+r-1]))
return av
out=weighted_running(weighted_data,weights,operational_value1)
tout=times1[operational_value1-1:]
final_out=np.column_stack((tout,out))
cline='#REF-COLUMN WEIGHTED-RUNNING-MEAN \n'
elif operation_type1 == 'BLOCK':
def weighted_block(wx,w,r):
i=0
j=r-1
av=[]
tav=[]
while j < len(wx):
if np.nansum(w[i:j]) == 0:
print('Weights has zero values: Cannot divide by Zero')
print(colored(' ERROR','red',attrs=['bold']))
exit()
av.append(np.nansum(wx[i:j])/np.nansum(w[i:j]))
tav.append([times1[i],times1[j]])
i=i+r
j=j+r
if j-r+1 < len(wx):
if np.nansum(w[i:j]) == 0:
print('Weights has zero values: Cannot divide by Zero')
print(colored(' ERROR','red',attrs=['bold']))
exit()
av.append(np.nansum(wx[i:])/np.nansum(w[i:]))
tav.append([times1[i],times1[-1]])
return tav, av
tout,out=weighted_block(weighted_data,weights,operational_value1)
final_out=np.column_stack((tout,out))
cline='#FROM TO WEIGHTED-BLOCK-MEAN \n'
if ('-o' in arguments):
outfile=output_file
else:
outfile='sahil.out'
print('No output file is provided. Output in file: ',outfile)
print(colored(' Use -o outfile','green',attrs=['bold']))
with open(outfile,'a') as f:
f.write(cline)
np.savetxt(f,final_out,fmt='%1.4f')
#========================================================================================
#---------------------------------------------------------------------------------------
#========================================================================================
elif what == 'BMEAN':
proceed=0
for i in arguments:
if i == '-b':
proceed=1
break
if proceed == 0:
print('Bootstrap Value not provided (-b option)')
print(colored(' ERROR','red',attrs=['bold']))
exit()
print(what,': ',np.nanmean(bootstrap(data1)))
#========================================================================================
#---------------------------------------------------------------------------------------
#========================================================================================
elif what == 'STD':
print(what,': ',np.nanstd(data1))
#========================================================================================
#---------------------------------------------------------------------------------------
#========================================================================================
elif what == 'SEM':
print(what,': ',np.nanstd(data1)/(np.sqrt(np.size(data1)-1)))