Skip to content

Commit 017e682

Browse files
authored
Add files via upload
1 parent b719f8e commit 017e682

File tree

1 file changed

+56
-58
lines changed

1 file changed

+56
-58
lines changed

captoolkit/fitsec.py

Lines changed: 56 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -355,42 +355,42 @@ def resample(x, y, xi, w=None, dx=1/12., window=3/12, weights=False, median=Fals
355355
# Window of data centered on time index
356356
idx = (x >= (xi[i] - 0.5*window)) & \
357357
(x <= (xi[i] + 0.5*window))
358-
358+
359359
# Get weights and data
360360
ybv = y[idx]
361361
wbv = w[idx]
362-
362+
363363
# Skip if no data
364364
if len(ybv) == 0: continue
365-
365+
366366
# Check use for median or mean (weighted)
367367
if median is not True:
368-
368+
369369
# Compute initial stats
370370
m0 = np.median(ybv)
371371
s0 = 1.4826 * np.median(np.abs(ybv - m0))
372372

373373
# Index of outliers using 3.5 robust sigma rule
374374
ind = np.abs(ybv - m0) > 3.5 * s0
375-
375+
376376
# Check for issues
377377
if len(ybv[~ind]) == 0: continue
378-
378+
379379
# Weighted (spatially) or raw average
380380
if weights:
381381
ybi = np.sum(wbv[~ind] * ybv[~ind]) / np.sum(wbv[~ind])
382382
ebi = np.sum(wbv[~ind] * (ybv[~ind] - ybi)**2) / np.sum(wbv[~ind])
383-
383+
384384
else:
385385
ybi = np.mean(ybv[~ind])
386386
ebi = np.std(ybv[~ind])
387-
387+
388388
else:
389-
389+
390390
# Median and error for all points
391391
ybi = np.median(ybv)
392392
ebi = np.std(ybv)
393-
393+
394394
# Save values and error
395395
xb[i] = xi[i]
396396
yb[i] = ybi
@@ -431,25 +431,25 @@ def resample(x, y, xi, w=None, dx=1/12., window=3/12, weights=False, median=Fals
431431

432432
# Start of main function
433433
def main(file,cdr, n=''):
434-
434+
435435
# Ignore warnings
436436
import warnings
437437
warnings.filterwarnings("ignore")
438-
438+
439439
# Check if we have processed it
440440
f_check = file.replace('.h5','_SEC.h5')
441-
441+
442442
# Don't read our output
443443
if "SEC" in file: return
444-
444+
445445
# Check if file exists
446446
if os.path.exists(f_check) is True:
447447
print("File processed:", file)
448448
return
449-
449+
450450
# Global to local inside function
451451
dx, dy = dx_, dy_
452-
452+
453453
print('loading data ...')
454454

455455
# Get variable names
@@ -466,7 +466,7 @@ def main(file,cdr, n=''):
466466
lew = f[wlvar][:] if wlvar in f else np.zeros(lon.shape)
467467
tes = f[wtvar][:] if wtvar in f else np.zeros(lon.shape)
468468
bias = f[bvar][:] if bvar in f else np.zeros(lon.shape)
469-
469+
470470
# Check for NaN's in waveform parmeters
471471
if len(bsc[np.isnan(bsc)]) > 0:
472472
print("You have Nan's in BSC parameter that you plan on using - you need fill or remove them.")
@@ -476,7 +476,7 @@ def main(file,cdr, n=''):
476476
sys.exit()
477477
if len(tes[np.isnan(tes)]) > 0:
478478
print("You have Nan's in TES parameter that you plan on using - you need fill or remove them.")
479-
479+
480480
# Converte data to wanted projection
481481
x, y = transform_coord('4326', proj, lon, lat)
482482

@@ -516,7 +516,7 @@ def main(file,cdr, n=''):
516516

517517
# Flatten grid coordinates 2d -> 1d
518518
xi, yi = Xi.ravel(), Yi.ravel()
519-
519+
520520
# Convert centroid location to latitude and longitude
521521
lonc, latc = transform_coord(proj, '4326', xi, yi)
522522

@@ -539,7 +539,7 @@ def main(file,cdr, n=''):
539539
# Time vector
540540
tbin = np.arange(tmin, tmax, tstep) + 0.5 * tstep
541541
#tbin = make_time(tmin,tmax)
542-
542+
543543
# Prediction loop
544544
for i in range(len(xi)):
545545

@@ -584,94 +584,94 @@ def main(file,cdr, n=''):
584584

585585
# Variance of provided error
586586
sv = sc ** 2
587-
587+
588588
# Apply distance weighting
589589
if weight:
590-
590+
591591
# Multiply to meters
592592
cdr = cdr*1e3
593-
593+
594594
# Weights using distance and error
595595
wc = 1. / (sv * (1. + (dr / cdr) ** 2))
596596
wbool = True
597-
597+
598598
else:
599-
599+
600600
# Set weighets
601601
wc = np.ones(dr.shape)
602602
wbool = False
603-
603+
604604
# Set correct model for each solution
605605
Ac = model_order(order.copy(), dt, bc, pxy=[dx,dy], wf=[bs,lw,ts])
606-
606+
607607
try:
608608
# Solve system and invert for model parameters
609609
xhat, ehat = lstsq(Ac.copy(), zc.copy(),
610610
n_iter=niter, n_sigma=nsig,
611611
ylim=rlim, cov=True)[0:2]
612-
612+
613613
except:
614614
print("Can't solve least-squares system ...")
615615
continue
616-
616+
617617
# Check if rate is within bounds or nan
618618
if np.abs(xhat[1]) > dhlim or np.isnan(xhat[1]): continue
619619

620620
# Residuals to model
621621
dz = zc - np.dot(Ac, xhat)
622-
622+
623623
# Filter residuals - robust MAD
624624
ibad = np.abs(dz) > nsig * mad_std(dz)
625-
625+
626626
# Remove bad data from solution
627627
dz[ibad] = np.nan
628-
628+
629629
# RMS error of residuals
630630
rms = np.nanstd(dz)
631631

632632
# Time columns in design matrix
633633
cols = [1,2,3,4]
634-
634+
635635
# Set residual offset to zero
636636
res_offset = np.nan
637-
637+
638638
# Check and add offsets to residuals
639639
if order[-1] > 1:
640640
try:
641641
# Get overlapping window for missions
642642
tmin_, tmax_ = tc[bc == 1].min(), tc[bc == 0].max()
643-
643+
644644
# Get overlapping data points
645645
dz0 = dz[bc == 0][(tc[bc == 0] > tmin_) & (tc[bc == 0] < tmax_)]
646646
dz1 = dz[bc == 1][(tc[bc == 1] > tmin_) & (tc[bc == 1] < tmax_)]
647-
647+
648648
# Check that we have enough points for overlap
649649
if len(dz0) > zlim and len(dz1) > zlim:
650-
650+
651651
# Compute median values over both overlapping parts of data
652652
b0 = np.nanmedian(dz0)
653653
b1 = np.nanmedian(dz1)
654-
654+
655655
else:
656656
# Dont use
657657
b0 = np.nan
658658
b1 = np.nan
659-
659+
660660
# Compute offset
661661
res_offset = b1 - b0
662-
662+
663663
# Check if any sub offset is NaN
664664
if ~np.isnan(res_offset):
665-
665+
666666
# Apply offset to index=1
667667
dz[bc == 1] -= res_offset
668-
668+
669669
except:
670670
pass
671-
671+
672672
# Recover temporal trends
673673
hc = dz + np.dot(Ac[:,cols], xhat[cols])
674-
674+
675675
# Initialze them
676676
s_amp = np.nan
677677
s_phs = np.nan
@@ -689,19 +689,19 @@ def main(file,cdr, n=''):
689689

690690
# Maks sure phase is from 0-365 days
691691
if s_phs < 0: s_phs += 365
692-
692+
693693
# Identify NaN values in array
694694
inan = ~np.isnan(hc)
695-
695+
696696
# Bin data to wanted resolution
697697
tb, zb, eb = resample(tc[inan].copy(), hc[inan].copy(), xi=tbin,\
698698
w=wc[inan].copy(), dx=tstep, window=tres,
699699
weights=weight, median=False)
700700

701-
# Convert relocated position to geographical coords.
702-
if nrel > 0:
703-
lonc[i], latc[i] = transform_coord(proj,'4326', x_i, y_i)
704-
701+
# Convert relocated position to geographical coords.
702+
if nrel > 0:
703+
lonc[i], latc[i] = transform_coord(proj,'4326', x_i, y_i)
704+
705705
# Output data
706706
f0[i,0] = lonc[i]
707707
f0[i,1] = latc[i]
@@ -718,12 +718,12 @@ def main(file,cdr, n=''):
718718
f0[i,12] = np.min(dr)
719719
f0[i,13] = t_span
720720
f0[i,14] = xhat[-1] if order[-1] > 0 else np.nan
721-
721+
722722
# Stack time series
723723
geo.append([lonc[i], latc[i]])
724724
sec.append(zb)
725725
err.append(eb)
726-
726+
727727
# Print progress (every n-th iterations)
728728
if (i % 1) == 0:
729729
print('cell#', str(i) + "/" + str(len(xi)), \
@@ -739,7 +739,7 @@ def main(file,cdr, n=''):
739739
geo = np.vstack(geo)
740740
except:
741741
return
742-
742+
743743
# Name of output variables
744744
vars = ['lon', 'lat', 'p0', 'p1', 'p2', 'p0_error',
745745
'p1_error', 'p2_error','amplitude','phase',
@@ -754,10 +754,10 @@ def main(file,cdr, n=''):
754754
# Output file names - strings
755755
path, ext = os.path.splitext(outfile)
756756
ofile0 = path + '_SEC.h5'
757-
757+
758758
# Find NaNs in height vector
759759
inan = np.isnan(f0[:,2])
760-
760+
761761
# Remove all NaNs from data sets
762762
f0 = f0[~inan,:]
763763

@@ -767,7 +767,7 @@ def main(file,cdr, n=''):
767767
# Save model solutions
768768
for v, g in zip(vars, f0.T):
769769
foo[v] = g
770-
770+
771771
# Save binned time series
772772
foo['lon(t)'] = geo[:,0]
773773
foo['lat(t)'] = geo[:,1]
@@ -791,5 +791,3 @@ def main(file,cdr, n=''):
791791
with parallel_backend("loky", inner_max_num_threads=1):
792792
Parallel(n_jobs=njobs, verbose=5)(delayed(main)(f,cdr, n) \
793793
for n, f in enumerate(files))
794-
795-

0 commit comments

Comments
 (0)