forked from brain-group/modelprocessing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
spherical_flux.py
241 lines (204 loc) · 8.51 KB
/
spherical_flux.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
"""
Calculates properties over a spherical shell.
Inputs:
--field, -f: field suffix to calculate shell for. Can
also give "all" to get shells calculated for flux,
number density, and normal velocity
--species, -s: What species to calculate shell for. Can
also give "all" to get shells calculated for O2_p1,
O_p1, and CO2_p1.
--infile, -i: Input file.
--radius, -r: Radius in units of Rm to calculate shell for.
Can also give all to get evenly spaced shells from 1-3 Rm.
-output_csv, -o: Flag to output a csv file with all the data
that has been calculated.
-total, -t: Flag to add "total_flux" as a field. Only totals
ions that have already been calculated.
-ion_velocity, -v: Flag to use ion velocities instead of
total velocities
"""
import numpy as np
import matplotlib.pyplot as plt
#import spiceypy as sp
import h5py
import matplotlib.gridspec as gridspec
from matplotlib import ticker
from matplotlib.collections import LineCollection
from modelprocessing.general_functions import *
from modelprocessing.flythrough_compare import *
import pandas as pd
from matplotlib.colors import LogNorm, Normalize, SymLogNorm
from itertools import product as iproduct
from modelprocessing.misc.labels import *
from modelprocessing.misc.field_default_params import *
import sys
import ast
#plt.style.use(['seaborn-poster', 'poster'])
def create_sphere_mesh(r,planet_r=3390,d_angle=5.0,hemi=None):
if hemi == '+x':
lon = np.arange(-90,90,d_angle)
lat = np.arange(-90,91, d_angle)
elif hemi == '-x':
lon = np.arange(90,270,d_angle)
lat = np.arange(-90,91, d_angle)
elif hemi == 'tail':
lon = np.arange(180-30, 180+30, d_angle)
lat = np.arange(-45,45, d_angle)
else:
lon = np.arange(-90,271, d_angle)
lat = np.arange(-90,91, d_angle)
phi = -1*(lat-90)*np.pi/180.0
theta = lon*np.pi/180.0
phi_v, theta_v = np.meshgrid(phi, theta)
#Make face centers
phi_f = 0.5*(phi_v[1:,1:]+phi_v[:-1,:-1])
theta_f = 0.5*(theta_v[1:,1:]+theta_v[:-1,:-1])
lat_f = -1*phi_f*180/np.pi+90
lon_f = theta_f*180/np.pi
x = (r*np.cos(theta_f)*np.sin(phi_f)).flatten()
y = (r*np.sin(theta_f)*np.sin(phi_f)).flatten()
z = (r*np.cos(phi_f)).flatten()
#z = (r*np.sin(theta_f)*np.sin(phi_f)).flatten()
#y = (r*np.cos(phi_f)).flatten()
coords_f = np.array([x,y,z])
dphi = (phi_v[1:,1:]-phi_v[:-1,:-1])
dtheta = (theta_v[1:,1:]-theta_v[:-1,:-1])
area = np.abs((r*planet_r*1e5)**2*(np.sin(phi_f)*dtheta*dphi).flatten())
rhat = coords_f/np.sqrt(np.sum(coords_f**2,axis=0))
return ((lon_f, lat_f), coords_f, rhat, area)
def create_plot(field, xy, fdat,r, show=False, fname='Output/test.pdf', override_lims=None):
if override_lims is None:
override_lims = {}
# Check to see if the field diverges
if field in field_lims_shells:
vmin, vmax = field_lims_shells[field]
#linthresh = 10**(int(np.ceil(np.log10(vmax)))-4.5)
linthresh = 1e4
if field in override_lims:
vmin, vmax = override_lims[field]
if sum([1 for k in diverging_field_keys if k in field]):
cmap = 'RdBu'
fdat = np.ma.filled(np.ma.masked_invalid( fdat),0)
if field not in field_lims_shells:
vmax = np.max(np.abs(fdat))
vmin = -1*vmax
if len(fdat[fdat>0]) ==0:return
linthresh= 100*np.min(np.abs(fdat[fdat>0]))
else:
cmap = 'viridis'
#fdat = np.ma.masked_where(fdat==0, fdat)
fdat = np.ma.masked_invalid(fdat)
if field not in field_lims_shells:
vmin, vmax = np.min(fdat), np.max(fdat)
symlog=False
if sum([1 for k in symlog_field_keys if k in field]):
norm = SymLogNorm(vmin=vmin, vmax=vmax, linthresh=linthresh)
maxlog=int(np.ceil( np.log10(vmax) ))
minlog=int(np.ceil( np.log10(-vmin) ))
linlog=int(np.ceil(np.log10(linthresh)))
symlog=True
#generate logarithmic ticks
tick_locations=([-(10**x) for x in range(minlog,linlog-1,-1)]
+[0.0]
+[(10**x) for x in range(linlog,maxlog+1)] )
elif sum([1 for k in log_field_keys if k in field]):
norm = LogNorm(vmin=vmin, vmax=vmax)
else: norm = Normalize(vmin=vmin, vmax=vmax)
lon, lat = xy
plt.pcolormesh(lon, lat, fdat.reshape(lon.shape), cmap=cmap,
norm=norm, rasterized=True, vmin=vmin, vmax=vmax)
if symlog:
plt.colorbar(label=label_lookup[field],ticks=tick_locations,
format=ticker.LogFormatterMathtext())
else:
if field in label_lookup:
plt.colorbar(label=label_lookup[field])
else:
plt.colorbar(label=field)
plt.gca().set_aspect('equal')
plt.ylim(-90,90)
plt.xlim(-90,270)
plt.xticks([-90,-30,30,90,150,210,270])
plt.yticks([-90,-45,0,45,90])
plt.xlabel('Longitude (0=Dayside, 180=Nightside)')
plt.ylabel('Latitude')
plt.title('R = {0} (RM)'.format(r))
print('Saving: {0}'.format(fname))
if show:
plt.show()
else:
plt.savefig(fname)
plt.close()
def run_sphere_flux(ds_names, ds_types, r, fields, ion_velocity, make_plot=True, plot_kwargs=None, d_angle=5.0):
xy, coords, rhat, area = create_sphere_mesh(r, d_angle=d_angle)
indxs = get_path_idxs(coords, ds_names, ds_types)
data = get_all_data(ds_names, ds_types, indxs,
[f for f in fields if f != 'total_flux'],
ion_velocity=ion_velocity, normal=rhat, area=area)
if 'total_flux' in fields:
flux_dat = {}
for dsk in ds_names.keys():
fluxes = np.array([v[dsk] for k,v in data.items() if 'flux' in k])
flux_dat[dsk] = np.sum(np.nan_to_num(fluxes), axis=0)
data['total_flux'] = flux_dat
if make_plot:
for dsk in ds_names.keys():
for field in fields:
create_plot(field, xy, data[field][dsk], r,
fname='Output/sphere_r{0}_{1}_{2}.pdf'.format(r,field,dsk),
**plot_kwargs)
data['area'] = area
return data
def main(argv):
try:
opts, args = getopt.getopt(argv,"f:i:r:s:otv",
["field=","species=", "infile=","radius=", "output_csv",
"total", "ion_velocity"] )
except getopt.GetoptError:
print(getopt.GetoptError)
print('error')
return
out_csv, total, ion_velocity = False, False, False
for opt, arg in opts:
if opt in ("-f", "--field"):
if arg == "all":
fields_suffix = ['flux', 'number_density']
elif arg == 'mag':
fields_suffix = ['magnetic_field_normal', 'magnetic_field_total', 'magnetic_field_x', 'magnetic_field_y', 'magnetic_field_z']
else:
fields_suffix = [arg]
elif opt in ("-s", "--species"):
if arg == 'all': ions = ['O2_p1_', 'O_p1_']#'CO2_p1',
elif arg == 'None': ions = ['']
else: ions = [arg+"_"]
elif opt in ("-i", "--infile"):
dsk = arg.split('/')[-1].split('.')[0]
ds_names = {dsk:arg}
if 'batsrus' in dsk: ds_types = {'batsrus':[dsk]}
else: ds_types = {'rhybrid':[dsk]}
elif opt in ("-r", "--radius"):
if arg == 'all': radii = np.arange(1.0, 3.0, 0.2)
else: radii = ast.literal_eval(arg)
if type(radii) == float: radii = [radii]
elif opt in ("-o", "-output_csv"):
out_csv = True
elif opt in ("-t", "-total"):
total = True
elif opt in ("-v", "-ion_velocity"):
ion_velocity = True
fields = [ion+suff for ion, suff in iproduct(ions, fields_suffix)]
if total: fields.append('total_flux')
if out_csv: df = pd.DataFrame(columns=ions, index=radii)
for ds_type in ds_names.keys():
for r in radii:
field_dat = run_sphere_flux(ds_names, ds_types, r, fields,
ion_velocity=ion_velocity
)
if out_csv:
for ion in ions:
total_ions = np.sum(np.nan_to_num(field_dat['area']*\
field_dat[ion+'flux'][ds_type]))
df.loc[r,ion] = total_ions
if out_csv: df.to_csv('Output/sphere_flux_{0}.csv'.format(ds_type))
if __name__=='__main__':
main(sys.argv[1:])