-
Notifications
You must be signed in to change notification settings - Fork 0
/
fit_ionline.py
825 lines (646 loc) · 29.1 KB
/
fit_ionline.py
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
import os
# mpi does paralelization, both multithread matrix operations
# just one per process to avoid cache trashing.
os.system("export OMP_NUM_THREADS=1")
os.environ["OMP_NUM_THREADS"] = "1"
import h5py
import numpy as n
import matplotlib.pyplot as plt
import scipy.constants as c
import isr_spec.il_interp as il
import scipy.interpolate as si
import scipy.optimize as so
import traceback
import glob
import stuffr
# power meter reading
import tx_power as txp
import os
#import optuna
from mpi4py import MPI
comm=MPI.COMM_WORLD
size=comm.Get_size()
rank=comm.Get_rank()
ilf=il.ilint(fname="isr_spec/ion_line_interpolate.h5")
ilf_ho=il.ilint(fname="isr_spec/ion_line_interpolate_h_o.h5")
def molecular_ion_fraction(h, h0=120, H=20):
"""
Ion-fraction for a Chapman-type exponential scale height behaviour
h0 = transition height
H = width of the transition
"""
return(n.tanh( n.exp(-(h-h0)/H) ))
def mh_molecular_ion_fraction(h):
"""
John Holt's molecular ion fraction function.
"""
zz1=-(h-120.0)/40.0
zz1[zz1>50.0]=50.0
H=10.0 - 6.0*n.exp(zz1)
zz2=-(h-180)/H
zz2[zz2>50]=50
fr=1-2.0/(1+n.sqrt(1+8.0*n.exp(zz2)))
fr[h<120]=1.0
return(fr)
def model_acf(te,ti,heavy_ion_frac,vi,lags,hplus=False):
"""
heavy_ion_frac is the fraction of the heavier ion
(O_2+/N_2+ with O+ or O+ with H+)
"""
dop_shift=2*n.pi*2*440.2e6*vi/c.c
csin=n.exp(1j*dop_shift*lags)
if hplus == False:
model=ilf.getspec(ne=n.array([1e11]),
te=n.array([te]),
ti=n.array([ti]),
mol_frac=n.array([heavy_ion_frac]),
vi=n.array([0.0]),
acf=True
)[0,:]
acff=si.interp1d(ilf.lag,model)
return(acff(lags)*csin)
else:
model=ilf_ho.getspec(ne=n.array([1e11]),
te=n.array([te]),
ti=n.array([ti]),
mol_frac=n.array([heavy_ion_frac]),
vi=n.array([0.0]),
acf=True
)[0,:]
acff=si.interp1d(ilf_ho.lag,model)
return(acff(lags)*csin)
def model_gaussian(dw,v,lags):
dop_shift=2*n.pi*2*440.2e6*v/c.c
csin=n.exp(1j*dop_shift*lags)
model = csin*n.exp(- (2*n.pi*2*440.2e6/c.c)*dw*lags)
return(model)
def fit_gaussian(acf,lags,var,var_scale=4.0,guess=n.array([0,10]),plot=False):
"""
Fit a gaussian to judge if there is a space object
"""
var=n.real(var)
# 2x for ground clutter 2x for correlated lags
std=n.sqrt(var_scale*var)/n.abs(acf[0].real)
# normalize all range gates to unity
scaling_const=acf[0].real
nacf=acf/scaling_const
def ss(x):
dop_width=x[0]
v=x[1]
zl=x[2]
model=zl*model_gaussian(dop_width,v,lags)
ssq=n.nansum(n.abs(model-nacf)**2.0/std**2.0)
return(ssq)
def ss_optuna(trial):
dop_width=trial.suggest_float("dop_width",10,5e3)
v=trial.suggest_float("velocity",-3e3,3e3)
zl=trial.suggest_float("zl",0.8,1.5)
model=zl*model_gaussian(dop_width,v,lags)
ssq=n.nansum(n.abs(model-nacf)**2.0/std**2.0)
# print(ssq)
return(ssq)
guess=[100,50,1.0]
xhat=so.minimize(ss,guess,method="Nelder-Mead",bounds=((10,5e3),(-3e3,3e3),(0.8,1.5))).x
# optuna.logging.set_verbosity(optuna.logging.ERROR)
# opt=optuna.create_study()
# opt.optimize(ss,n_trials=50 )
# optres=opt.best_params
# xhat=[optres["dop_width"],optres["velocity"],optres["zl"]]
# print(xhat)
# lags for ploting the analytic model, also include real zero-lag
dx=0.1
midx=n.where(n.isnan(acf)!=True)[0]
n_m=len(midx)
J=n.zeros([2*n_m,3])
model=xhat[2]*model_gaussian(xhat[0],xhat[1],lags[midx])
model_dx0=xhat[2]*model_gaussian(xhat[0]+dx,xhat[1],lags[midx])
model_dx1=xhat[2]*model_gaussian(xhat[0],xhat[1]+dx,lags[midx])
model_dx2=(xhat[2]+dx)*model_gaussian(xhat[0],xhat[1],lags[midx])
J[0:n_m,0]=n.real((model-model_dx0)/dx)
J[0:n_m,1]=n.real((model-model_dx1)/dx)
J[0:n_m,2]=n.real((model-model_dx2)/dx)
J[n_m:(2*n_m),0]=n.imag((model-model_dx0)/dx)
J[n_m:(2*n_m),1]=n.imag((model-model_dx1)/dx)
J[n_m:(2*n_m),2]=n.imag((model-model_dx2)/dx)
S=n.zeros([2*n_m,2*n_m])
for mi in range(n_m):
S[mi,mi]=1/std[midx[mi]]**2.0
S[2*mi,2*mi]=1/std[midx[mi]]**2.0
Sigma=n.linalg.inv(n.dot(n.dot(n.transpose(J),S),J))
sigmas=n.sqrt(n.real(n.diag(Sigma)))
#mlags=n.linspace(0,480e-6,num=100)
if plot:
#print(xhat)
model=xhat[2]*model_gaussian(xhat[0],xhat[1],lags)
plt.plot(lags*1e6,model.real)
plt.plot(lags*1e6,model.imag)
plt.errorbar(lags*1e6,nacf.real,yerr=2*std)
plt.errorbar(lags*1e6,nacf.imag,yerr=2*std)
plt.xlabel("Lag ($\mu$s)")
plt.ylabel("Autocorrelation function R($\\tau)$")
plt.title("Gaussian fit\ndoppler width %1.0f $\pm$ %1.0f m/s vel %1.0f $\pm$ %1.0f m/s"%(xhat[0],sigmas[0],xhat[1],sigmas[1]))
plt.show()
return(xhat,sigmas)
def fit_acf(acf,
lags,
rgs,
var,
var_scale=2.0,
guess=n.array([n.nan,n.nan,n.nan,n.nan]),
plot=False,
use_optuna=False,
scaling_constant=1e4):
if n.isnan(guess[0]):
guess[0]=1.1
if n.isnan(guess[1]):
guess[1]=500
if n.isnan(guess[2]):
guess[2]=100
# print(acf)
# print(n.sqrt(var))
var=n.real(var)
# 2x for ground clutter 3x for correlated lags
std=n.sqrt(var_scale*var)#/n.abs(acf[0].real)
#print(std)
# estimate zero-lag
zl_guess=1.1*n.abs(acf[0].real)
# override zero-lag guess
guess[3]=1.1*zl_guess
mol_fr=mh_molecular_ion_fraction(n.array([rgs]))[0]
xhat=n.zeros(4)
if use_optuna:
def ss_optuna(trial):
te_ti=trial.suggest_float("te_ti",1,3)
ti=trial.suggest_float("ti",150,3000)
vi=trial.suggest_float("vi",-1500,1500)
zl=trial.suggest_float("zl",0.3*zl_guess,3*zl_guess)
model=zl*model_acf(te_ti*ti,ti,mol_fr,vi,lags)
ssq=n.nansum(n.abs(model-acf)**2.0/std**2.0)
return(ssq)
optuna.logging.set_verbosity(optuna.logging.ERROR)
opt=optuna.create_study()
opt.optimize(ss_optuna,n_trials=100 )
optres=opt.best_params
xhat=n.array([optres["te_ti"],optres["ti"],optres["vi"],optres["zl"]])
# print("optuna found")
# print(xhat)
else:
def ss(x):
te_ti=x[0]
ti=x[1]
vi=x[2]
zl=x[3]
model=zl*model_acf(te_ti*ti,ti,mol_fr,vi,lags)
ssq=n.nansum(n.abs(model-acf)**2.0/std**2.0)
return(ssq)
xhat=so.minimize(ss,guess,method="Nelder-Mead",bounds=((0.99,3),(150,3000),(-1500,1500),(0.3*zl_guess,3*zl_guess))).x
sb=ss(xhat)
bx=xhat
guess[2]=-1*guess[2]
xhat=so.minimize(ss,guess,method="Nelder-Mead",bounds=((0.99,3),(150,3000),(-1500,1500),(0.3*zl_guess,3*zl_guess))).x
st=ss(xhat)
if st<sb:
bx=xhat
xhat=so.minimize(ss,[1.1,500,100,1.05*zl_guess],method="Nelder-Mead",bounds=((0.99,3),(150,3000),(-1500,1500),(0.3*zl_guess,3*zl_guess))).x
st=ss(xhat)
if st<sb:
bx=xhat
xhat=bx
# print("fmin found")
# print(xhat)
dx0=0.05*xhat[0]
dx1=0.05*xhat[1]
dx2=0.05*n.abs(xhat[2])
dx3=0.05*xhat[3]
midx=n.where(n.isnan(acf)!=True)[0]
n_m=len(midx)
J=n.zeros([2*n_m,4])
model=xhat[3]*model_acf(xhat[0]*xhat[1],xhat[1],mol_fr,xhat[2],lags[midx])
# is residuals are worse than twice the standard deviation of errors,
# make the error std estimate worse, as there is probably something
# unexplained the the measurement that is making things worse than we think
# this tends to happen on the top-side in the presence of rfi
sigma_resid=n.sqrt(n.mean(n.abs(model-acf[midx])**2.0))
std[sigma_resid>2*std]=sigma_resid
model_dx0=xhat[3]*model_acf((xhat[0]+dx0)*xhat[1],xhat[1],mol_fr,xhat[2],lags[midx])
model_dx1=xhat[3]*model_acf(xhat[0]*(xhat[1]+dx1),(xhat[1]+dx1),mol_fr,xhat[2],lags[midx])
model_dx2=xhat[3]*model_acf(xhat[0]*xhat[1],xhat[1],mol_fr,(xhat[2]+dx2),lags[midx])
model_dx3=(xhat[3]+dx3)*model_acf(xhat[0]*xhat[1],xhat[1],mol_fr,xhat[2],lags[midx])
J[0:n_m,0]=n.real((model_dx0-model)/dx0)
J[0:n_m,1]=n.real((model_dx1-model)/dx1)
J[0:n_m,2]=n.real((model_dx2-model)/dx2)
J[0:n_m,3]=n.real((model_dx3-model)/dx3)
J[n_m:(2*n_m),0]=n.imag((model_dx0-model)/dx0)
J[n_m:(2*n_m),1]=n.imag((model_dx1-model)/dx1)
J[n_m:(2*n_m),2]=n.imag((model_dx2-model)/dx2)
J[n_m:(2*n_m),3]=n.imag((model_dx2-model)/dx3)
S=n.zeros([2*n_m,2*n_m])
for mi in range(n_m):
S[mi,mi]=1/std[midx[mi]]**2.0
S[2*mi,2*mi]=1/std[midx[mi]]**2.0
Sigma=n.linalg.inv(n.dot(n.dot(n.transpose(J),S),J))
sigmas=n.sqrt(n.real(n.diag(Sigma)))
# lags for ploting the analytic model, also include real zero-lag
mlags=n.linspace(0,480e-6,num=100)
model=xhat[3]*model_acf(xhat[0]*xhat[1],xhat[1],mol_fr,xhat[2],lags)
model2=xhat[3]*model_acf(xhat[0]*xhat[1],xhat[1],mol_fr,xhat[2],mlags)
if plot:
print(bx)
plt.plot(mlags*1e6,model2.real)
plt.plot(mlags*1e6,model2.imag)
plt.errorbar(lags*1e6,acf.real,yerr=2*std)
plt.errorbar(lags*1e6,acf.imag,yerr=2*std)
plt.ylim([-1.0*zl_guess,2*zl_guess])
plt.xlabel("Lag ($\mu$s)")
plt.ylabel("Autocorrelation function R($\\tau)$")
plt.title("%1.0f km\nT$_e$=%1.0f K T$_i$=%1.0f K v$_i$=%1.0f$\pm$%1.0f (m/s) $\\rho=$%1.1f"%(rgs,xhat[0]*xhat[1],xhat[1],xhat[2],sigmas[2],mol_fr))
plt.show()
return(xhat,model,sigmas)
def fit_acf_ts(acf,
lags,
rgs,
var,
var_scale=2.0,
guess=n.array([n.nan,n.nan,n.nan,n.nan,n.nan]), # te/ti, ti, vi, zl, heavy_ion_frac
plot=False,
scaling_constant=1e4):
"""
topside
"""
if n.isnan(guess[0]):
guess[0]=1.5
if n.isnan(guess[1]):
guess[1]=1200
if n.isnan(guess[2]):
guess[2]=42.0
# if n.isnan(guess[4]):
# guess[4]=1.0 # 100% O+
var=n.real(var)
std=n.sqrt(var_scale*var)
# estimate zero-lag
zl_guess=n.abs(acf[0].real)
# override zero-lag guess
guess[3]=1.1*zl_guess
def ss(x):
te_ti=x[0]
ti=x[1]
vi=x[2]
zl=x[3]
ofrac=1-1/x[4]
model=zl*model_acf(te_ti*ti,ti,ofrac,vi,lags,hplus=True)
ssq=n.nansum(n.abs(model-acf)**2.0/std**2.0)
# print(ssq)
# print(x)
# print(zl_guess)
return(ssq)
guess2=n.zeros(5)
guess2[0:4]=guess
guess2[4]=1e3
xhat=so.minimize(ss,guess2,method="Nelder-Mead",bounds=((0.99,3),(150,3000),(-1500,1500),(0.1*zl_guess,5*zl_guess),(2,10000))).x
sb=ss(xhat)
bx=xhat
guess[2]=-1*guess[2]
xhat=so.minimize(ss,guess2,method="Nelder-Mead",bounds=((0.99,3),(150,3000),(-1500,1500),(0.1*zl_guess,5*zl_guess),(2,10000))).x
st=ss(xhat)
if st<sb:
bx=xhat
xhat=so.minimize(ss,[1.1,1500,13,1.05*zl_guess,800],method="Nelder-Mead",bounds=((0.99,3),(150,3000),(-1500,1500),(0.1*zl_guess,5*zl_guess),(2,10000))).x
st=ss(xhat)
if st<sb:
bx=xhat
xhat=bx
dx0=0.05*xhat[0]
dx1=0.05*xhat[1]
dx2=0.05*n.abs(xhat[2])
dx3=0.05*xhat[3]
midx=n.where(n.isnan(acf)!=True)[0]
n_m=len(midx)
J=n.zeros([2*n_m,4])
ofrac=xhat[4]
model=xhat[3]*model_acf(xhat[0]*xhat[1],xhat[1],ofrac,xhat[2],lags[midx],hplus=True)
# is residuals are worse than twice the standard deviation of errors,
# make the error std estimate worse, as there is probably something
# unexplained the the measurement that is making things worse than we think
# this tends to happen on the top-side in the presence of rfi
sigma_resid=n.sqrt(n.mean(n.abs(model-acf[midx])**2.0))
std[sigma_resid>2*std]=sigma_resid
model_dx0=xhat[3]*model_acf((xhat[0]+dx0)*xhat[1],xhat[1],ofrac,xhat[2],lags[midx],hplus=True)
model_dx1=xhat[3]*model_acf(xhat[0]*(xhat[1]+dx1),(xhat[1]+dx1),ofrac,xhat[2],lags[midx],hplus=True)
model_dx2=xhat[3]*model_acf(xhat[0]*xhat[1],xhat[1],ofrac,(xhat[2]+dx2),lags[midx],hplus=True)
model_dx3=(xhat[3]+dx3)*model_acf(xhat[0]*xhat[1],xhat[1],ofrac,xhat[2],lags[midx],hplus=True)
J[0:n_m,0]=n.real((model_dx0-model)/dx0)
J[0:n_m,1]=n.real((model_dx1-model)/dx1)
J[0:n_m,2]=n.real((model_dx2-model)/dx2)
J[0:n_m,3]=n.real((model_dx3-model)/dx3)
J[n_m:(2*n_m),0]=n.imag((model_dx0-model)/dx0)
J[n_m:(2*n_m),1]=n.imag((model_dx1-model)/dx1)
J[n_m:(2*n_m),2]=n.imag((model_dx2-model)/dx2)
J[n_m:(2*n_m),3]=n.imag((model_dx2-model)/dx3)
S=n.zeros([2*n_m,2*n_m])
for mi in range(n_m):
S[mi,mi]=1/std[midx[mi]]**2.0
S[2*mi,2*mi]=1/std[midx[mi]]**2.0
Sigma=n.linalg.inv(n.dot(n.dot(n.transpose(J),S),J))
sigmas=n.sqrt(n.real(n.diag(Sigma)))
# lags for ploting the analytic model, also include real zero-lag
mlags=n.linspace(0,480e-6,num=100)
model=xhat[3]*model_acf(xhat[0]*xhat[1],xhat[1],ofrac,xhat[2],lags,hplus=True)
model2=xhat[3]*model_acf(xhat[0]*xhat[1],xhat[1],ofrac,xhat[2],mlags,hplus=True)
if plot:
print(bx)
plt.plot(mlags*1e6,model2.real)
plt.plot(mlags*1e6,model2.imag)
plt.errorbar(lags*1e6,acf.real,yerr=2*std)
plt.errorbar(lags*1e6,acf.imag,yerr=2*std)
plt.ylim([-1.0*zl_guess,2*zl_guess])
plt.xlabel("Lag ($\mu$s)")
plt.ylabel("Autocorrelation function R($\\tau)$")
plt.title("%1.0f km\nT$_e$=%1.0f K T$_i$=%1.0f K v$_i$=%1.0f$\pm$%1.0f (m/s) $\\rho=$%1.1f"%(rgs,xhat[0]*xhat[1],xhat[1],xhat[2],sigmas[2],ofrac))
plt.show()
return(xhat[0:4],model,sigmas)
# the scaling constant ensures matrix algebra can be done without problems with numerical accuracy
def fit_lpifiles(dirn="lpi_f",
output_dir="e",
n_avg=120,acf_key="acfs_e",plot=False,
scaling_constant=1e5,
reanalyze=False,
zpm=None,
gc_cancel_all_ranges=False,
minimum_tx_pwr=400e3,
range_limits=n.array([0,300,700,1500]), # range averaging boundaries in km
range_avg=n.array([0, 1, 2]), # range averaging window in range gates symmetric windows are used (ri-window):(ri+window) with range**2.0 weighting
first_lag=0):
if zpm == None:
def zpm(t):
return(1.2e6)
os.system("mkdir -p %s"%(output_dir))
fl=glob.glob("%s/lpi*.h5"%(dirn))
fl.sort()
h=h5py.File(fl[0],"r")
acf=n.copy(h[acf_key][()])
lag=n.copy(h["lags"][()])
rgs=n.copy(h["rgs_km"][()])
h.close()
n_ints=int(n.floor(len(fl)/n_avg))
# first_lag=1
# above this, don't use ground clutter removal
# use removal below this
rg_clutter_rem_cutoff=n.where(rgs>300)[0][0]
n_rg=len(rgs)
n_l=len(lag)
acf[:,:]=0.0
ws=n.copy(acf)
for fi in range(rank,n_ints,size):
acf[:,:]=0.0
ws[:,:]=0.0
t0=n.nan
t1=n.nan
tsys=0.0
acfs=n.zeros([n_avg,n_rg,n_l],dtype=n.complex64)
wgts=n.zeros([n_avg,n_rg,n_l],dtype=n.float64)
space_object_times=[]
space_object_rgs=[]
space_object_count=n.zeros(n_rg,dtype=int)
for ai in range(n_avg):
h=h5py.File(fl[fi*n_avg+ai],"r")
ampgain=h["alpha"][()]
a=h["acfs_e"][()]/ampgain
if gc_cancel_all_ranges:
# factor of 2 due to summing two echoes together.
# the factor of 2 is verified by performing a magic constant estimation on two independent fits:
# one with ground clutter cancel on all heights, and one with no ground clutter cancellation on any height
a=h["acfs_g"][()]/ampgain/2.0
else:
# only populate lower altitude bins
a[0:rg_clutter_rem_cutoff,:]=h["acfs_g"][()][0:rg_clutter_rem_cutoff,:]/ampgain/2.0
# ground clutter removed and scaled
# in amplitude to correct for the pulse to pulse subtraction
# the factor 2 might not be correct, as the acf of ionospheric plasma is affected by clutter subtraction
# probably best to have a separate calibration constant for ground clutter subtracted data
#a[0:rg_clutter_rem_cutoff,:]=a_g[0:rg_clutter_rem_cutoff,:]
v=h["acfs_var"][()]/ampgain**2.0
tsys+=h["T_sys"][()]
debris=n.zeros(n_rg,dtype=bool)
debris[:]=False
# fit gaussian model to determine if there are space objects at some range gates
if False:
plt.pcolormesh(lag,rgs,a.real)
plt.colorbar()
plt.show()
ao=n.copy(a)
vo=n.copy(v)
for ri in range(acf.shape[0]):
if n.sum(n.isnan(a[ri,:]))/len(lag) < 0.5 and rgs[ri] > 250.0:
#print(rgs[ri])
gres,gsigma=fit_gaussian(ao[ri,:],lag,n.real(n.abs(vo[ri,:])),plot=False)
if gres[0]<300.0 and gsigma[0]<100:
print("debris at %1.0f km dopp width %1.0f+/-%1.0f (m/s)"%(rgs[ri],gres[0],gsigma[0]))
# make neighbouring range gates contaminated
# store time and range so that a warning label can be attached
# to the data regarding potentially corrupted data near the region
space_object_times.append(h["i0"][()])
space_object_rgs.append(rgs[ri])
for rg_inc in range(-2,2):
if (rg_inc+ri >= 0) and (rg_inc+ri < n_rg):
debris[ri+rg_inc]=True
a[ri+rg_inc,:]=n.nan
v[ri+rg_inc,:]=n.nan
space_object_count[ri+rg_inc]+=1
acfs[ai,:,:]=a/v
wgts[ai,:,:]=1/v
# ws+=1/v
if n.isnan(t0):
t0=h["i0"][()]
print("Starting new integration period %s"%(stuffr.unix2datestr(t0)))
t1=h["i0"][()]
h.close()
if os.path.exists("%s/pp-%d.h5"%(output_dir,t0)) and reanalyze==False:
print("Already exists. Skipping")
continue
tsys=tsys/n_avg
var=1/n.nansum(wgts,axis=0)
acf=n.nansum(acfs,axis=0)/n.nansum(wgts,axis=0)
if True:
# optionally range average autocorrelation functions, after throwing away space objects.
# range_limits=[0,200,300,500,700,1500]
# range_avg= [0, 1, 2, 3, 6]
range_limit_idx=[]
for rai,ra in enumerate(range_limits):
range_limit_idx.append(n.argmin(n.abs(rgs-ra)))
acf_orig=n.copy(acf)
var_orig=n.copy(var)
range_weight=n.copy(acf)
range_weight[:,:]=0.0
for ri in range(len(rgs)):
range_weight[ri,:]=rgs[ri]**2.0
for rai,ra in enumerate(range_avg):
avg_acf=n.copy(acf_orig)
avg_var=n.copy(var_orig)
if ra > 0:
for ri in range(acf.shape[0]):
avg_acf[ri,:]=n.nansum(range_weight[n.max((0,(ri-ra))):n.min((acf.shape[0],(ri+ra))),:]*acf_orig[n.max((0,(ri-ra))):n.min((acf.shape[0],(ri+ra))),:],axis=0)/n.nansum(range_weight[n.max((0,(ri-ra))):n.min((acf.shape[0],(ri+ra))),:],axis=0)
avg_var[ri,:]=1/(n.nansum(1/var_orig[(ri-ra):n.min((acf.shape[0],(ri+ra))),:],axis=0))
acf[range_limit_idx[rai]:range_limit_idx[rai+1],:]=avg_acf[range_limit_idx[rai]:range_limit_idx[rai+1],:]
var[range_limit_idx[rai]:range_limit_idx[rai+1],:]=avg_var[range_limit_idx[rai]:range_limit_idx[rai+1],:]
acf0=n.copy(acf)
for ri in range(acf0.shape[0]):
acf0[ri,:]=acf0[ri,:]/acf0[ri,first_lag].real
if plot:
plt.pcolormesh(acf0.real,vmin=-0.1,vmax=1.1)
plt.colorbar()
plt.show()
# var=1/ws
pp=[]
dpp=[]
model_acfs=n.copy(acf0)
model_acfs[:,:]=n.nan
n_lags=acf.shape[1]
guess=n.array([n.nan,n.nan,n.nan,n.nan])
print("tx power %1.2f MW"%(zpm(0.5*(t0+t1))/1e6))
for ri in range(acf.shape[0]):
try:
if (n.sum(n.isnan(acf[ri,first_lag:n_lags]))/(n_lags-first_lag) < 0.8):
if rgs[ri]>700:
res,model_acf,dres=fit_acf_ts(acf[ri,first_lag:n_lags],lag[first_lag:n_lags],rgs[ri],var[ri,first_lag:n_lags],guess=guess,plot=plot ,scaling_constant=scaling_constant)
else:
res,model_acf,dres=fit_acf(acf[ri,first_lag:n_lags],lag[first_lag:n_lags],rgs[ri],var[ri,first_lag:n_lags],guess=guess,plot=plot ,scaling_constant=scaling_constant)
model_acfs[ri,first_lag:n_lags]=model_acf/model_acf[0].real
guess=res
# print(dres)
else:
res=n.array([n.nan,n.nan,n.nan,n.nan])
dres=n.array([n.nan,n.nan,n.nan,n.nan])
# ne raw
res_out=n.copy(res)
dres_out=n.copy(dres)
# get electron density from echo power (acf zero lag)
# acf(0)=(1/magic const)*ne*Ptx/(1+te/ti)
# ne = magic_const*acf(0)*(1+te/ti)*r**2.0/Ptx
# res[3] is zero-lag power (arb scale)
ne_const=(1+res[0])*rgs[ri]**2.0/zpm(0.5*(t0+t1))
res_out[3]=res[3]*ne_const
dres_out[3]=dres_out[3]*ne_const
pp.append(res_out)
dpp.append(dres_out)
except:
pp.append([n.nan,n.nan,n.nan,n.nan])
dpp.append([n.nan,n.nan,n.nan,n.nan])
traceback.print_exc()
nan_frac=n.sum(n.isnan(acf[ri,first_lag:n_lags]))/(n_lags-first_lag)
print(acf[ri,first_lag:n_lags])
print("error caught at range %1.0f km (nanfrac=%1.0f). marching onwards."%(rgs[ri],nan_frac))
plt.subplot(121)
plt.pcolormesh(lag[first_lag:n_lags]*1e6,rgs,model_acfs[:,first_lag:n_lags].real,vmin=-0.2,vmax=1.1)
plt.title("Best fit")
plt.xlabel("Lag ($\mu$s)")
plt.ylabel("Range (km)")
plt.colorbar()
plt.subplot(122)
plt.pcolormesh(lag[first_lag:n_lags]*1e6,rgs,acf0[:,first_lag:n_lags].real,vmin=-0.2,vmax=1.1)
plt.title("Measurement")
plt.xlabel("Lag ($\mu$s)")
plt.ylabel("Range (km)")
plt.colorbar()
plt.tight_layout()
plt.savefig("%s/pp_fit_%d.png"%(output_dir,t0))
plt.close()
plt.clf()
pp=n.array(pp)
dpp=n.array(dpp)
plt.plot(pp[:,0]*pp[:,1],rgs,".",label="Te")
plt.plot(pp[:,1],rgs,".",label="Ti")
plt.plot(pp[:,2]*10,rgs,".",label="vi*10")
plt.plot(n.log10(pp[:,3]),rgs,".",label="ne raw")
plt.xlim([-1000,5000])
plt.legend()
plt.tight_layout()
plt.savefig("%s/pp-%d.png"%(output_dir,t0))
plt.close()
plt.clf()
ho=h5py.File("%s/pp-%d.h5"%(output_dir,t0),"w")
ho["Te"]=pp[:,0]*pp[:,1]
ho["Ti"]=pp[:,1]
ho["vi"]=pp[:,2]
ho["ne"]=pp[:,3]
ho["dTe/Ti"]=dpp[:,0] # tbd fix this
ho["dTi"]=dpp[:,1]
ho["dvi"]=dpp[:,2]
ho["dne"]=dpp[:,3] # tbd fix this
ho["rgs"]=rgs
ho["t0"]=t0
ho["t1"]=t1
ho["range_avg_limits_km"]=range_limits
ho["range_avg_window_km"]=(rgs[1]-rgs[0])*(2*range_avg+1)
ho["T_sys"]=tsys
ho["P_tx"]=zpm(0.5*(t0+t1))
ho["space_object_count"]=space_object_count
ho["space_object_times"]=space_object_times
ho["space_object_rgs"]=space_object_rgs
ho.close()
if __name__ == "__main__":
import sys
# cmd line
# fit_lpifiles(dirn=sys.argv[1],n_avg=24,plot=bool(int(sys.argv[2])),first_lag=1,reanalyze=True, range_avg=4)
if False:
dirname="/media/j/fee7388b-a51d-4e10-86e3-5cabb0e1bc13/isr/2023-09-05/usrp-rx0-r_20230905T214448_20230906T040054/"
zpm,mpm=txp.get_tx_power_model(dirn="%s/metadata/powermeter"%(dirname))
fit_lpifiles(dirn="%s/lpi_240"%(dirname),output_dir="%s/ts"%(dirname),n_avg=12,plot=0,first_lag=0,reanalyze=True, zpm=zpm, use_gc=True)
exit(0)
if True:
dirname="/media/j/fee7388b-a51d-4e10-86e3-5cabb0e1bc13/isr/2023-09-28/usrp-rx0-r_20230928T211929_20230929T040533"
zpm,mpm=txp.get_tx_power_model(dirn="%s/metadata/powermeter"%(dirname))
fit_lpifiles(dirn="%s/lpi_240"%(dirname),output_dir="%s/lpi_240"%(dirname),n_avg=12,plot=0,first_lag=1,reanalyze=True, zpm=zpm, range_avg=n.array([0,2,2]))
fit_lpifiles(dirn="%s/lpi_120"%(dirname),output_dir="%s/lpi_120"%(dirname),n_avg=12,plot=0,first_lag=1,reanalyze=True, zpm=zpm, range_avg=n.array([0,2,2]))
# range_limits=n.array([0,300,700,1500]), # range averaging boundaries in km
# range_avg=n.array([0, 1, 2]), # range averaging window in range gates symmetric windows a
fit_lpifiles(dirn="%s/lpi_60"%(dirname),output_dir="%s/lpi_60"%(dirname),n_avg=12,plot=0,first_lag=1,reanalyze=True, zpm=zpm, range_avg=n.array([1,2,2]))
fit_lpifiles(dirn="%s/lpi_30"%(dirname),output_dir="%s/lpi_30"%(dirname),n_avg=12,plot=0,first_lag=1,reanalyze=True, zpm=zpm, range_avg=n.array([1,2,2]))
exit(0)
if False:
dirname="/media/j/fee7388b-a51d-4e10-86e3-5cabb0e1bc13/isr/2023-09-24/usrp-rx0-r_20230924T200050_20230925T041059"
zpm,mpm=txp.get_tx_power_model(dirn="%s/metadata/powermeter"%(dirname))
fit_lpifiles(dirn="%s/lpi_240"%(dirname),output_dir="%s/lpi_240"%(dirname),n_avg=12,plot=0,first_lag=0,reanalyze=True, zpm=zpm)
exit(0)
# fit_lpifiles(dirn="lpi_2023-09-24_30",output_dir="lpi_2023-09-24_30/e",n_avg=12,plot=0,first_lag=0,reanalyze=True, zpm=zpm, range_avg=3)
#fit_lpifiles(dirn="lpi_2023-09-24_60",output_dir="lpi_2023-09-24_60/e",n_avg=6,plot=0,first_lag=0,reanalyze=True, zpm=zpm, range_avg=0)
#fit_lpifiles(dirn="lpi_2023-09-24_30",output_dir="lpi_2023-09-24_30/e",n_avg=6,plot=0,first_lag=0,reanalyze=True, zpm=zpm, range_avg=1)
if False:
zpm,mpm=txp.get_tx_power_model(dirn="/media/j/fee7388b-a51d-4e10-86e3-5cabb0e1bc13/isr/2023-09-05/usrp-rx0-r_20230905T214448_20230906T040054/metadata/powermeter")
# e-region analysis
#fit_lpifiles(dirn="lpi_30",output_dir="lpi_30/e0",n_avg=6,plot=0,first_lag=1,reanalyze=True, range_avg=0)
fit_lpifiles(dirn="lpi_30",output_dir="lpi_30/e3",n_avg=6,plot=0,first_lag=1,reanalyze=True, range_avg=1)
# try out getting topside using different methods
# topside 30
#fit_lpifiles(dirn="lpi_30",n_avg=24,plot=0,first_lag=1,reanalyze=True, range_avg=16)
# topside 60
#fit_lpifiles(dirn="lpi_60",n_avg=24,plot=0,first_lag=1,reanalyze=True, range_avg=8)
# topside 120
#fit_lpifiles(dirn="lpi_120",n_avg=24,plot=0,first_lag=1,reanalyze=True, range_avg=4)
# topside 240
# fit_lpifiles(dirn="lpi_240",n_avg=24,plot=0,first_lag=1,reanalyze=True, range_avg=2)
# fit_lpifiles(dirn="lpi_f2",n_avg=12,plot=False,first_lag=1)
# fit_lpifiles(dirn="lpi_e",n_avg=12,plot=False,first_lag=1,reanalyze=True)
# fit_lpifiles(dirn="lpi_ts",n_avg=1,plot=False)
# fit_lpifiles(dirn="lpi_e",n_avg=60)
# h=h5py.File("avg.h5","r")
# acf=h["acf"][()]
# var=n.real(h["var"][()])
# lag=h["lag"][()]
# rgs=h["rgs"][()]
# pp=[]
# for ri in range(acf.shape[0]):
# try:
# res=fit_acf(acf[ri,:],lag,rgs,var[ri,:])
# pp.append(res)
# except:
# pp.append([n.nan,n.nan,n.nan,n.nan])
# traceback.print_exc()
# print("err")
# pp=n.array(pp)
# plt.plot(pp[:,0]*pp[:,1],rgs,".",label="Te")
# plt.plot(pp[:,1],rgs,".",label="Ti")
# plt.plot(pp[:,2]*10,rgs,".",label="vi*10")
# plt.plot(pp[:,3]*100,rgs,".",label="zl*100")
# plt.legend()
# plt.show()
# h.close()