Blame view

Bin.py/run.py 17.3 KB
90a0ee4e   Elena.Budnik   python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
from datetime import datetime, date, time, timedelta
import pandas as pd
import numpy as np
import os
import sys
from lxml import etree
from netCDF4 import Dataset
import logging
from logging.handlers import RotatingFileHandler
import time as myTime

def main():

	J2000REF = 946679400 # 2000-01-01T00:00:00 -30min
fef70152   Elena.Budnik   orb in km
15
16
	AU = 150000000.0 # km
	
90a0ee4e   Elena.Budnik   python
17
	# CHECK ARGS
5d91ae4f   Elena.Budnik   bug
18
	checkArgs(3, 'Usage : python run.py (target) (Solar Wind XML config file) [(SwStopTime ISO / -1)]')
f5a5ef6f   Elena.Budnik   work
19
	
90a0ee4e   Elena.Budnik   python
20
	prefix =  sys.argv[1]
e2271bb5   Elena.Budnik   work
21
	xmlFile = sys.argv[2]
5d91ae4f   Elena.Budnik   bug
22
	if (len(sys.argv) == 4) :
78130ee6   Elena.Budnik   bug
23
24
25
26
27
		if ( sys.argv[3] != '-1' ) :
			swStopD = datetime.strptime(sys.argv[3], '%Y-%m-%dT%H:%M:%S.000Z')
			swStop =  swStopD.isoformat()
		else :
			swStop = '-1'
5d91ae4f   Elena.Budnik   bug
28
29
30
	else :
		swStop = '-1'
		
90a0ee4e   Elena.Budnik   python
31
32
33
34
35
36
37
	start_time = myTime.time()

	# GET ENVIRONMENT VARIABLES
	SW2ROOT     = os.getenv('SW2ROOT')
	SW2MISSIONS = os.getenv('REQ')
	SW2DATA     = os.getenv('SW2DATA')
	SW2NC       = os.getenv('SW2NC')
fef70152   Elena.Budnik   orb in km
38
	
f5a5ef6f   Elena.Budnik   work
39
40
	# GET INFOS FROM XML CONFIG FILE
	start,stop,plasmaVi,srcVi,srcR,srcLon,tgtVi,tgtR,tgtLon = getXMLConfig(xmlFile)
47081b7a   Elena.Budnik   work
41
	src = plasmaVi.split('_')[0]
f5a5ef6f   Elena.Budnik   work
42

90a0ee4e   Elena.Budnik   python
43
	# CREATE A DIRECTORY FOR THE NEW QUERY
f5a5ef6f   Elena.Budnik   work
44
45
46
	MYDIR = SW2DATA+'/'+src+'/'+prefix+'_'+datetime.now().strftime('%Y%m%d')
	if not os.path.exists(MYDIR):
		os.makedirs(MYDIR,0775)
90a0ee4e   Elena.Budnik   python
47
48
49
	
	# CREATION OF A LOGGER
	logFile = prefix+'_'+datetime.now().strftime('%Y%m%d')+'.log'
f5a5ef6f   Elena.Budnik   work
50
	logger = initLogger(MYDIR+'/'+logFile)	
90a0ee4e   Elena.Budnik   python
51
52
53
54
	logger.info("Start : " + start)
	logger.info("Stop : " + stop)
	logger.info("Plasma VI : " + plasmaVi)
	logger.info("Source VI : " + srcVi)
f5a5ef6f   Elena.Budnik   work
55
56
	logger.info("Source distance : " + srcR)
	logger.info("Source longitude : " + srcLon)
90a0ee4e   Elena.Budnik   python
57
	logger.info("Target VI : " + tgtVi)
f5a5ef6f   Elena.Budnik   work
58
59
	logger.info("Target distance : " + tgtR)
	logger.info("Target longitude : " + tgtLon)
90a0ee4e   Elena.Budnik   python
60
61
62


	# COMPUTING BOUNDARIES
45252157   Elena.Budnik   work
63
	marginPlasma      = getMarginDays(prefix) #Days
90a0ee4e   Elena.Budnik   python
64
65
	plasmaStart       = shiftedDate(start, days=-marginPlasma, seconds=-1)
	plasmaDDStart     = time2ddtime(plasmaStart)
092572bf   Elena.Budnik   new args, intern...
66
67
68
69
70
71
72
73
74
	
	if swStop == '-1' :
		plasmaStop = shiftedDate(stop, days=marginPlasma)
	else :
		if (shiftedDate(stop, days=marginPlasma) >= swStop ) :
			plasmaStop = swStop
		else :
			plasmaStop = shiftedDate(stop, days=marginPlasma)
	# if run run.py 'alone' - for previous years	
47081b7a   Elena.Budnik   work
75
	#plasmaStop        = shiftedDate(stop, days=marginPlasma)
092572bf   Elena.Budnik   new args, intern...
76
	#plasmaStop        = shiftedDate(swStop)
2b5aff50   Elena.Budnik   stereo added
77
78
	print plasmaStop
	 
90a0ee4e   Elena.Budnik   python
79
80
	plasmaDDStop      = time2ddtime(plasmaStop)
	ddTimeDeltaPlasma = DDTimeDelta(plasmaStart, plasmaStop)
092572bf   Elena.Budnik   new args, intern...
81

90a0ee4e   Elena.Budnik   python
82
83
84
85
86
87
88
89
	marginOrbit       = 20 # Hours
	orbitsStart       = shiftedDate(plasmaStart, hours=-marginOrbit)
	orbitsStop        = shiftedDate(plasmaStop, hours=marginOrbit)
	orbitsDDStart     = time2ddtime(orbitsStart)
	ddTimeDeltaOrbit  = DDTimeDelta(orbitsStart, orbitsStop)

	# GET DATA FROM DD BASE DEPENDING ON SW INPUT 
	if plasmaVi == 'omni_hour_all':
2b5aff50   Elena.Budnik   stereo added
90
		plasmaCmd    = ['get_OMNI_1H',MYDIR + '/plasma.csv',plasmaDDStart,ddTimeDeltaPlasma]
90a0ee4e   Elena.Budnik   python
91
	elif plasmaVi == 'ace_swepam_real':
2b5aff50   Elena.Budnik   stereo added
92
93
94
95
96
97
98
99
		plasmaCmd    = ['get_ACE_RT',MYDIR + '/plasma.csv',MYDIR + '/mag.csv',plasmaDDStart,ddTimeDeltaPlasma]
	elif plasmaVi == 'sta_l2_pla':
		plasmaCmd    = ['get_STEREO','a',MYDIR + '/plasma.csv',MYDIR + '/mag.csv',plasmaDDStart,ddTimeDeltaPlasma]
	elif plasmaVi == 'stb_l2_pla':
		plasmaCmd    = ['get_STEREO','b',MYDIR + '/plasma.csv',MYDIR + '/mag.csv',plasmaDDStart,ddTimeDeltaPlasma]
	elif plasmaVi == 'dsc_fc_1m':
		plasmaCmd    = ['get_DSCOVR', MYDIR + '/plasma.csv',MYDIR + '/mag.csv',plasmaDDStart,ddTimeDeltaPlasma]
			
af16ae5a   Elena.Budnik   2 angles + Templates
100
	print plasmaCmd
90a0ee4e   Elena.Budnik   python
101
102
103
104
105
	srcCmd   = ['get_R_LON_HCI',MYDIR+'/source.csv',srcVi,srcR,srcLon,orbitsDDStart,ddTimeDeltaOrbit]
	tgtCmd = ['get_R_LON_HCI',MYDIR+'/target.csv',tgtVi,tgtR,tgtLon,orbitsDDStart,ddTimeDeltaOrbit]
	os.system(' '.join(plasmaCmd))
	os.system(' '.join(srcCmd))
	os.system(' '.join(tgtCmd))
45252157   Elena.Budnik   work
106
       
90a0ee4e   Elena.Budnik   python
107
108
109
110
111
112
113
114
115
116
117
118
	if os.path.getsize(MYDIR+'/plasma.csv') == 0:
		logger.error('Failed to load plasma data')
		sys.exit(2)
	elif os.path.getsize(MYDIR+'/source.csv') == 0:
		logger.error('Failed to load source orbit data')
		sys.exit(2)
	elif os.path.getsize(MYDIR+'/target.csv') == 0:
		logger.error('Failed to load target orbit data')
		sys.exit(2)

	# PLASMA DATAFRAME
	if plasmaVi == 'omni_hour_all':
2b5aff50   Elena.Budnik   stereo added
119
		plasma = pd.read_csv(MYDIR + '/plasma.csv', dtype='S16,f4,f4,f4,f4,f4,f4,f4,f4')		
90a0ee4e   Elena.Budnik   python
120
121
122
123
124
125
126
	elif plasmaVi == 'ace_swepam_real':
		if os.path.getsize(MYDIR+'/mag.csv') == 0:
			logger.error('Failed to load mag data')
			sys.exit(2)
		sw = pd.read_csv(MYDIR+'/plasma.csv', dtype='S16,f4,f4,f4')				 
		mag = pd.read_csv(MYDIR+'/mag.csv', dtype='S16,f4,f4,f4')				 
		plasma = sw.merge(mag, on='Time')
2b5aff50   Elena.Budnik   stereo added
127
128
129
130
131
132
133
	elif plasmaVi == 'sta_l2_pla' or plasmaVi == 'stb_l2_pla' or plasmaVi == 'dsc_fc_1m':
		if os.path.getsize(MYDIR+'/mag.csv') == 0:
			logger.error('Failed to load mag data')
			sys.exit(2)
		sw = pd.read_csv(MYDIR+'/plasma.csv', dtype='S16,f4,f4,f4,f4,f4')				 
		mag = pd.read_csv(MYDIR+'/mag.csv', dtype='S16,f4,f4,f4')				 
		plasma = sw.merge(mag, on='Time')	
90a0ee4e   Elena.Budnik   python
134
135
136
		
	plasma['Time'] = ddTime2Datetime(plasma['Time'])
	plasma = plasma.set_index('Time')
2b5aff50   Elena.Budnik   stereo added
137
	 
f5a5ef6f   Elena.Budnik   work
138
	logger.info('Number of NaNs for plasma data before cleaning : %d' % plasma.isnull().sum().sum())
90a0ee4e   Elena.Budnik   python
139
	plasma = plasma.interpolate().fillna(method='bfill')
f5a5ef6f   Elena.Budnik   work
140
	logger.info('Number of NaNs for plasma data after cleaning : %d' % plasma.isnull().sum().sum())
90a0ee4e   Elena.Budnik   python
141
142
143
144
145
146
147
148
149
150
151
152
153
154

	# SOURCE DATAFRAME
	source = pd.read_csv(MYDIR+'/source.csv', dtype='S16,f4,f4,f4')
	source['Time'] = ddTime2Datetime(source['Time'])
	source.columns = ['Time','R_HCI_source', 'LON_HCI_source']
	source = source.set_index('Time')

	# TARGET DATAFRAME
	target = pd.read_csv(MYDIR+'/target.csv', dtype='S16,f4,f4,f4')
	target['Time'] = ddTime2Datetime(target['Time'])
	target.columns = ['Time','R_HCI_target', 'LON_HCI_target']
	target = target.set_index('Time')

	# CARTESIAN TO SPHERICAL COORDS
fef70152   Elena.Budnik   orb in km
155
	r_source = source['R_HCI_source'] / AU
af16ae5a   Elena.Budnik   2 angles + Templates
156
		
90a0ee4e   Elena.Budnik   python
157
158
159
160
161
162
163
164
	lon_source_deg = np.degrees(source['LON_HCI_source'])
	lon_source_deg[lon_source_deg < 0] = lon_source_deg+360.0 #-180/180 -> 0/360

	sourceData = np.array([source.index,r_source,lon_source_deg]).T
	sourceColumns = ['Time','R_source','Lon_source']
	source = pd.DataFrame(data=sourceData,columns=sourceColumns)
	source = source.set_index('Time')

fef70152   Elena.Budnik   orb in km
165
	r_target = target['R_HCI_target'] / AU
90a0ee4e   Elena.Budnik   python
166
167
168
169
170
171
172
173
	lon_target_deg = np.degrees(target['LON_HCI_target'])
	lon_target_deg[lon_target_deg < 0] = lon_target_deg+360.0 #-180/180 -> 0/360

	targetData = np.array([target.index,r_target,lon_target_deg]).T
	targetColumns = ['Time','R_target','Lon_target']
	target = pd.DataFrame(data=targetData,columns=targetColumns)
	target = target.set_index('Time')

2b5aff50   Elena.Budnik   stereo added
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
	# TAO frame : RTN with t=-t
	if plasmaVi == 'sta_l2_pla' or plasmaVi == 'stb_l2_pla' :
		vx = plasma['Vr']
		vy = -plasma['Vt']
		vz = plasma['Vn']
		temperature = plasma['Vth']*plasma['Vth']*60.6 # v=sqrt(2kT/m)
	elif plasmaVi == 'dsc_fc_1m':
		vx = -plasma['Vx']
		vy = -plasma['Vy']
		vz = plasma['Vz']
		temperature = plasma.Temperature
	else :
		# SPHERICAL TO CARTESIAN COORDS
		if plasmaVi == 'omni_hour_all':
			vlon = np.radians(plasma['Vlon'])
			vlat = np.radians(plasma['Vlat'])
		elif plasmaVi == 'ace_swepam_real': 
			vlon = np.radians(-2.0)
			vlat = np.radians(1.0)
			
		vx = plasma['V']*np.cos(vlat)*np.cos(vlon)
		vy = -plasma['V']*np.cos(vlat)*np.sin(vlon)
		vz = plasma['V']*np.sin(vlat)
90a0ee4e   Elena.Budnik   python
197
		
2b5aff50   Elena.Budnik   stereo added
198
		temperature = plasma.Temperature
90a0ee4e   Elena.Budnik   python
199
200
201
202
203
204
205

	# ROTATION
	bx = -np.array(plasma['Bx'])
	by = -np.array(plasma['By'])
	bz = np.array(plasma['Bz'])

	# FINAL PLASMA DATAFRAME
2b5aff50   Elena.Budnik   stereo added
206
	plasmaData = np.array([plasma.index,plasma.Density,temperature,vx,vy,vz,bx,by,bz])
90a0ee4e   Elena.Budnik   python
207
208
209
210
211
212
213
214
	plasmaColumns = ['Time','Density','Temperature','Vx','Vy','Vz','Bx','By','Bz']
	plasma = pd.DataFrame(data=plasmaData.T,columns=plasmaColumns)
	plasma = plasma.set_index('Time')

	# FINAL DATAFRAME
	combined = plasma.join(source,how='outer').join(target,how='outer')

	# trunk = combined.truncate(before=start, after=stop)
5d91ae4f   Elena.Budnik   bug
215
216
217
218
	#if (prefix == 'venus' or prefix == 'mercury') :
		#trunk = combined.truncate(before=start)
	#else :
	trunk = combined #.truncate(after=stop)
092572bf   Elena.Budnik   new args, intern...
219
		
90a0ee4e   Elena.Budnik   python
220
221
222
223
	df = trunk.groupby(trunk.index).first()

	df = df.resample('1H')
	df = df.interpolate().fillna(method='backfill')
f5a5ef6f   Elena.Budnik   work
224
	
3fcdd2be   Elena.Budnik   condition on sw d...
225
226
	df.Density[df.Density < 0.01] = 0.01
	
f5a5ef6f   Elena.Budnik   work
227
	if df['R_target'].mean() < df['R_source'].mean():		
90a0ee4e   Elena.Budnik   python
228
229
230
231
		df = df.reindex(index=df.index[::-1])
		idprop = -1
		xmax1  = 1.3
		xmin1  = 0.3
45252157   Elena.Budnik   work
232
233
234
		if prefix == 'venus':
			xmax1 = 1.5
			xmin1 = 0.5
90a0ee4e   Elena.Budnik   python
235
236
	else:
		idprop = 1
af920889   Elena.Budnik   ajust
237
		xmin1  = 0.8
45252157   Elena.Budnik   work
238
239
240
241
242
243
		if prefix == 'jupiter' or prefix == 'juno' :
			xmax1 = 5.8
		elif prefix == 'mars' :
			xmax1 = 1.8
		else :
			xmax1 = 10.8
90a0ee4e   Elena.Budnik   python
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
		
	# QUALITY FLAG
	dataFlagData = np.array( [df.index,np.zeros(len(df.index)).astype(int)])
	# dataFlagData = np.array( [df.index,np.ones(len(df.index)).astype(int)])
	dataFlagColumns = ['Time','QualityFlag']
	dataFlag = pd.DataFrame(data=dataFlagData.T,columns=dataFlagColumns)
	dataFlag = dataFlag.set_index('Time')
	df = df.join(dataFlag,how='outer')

	# WRITE TO A DATA FILE
	df.to_csv(MYDIR+'/myInputs.txt',date_format='%Y-%m-%dT%H:%M:%S',float_format="%.2f",header=False, sep=" ")
	

	# WRITE THE INPUTS FILE
	myT = [ time2J2000(str(t),J2000REF) for t in df.index ]

	filename = MYDIR+"/inputs.txt"
	fmt = 'e'
	sftFmt = ''
	with open(filename, "w") as myFile:
	    for ti,di,tempi,vxi,vyi,vzi,bxi,byi,bzi,rsrci,lonsrci,rtgti,lontgti,qfi in zip(myT, df['Density'], df['Temperature'], df['Vx'], df['Vy'], df['Vz'], df['Bx'], df['By'], df['Bz'], df['R_source'], df['Lon_source'],df['R_target'],df['Lon_target'],df['QualityFlag']):
	        line = [sftFmt,ti,format(di, fmt),format(tempi, fmt),format(vxi, fmt),format(vyi, fmt),format(vzi, fmt),format(bxi, fmt),format(byi, fmt),format(bzi, fmt),format(rsrci, fmt),format(lonsrci, fmt),format(rtgti, fmt),format(lontgti, fmt),format(qfi, fmt)]
	        myFile.write('   '.join(line)+'\n')

	myFile.close()

	# SW MHD CODE
	writeNamelist(MYDIR,idprop,xmax1,xmin1)
	logger.info('Computing solar wind propagation ...')
	os.system('sw.exe')
	
	# PROCESSING OUTPUTS OF SW CODE
	years,months,days,t,n,temp,vx,vy,by,pdyn,dphi,qualFlag = np.loadtxt(MYDIR+'/outputs.txt', comments="#", unpack="True", dtype=str,usecols=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11))

	myDates = []
	for yi,mi,di,ti, in zip(years,months,days,t):
		if ti=='24:00:00':
5d91ae4f   Elena.Budnik   bug
281
			ti='23:59:59'
90a0ee4e   Elena.Budnik   python
282
283
284
285
286
287
288
289
290
		myDates.append(datetime.strptime(yi+'-'+mi+'-'+di+' '+ti, '%Y-%m-%d %H:%M:%S'))
	
	myDates = np.array(myDates)

	outputsData = np.array([myDates,n.astype(float),temp.astype(float),vx.astype(float),vy.astype(float),by.astype(float),pdyn.astype(float),dphi.astype(float),qualFlag.astype(float)])
	outputsColumns = ['Time','Density','Temperature','Vx','Vy','By','pdyn','dphi','qualFlag']
	outputs = pd.DataFrame(data=outputsData.T,columns=outputsColumns)
	outputs = outputs.set_index('Time')

092572bf   Elena.Budnik   new args, intern...
291
	outputs = outputs.truncate(before=start, after=stop)
90a0ee4e   Elena.Budnik   python
292
293
294
295
296
297

	outputs.to_csv(MYDIR+'/myOutputs.txt',date_format='%Y-%m-%dT%H:%M:%S',float_format="%.2f",header=False, sep=" ")

	# WRITE THE NETCDF OUTPUT
	ddTime = []
	for ti in outputs.index:
001bb5fc   Elena.Budnik   python nc
298
299
		ddTime.append(str(ti.year)+'{:03}'.format(ti.dayofyear-1)+'{:02}'.format(ti.hour)+'{:02}'.format(ti.minute)+'{:02}'.format(ti.second)+'000\0')

f5a5ef6f   Elena.Budnik   work
300
301
302
303
	if not os.path.exists(SW2NC):
		os.makedirs(SW2NC,0775)
		
   	ncFile = SW2NC+'/'+os.path.basename(xmlFile).split('.')[0]+'.nc'
90a0ee4e   Elena.Budnik   python
304

3fcdd2be   Elena.Budnik   condition on sw d...
305
	nc = Dataset( ncFile, "w", format="NETCDF3_CLASSIC" )
001bb5fc   Elena.Budnik   python nc
306
307
308
	
	nc.createDimension( "Time", len(ddTime) )
	nc.createDimension( "TimeLength", 17 )
90a0ee4e   Elena.Budnik   python
309
	nc.createDimension( "Vector", 2 )
001bb5fc   Elena.Budnik   python nc
310
311
312
313
314
315
316
317
318
	
	timeVar = nc.createVariable( 'Time', 'S1', ( u'Time', u'TimeLength') )
	timeStartVar = nc.createVariable( 'StartTime', 'S1', ( u'TimeLength') )
	timeStopVar = nc.createVariable( 'StopTime', 'S1', ( u'TimeLength') )
		
	timeVar[:] = np.asarray(map(list,ddTime))
	timeStartVar[:] = list(ddTime[0])
	timeStopVar[:] = list(ddTime[int(len(ddTime))-1])
	
90a0ee4e   Elena.Budnik   python
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
	v = [ (vix, viy) for vix, viy in zip(np.array(outputs['Vx']), np.array(outputs['Vy'])) ]

	velocityVar    = nc.createVariable( 'V', 'f4', (u'Time', u'Vector') )
	velocityVar.units = 'km/s'
	velocityVar[:] = v

	magVar    = nc.createVariable( 'B', 'f4', (u'Time',) )
	magVar.units = 'nT'
	magVar[:] = np.array(outputs['By'])

	densityVar    = nc.createVariable( 'N', 'f4', (u'Time',) )
	densityVar.units = 'cm-3'
	densityVar[:] = np.array(outputs['Density'])

	temperatureVar    = nc.createVariable( 'T', 'f4', (u'Time',) )
	tempKelvin = [ tempi/11600.0 for tempi in np.array(outputs['Temperature']) ]
af16ae5a   Elena.Budnik   2 angles + Templates
335
	temperatureVar.units = 'eV'
90a0ee4e   Elena.Budnik   python
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
	temperatureVar[:] = tempKelvin

	deltaPhiVar    = nc.createVariable( 'Delta_angle', 'f4', (u'Time',) )
	deltaPhiVar.units = 'degrees'
	deltaPhiVar[:] = np.array(outputs['dphi'])

	pdynVar    = nc.createVariable( 'P_dyn', 'f4', (u'Time',) )
	pdynVar.units = 'nPa'
	pdynVar[:] = np.array(outputs['pdyn'])

	qualFlagVar    = nc.createVariable( 'QualityFlag', 'i4', (u'Time',) )
	qualFlagVar[:] = np.array(outputs['qualFlag'])
	                     
	globAttr = {'Source': 'Solar Wind Model', 'Created': str(datetime.now())}
	nc.setncatts( globAttr )

	nc.close()

	# END OF PROCESS
	os.system('mv namelist '+MYDIR)
001bb5fc   Elena.Budnik   python nc
356
	#os.system('mv fort.* '+MYDIR)
90a0ee4e   Elena.Budnik   python
357
358
359
360
361
	stop_time = myTime.time() 
	interval = stop_time - start_time
	logger.info('Program terminated in ' + '{:.2f}'.format(interval) + ' seconds.')

def checkArgs(nbArgs, message):
5d91ae4f   Elena.Budnik   bug
362
	if len(sys.argv) < nbArgs:
90a0ee4e   Elena.Budnik   python
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
		print(message)
		sys.exit(2)

def initLogger(logfile):
	logger = logging.getLogger()
	logger.setLevel(logging.INFO)
 
	fileFormatter = logging.Formatter('%(asctime)s :: [%(levelname)s] :: %(message)s')
	fileHandler   = RotatingFileHandler(logfile, 'a', 1000000, 1)
	fileHandler.setLevel(logging.ERROR)
	fileHandler.setFormatter(fileFormatter)
	logger.addHandler(fileHandler)
 
	consoleFormatter = logging.Formatter('[%(levelname)s] %(message)s')
	consoleHandler   = logging.StreamHandler()
	consoleHandler.setLevel(logging.INFO)
	consoleHandler.setFormatter(consoleFormatter)
	logger.addHandler(consoleHandler)

	return logger


def getXMLConfig(XMLFilename):

	myXml    = etree.parse(XMLFilename)
	start    = myXml.xpath("/MISSION/START")[0].text
	stop     = myXml.xpath("/MISSION/STOP")[0].text
	plasmaVI = myXml.xpath("/MISSION/PLASMA_VI")[0].text
	srcVI    = myXml.xpath("/MISSION/SOURCE_VI")[0].text
	srcR     = myXml.xpath("/MISSION/SOURCE_R_PARAM")[0].text
	srcLon   = myXml.xpath("/MISSION/SOURCE_LON_PARAM")[0].text
	tgtVI    = myXml.xpath("/MISSION/TARGET_VI")[0].text
	tgtR     = myXml.xpath("/MISSION/TARGET_R_PARAM")[0].text
	tgtLon   = myXml.xpath("/MISSION/TARGET_LON_PARAM")[0].text

	return start,stop,plasmaVI,srcVI,srcR,srcLon,tgtVI,tgtR,tgtLon


def getMarginDays(tgtName):
	if tgtName == 'mercury':
001bb5fc   Elena.Budnik   python nc
403
		distAU = 0.61
90a0ee4e   Elena.Budnik   python
404
	elif tgtName == 'venus':
47081b7a   Elena.Budnik   work
405
		distAU = 0.28
90a0ee4e   Elena.Budnik   python
406
407
408
409
410
411
412
413
414
415
	elif tgtName == 'mars':
		distAU = 0.52
	elif tgtName == 'jupiter':
		distAU = 4.21
	elif tgtName == 'saturn':
		distAU = 8.54
	elif tgtName == 'p67':
		distAU = 4.0
	elif tgtName == 'juno':
		distAU = 6.0
5375ecd7   Elena.Budnik   added neptune, ur...
416
417
418
419
	elif tgtName == 'neptune':
		distAU = 29.0
	elif tgtName == 'uranus':
		distAU = 18.0	
90a0ee4e   Elena.Budnik   python
420
421
422
	else:
		distAU = 9.0

de0fd05e   Elena.Budnik   30 margin at leas...
423
	return np.ceil( (distAU*150000000)/(200*24*3600)) + 30
90a0ee4e   Elena.Budnik   python
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

def shiftedDate(myDate, days=0, hours=0, minutes=0, seconds=0):
    fmt    = "%Y-%m-%dT%H:%M:%S"
    d      = datetime.strptime(myDate, fmt)

    myShiftedDate = d + timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)

    return myShiftedDate.strftime("%Y-%m-%dT%H:%M:%S")

def time2ddtime(myDate):
    fmt    = "%Y-%m-%dT%H:%M:%S"
    d      = datetime.strptime(myDate, fmt)
    dddoy  = '{:03}'.format(int(d.strftime("%j"))-1)
    hour   = '{:02}'.format(d.hour)
    minute = '{:02}'.format(d.minute)
    second = '{:02}'.format(d.second)
    
    ddtime = str(d.year) + dddoy + hour + minute + second +'000'

    return ddtime

def timeDelta(date1, date2):
    fmt    = "%Y-%m-%dT%H:%M:%S"
    d1     = datetime.strptime(date1, fmt) 
    d2     = datetime.strptime(date2, fmt) 
    td = d2 - d1

    intDays    = td.days
    intHours   = td.seconds//3600
    intMinutes = (td.seconds//60)%60
    intSeconds = td.seconds-intHours*3600-intMinutes*60

    return intDays, intHours, intMinutes, intSeconds

def DDTimeDelta(date1, date2):
    interD, interH, interM, interS = timeDelta(date1, date2)
    ddTimeDelta = '0000' + '{:03}'.format(interD) + '{:02}'.format(interH) + '{:02}'.format(interM) + '{:02}'.format(interS) + '000'

    return ddTimeDelta

def ddTime2Datetime(ddTime):
    myDatetime = []
    for t in ddTime:
        year = int(t[0:4])
        day = int(t[4:7]) + 1
        myDate = datetime(year, 1, 1) + timedelta(day - 1)
        
        hour = int(t[7:9])
        minute = int(t[9:11])
        seconds = int(t[11:13])
        ms = int(t[13:16])*1000
        myTime = time(hour, minute,seconds,ms)
        
        myDatetime.append( datetime.combine(myDate, myTime) )
            
    return myDatetime

f5a5ef6f   Elena.Budnik   work
481
# ISO to J2000
90a0ee4e   Elena.Budnik   python
482
483
484
485
486
487
def time2J2000(myDate, j2000):
    fmt    = "%Y-%m-%d %H:%M:%S"
    d      = int(datetime.strptime(myDate, fmt).strftime("%s"))

    return str(d-j2000)

f5a5ef6f   Elena.Budnik   work
488
# make NAMELIST
90a0ee4e   Elena.Budnik   python
489
490
491
492
493
494
495
def writeNamelist(directory,idprop,xmax1,xmin1):
	with open('namelist', "w") as nl:
		nl.write('&INPARA1\n')
		nl.write('	idp_in=1\n')
		nl.write('	idp_prop=1\n')
		nl.write('	idp_out=1\n')
		#nl.write('	angref(1)=0.,30.,60.,90.,120.,150.,180.,210.,240.,270.,300.,330.\n')
af16ae5a   Elena.Budnik   2 angles + Templates
496
497
		#nl.write('	angref(1)=0.,60.,120.,180.,240.,300.\n')
		nl.write('	angref(1)=0.,180.\n')
90a0ee4e   Elena.Budnik   python
498
499
500
501
502
		nl.write('	idprop='+str(idprop)+'\n')
		nl.write('	fnin=\''+directory+'/inputs.txt\'\n')
		nl.write('	fnout=\''+directory+'/outputs.txt\'\n')
		nl.write('	fdirtmp=\''+directory+'/\'\n')
		nl.write('	instop=0\n')
5d91ae4f   Elena.Budnik   bug
503
504
		nl.write('	dtr=150.\n')
		nl.write('	touts=24.\n')
90a0ee4e   Elena.Budnik   python
505
506
507
508
509
510
511
512
513
514
515
516
		nl.write('	xmin1='+str(xmin1)+'\n')
		nl.write('	xmax1='+str(xmax1)+'\n')
		nl.write('/\n')
		nl.write('&INPARA2\n')
		nl.write('	npout=10\n')
		nl.write('	bx0at1au=0.001d0\n')
		nl.write('	gm=1.40\n')
		nl.write('/\n')
	nl.close()

if __name__ == '__main__':
	main()