/
radiolab.py
506 lines (402 loc) · 17.8 KB
/
radiolab.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
import tempfile
import os
import subprocess
import time
import numpy as np
import sys
# Code for the Digital Front-End Control (DFEC)
# Abandon all hope, all ye who enter!
def set_srs(srs_num,freq=None,vpp=None,dbm=None,off=None,pha=None):
"""SRS FUNCTION GENERATOR CONTROL
NAME: set_srs
PURPOSE: All-in-one program to control SRS DS345 function generators
CALLING SEQUENCE: set_srs(srs_number,freq=None,vpp=None,dbm=None,off=None,
pha=None)
REQUIRED INPUTS:
srs_num (int): The SRS LO number (either 1 or 2).
OPTIONAL INPUTS:
freq (float): Frequency to set the LO to (in Hz). Must be between 0 and
30 MHz. Default does not change frequency.
vpp (float): Amplitude to set the LO to in Volts, peak to peak. Must be
between -5 and +5 Volts. Default does not change amplitude.
dbm (float): Amplitude to set the LO to, in dBm (decible-milliWatts). Must be
between -36 and 23 dBm. Default does not change amplitude.
off (float): DC offset for the LO in Volts. Must be between -5 and +5
Volts. Default does not change amplitude.
pha (float): Phase offset to apply to LO signal in degrees. Must be
0 and 7200 degrees. Default does not change phase.
EXAMPLE: set_srs(1,freq=1e7,dbm=0,pha=180)
NOTES: You cannot set both vpp and dbm, since the are both controlling the
amplitude of the LO. Also, one should avoid having the total voltage at any
given time exceed +/- 5 Volts (i.e. don't set off=5 AND vpp=5).
MODIFICATION HIST:
-- 2/11/2014 - Initial creation.
"""
if srs_num not in [1, 2]:
raise Exception("ERROR: SRS generator not defined!")
elif srs_num == 1:
addr = '19'
elif srs_num == 2:
addr = '21'
tempFile = tempfile.NamedTemporaryFile(delete=False)
tempFile.write('++addr ' + addr + '\n')
tempFile.close()
os.system('gpib ' + tempFile.name + ' 10.32.92.86')
os.unlink(tempFile.name)
tempFile = tempfile.NamedTemporaryFile(delete=False)
tempFile.write('++mode 1\n')
tempFile.close()
os.system('gpib ' + tempFile.name + ' 10.32.92.86')
os.unlink(tempFile.name)
tempFile = tempfile.NamedTemporaryFile(delete=False)
tempFile.write('++eos 2\n')
tempFile.close()
os.system('gpib ' + tempFile.name + ' 10.32.92.86')
os.unlink(tempFile.name)
if (freq is not None) and (freq <= 0 or freq >= 3e7):
raise Exception("ERROR: Freq must be between 0 Hz and 30 MHz!")
if (vpp is not None) and (vpp <= -5 or vpp >= 5):
raise Exception("ERROR: Peak-to-peak volts must be between +/- 5 V!")
if (dbm is not None) and (dbm <= -36 or dbm >= 23):
raise Exception("ERROR: Power must be between -36 and +23 dBm!")
if (pha is not None) and (pha < 0 or dbm >= 7200):
raise Exception("ERROR: Phase offset must be between 0 and 7200 degrees!")
if (dbm is not None) and (vpp is not None):
raise Exception("ERROR: Cannot define both Vpp and dBm!")
if freq is not None:
tempFile = tempfile.NamedTemporaryFile(delete=False)
tempFile.write('FREQ %0.6f\n' % freq)
tempFile.close()
os.system('gpib ' + tempFile.name + ' 10.32.92.86')
os.unlink(tempFile.name)
if vpp is not None:
tempFile = tempfile.NamedTemporaryFile(delete=False)
tempFile.write('AMPL %0.2f VP\n' % vpp)
tempFile.close()
os.system('gpib ' + tempFile.name + ' 10.32.92.86')
os.unlink(tempFile.name)
if dbm is not None:
tempFile = tempfile.NamedTemporaryFile(delete=False)
tempFile.write('AMPL %0.2f DB\n' % dbm)
tempFile.close()
os.system('gpib ' + tempFile.name + ' 10.32.92.86')
os.unlink(tempFile.name)
if off is not None:
tempFile = tempfile.NamedTemporaryFile(delete=False)
tempFile.write('OFFS %0.2f\n' % off)
tempFile.close()
os.system('gpib ' + tempFile.name + ' 10.32.92.86')
os.unlink(tempFile.name)
if pha is not None:
tempFile = tempfile.NamedTemporaryFile(delete=False)
tempFile.write('PHSE %0.3f\n' % pha)
tempFile.close()
os.system('gpib ' + tempFile.name + ' 10.32.92.86')
os.unlink(tempFile.name)
def sampler(nSamp,freqSamp,fileName=None,dual=False,low=False,integer=False,timeWarn=True):
"""PULSAR SAMPLER FUNCTION
NAME: sampler
PURPOSE: Get data from the sampler in Pulsar
CALLING SEQUENCE: sampler(nSamp,freqSamp,fileName=None,dual=False,low=False,
integer=False, timeWarn=True)
OUTPUT:
data (ndarray): Series of values measured by the sampler.
REQUIRED INPUTS:
nSamp (int): Number of samples to record to the file. Must be between
0 and 262144 samples.
freqSamp (float): Sampling frequency (in Hz) to record data at. Must
below 20 MHz (or 10 MHz for "dual mode").
OPTIONAL INPUTS:
fileName (str): Location of file to record data to.
dual (bool): If True, then samples in "dual channel" mode, where data is
recorded from two channels instead of just one.
low (bool): "Low Voltage Mode" -- nominally, the ADC is designed to sample
between +/- 5 Volts. However, if low is set to True, the ADC will
sample between +/- 1 Volts. Use this only if you know your incoming
signal will not exceed +/- 1 Volts!
integer (bool): If set to true, will record the values as integer values
coming from the ADC (between 0 and 4096) instead of converting the
values to Volts.
timeWarn (bool): If sampling for longer than a tenth of a second,
pulsar may take an extremely long amount of time to return a value.
Setting this to True will force the function throw an error if
sampling for longer than this time (i.e. 10*nSamp > freqSamp)
EXAMPLE: sampler(1000,1e7,dual=True,integer=True)
MODIFICATION HIST:
-- 2/11/2014 - Initial creation.
"""
if fileName is None:
tempFile = tempfile.NamedTemporaryFile(delete=False)
fileName = tempFile.name
useTemp = True
elif not isinstance(fileName,str):
raise Exception('ERROR: Filename must be a string!')
else:
useTemp = False
if (freqSamp > 2e7):
raise Exception("ERROR: Sampling frequency cannot be greater than 20 MHz!")
elif dual and (freqSamp > 1e7):
raise Exception("ERROR: Sampling frequency cannot be greater than 10 MHz (in dual mode)!")
if (nSamp >= 262144) or (nSamp <= 0):
raise Exception("ERROR: Number of samples must be between 0 and 262144!")
if (timeWarn and (freqSamp < 10.0*nSamp)):
raise Exception("ERROR: Sampling time is too long!")
if dual:
chanStr = 'dual'
else:
chanStr = 'chan=2'
if low:
lowStr = ' lo'
else:
lowStr = ''
if integer:
intStr = ' integer'
else:
intStr = ''
os.system('echo adc nsamples=%i freq=%.5e %s fname=%s%s%s | /home/global/instrument/sendpc/sendpc' % (nSamp,freqSamp,chanStr,fileName,lowStr,intStr))
data = np.loadtxt(fileName)
if useTemp:
os.unlink(tempFile.name)
return data
def dft(xRange,xVals,yRange,inverse=False):
"""DISCRETE FOURIER TRANSFORM FUNCTION
NAME: dft
PURPOSE: Perform a discrete fourier transform on an array of values
CALLING SEQUENCE: sampler(xRange,xVals,yRange,inverse=True)
OUTPUT:
yVals (ndarray): Complex values for each of the frequencies/times
specified in 'yRange'.
REQUIRED INPUTS:
xRange (ndarray): The times (or frequencies, if inverse=True) that
each of the values was measured for.
xVals (ndarray): The measured values for the times/frequencies specifed
in 'xRange'.
yRange (ndarray): The frequencies (or times, if inverse=True) to
calculate the DFT for.
OPTIONAL INPUTS:
inverse (bool): When set to true, will calculate the inverse Fourier
transform (freq -> time, instead of time->freq).
MODIFICATION HIST:
-- 2/17/2014 - Initial creation.
"""
# Super-simple DFT algorithm
# Make sure that the arrays are ARRAYS, not LISTS
xRange = np.asarray(xRange)
xVals = np.asarray(xVals)
yRange = np.asarray(yRange)
# Generate an empty complex array to store values in
yVals = np.zeros_like(yRange)
yVals = 1.0*yVals+(1.0j*yVals)
# Perform DFT over specified frequencies
idx=0;
for yPos in yRange:
if inverse:
yVals[idx] = np.sum(xVals*np.e**(1.0j*xRange*yPos*2.0*np.pi))
else:
yVals[idx] = np.sum(xVals*np.e**(-1.0j*xRange*yPos*2.0*np.pi))
idx+=1
if not inverse:
yVals = yVals/(xVals.size)
return yVals
def gpibCall(gpibString):
tempFile = tempfile.NamedTemporaryFile(delete=False)
tempFile.write(gpibString + '\n')
tempFile.close()
os.system('/home/global/ay121/python/gpib ' + tempFile.name + ' 10.32.92.86')
os.unlink(tempFile.name)
def gpibReq(gpibString):
tempFile = tempfile.NamedTemporaryFile(delete=False)
tempFile.write(gpibString + '\n')
tempFile.close()
proc = subprocess.Popen(["/home/global/ay121/python/gpibw " + tempFile.name + " 10.32.92.86"],shell=True, stdout=subprocess.PIPE)
(spOut,spErr) = proc.communicate()
os.unlink(tempFile.name)
return spOut
def sendPC(pcString):
proc = subprocess.Popen(["echo " + pcString + "| /home/global/instrument/sendpc/sendpc"],shell=True, stdout=subprocess.PIPE)
(spOut,spErr) = proc.communicate()
return spOut
def getDVMData():
gpibCall('++addr 17')
dvmVolt = float(gpibReq('N4T3'))
return dvmVolt
def pntHome(homeMax=5):
sendPC('point tense alt_e=75 az_e=180 az_w=180 alt_w=75')
homeStatus = sendPC('home alt_e az_e alt_w az_w').split()
homeAttempt = 1;
while ((homeMax > homeAttempt) & (homeStatus[0] != 'done')):
time.sleep(3)
homeStatus = sendPC('home alt_e az_e alt_w az_w').split()
if (homeStatus[0] != 'done'):
print 'ERROR: Telescopes failed to home!'
return 1
else:
print 'Homing successful after ' + str(homeAttempt) + ' tries!'
return 0
def moveTo(az=None,alt=None,alt_w=None,az_w=None,alt_e=None,az_e=None):
if (az is not None):
az_w = az
az_e = az
if (alt is not None):
alt_w = alt
alt_e = alt
if (((az_e is None) & (az_w is None)) & ((alt_e is None) & (alt_w is None))):
raise Exception("ERROR: No pointing information included!")
cmdStr = 'point tense'
if (az_w is not None):
cmdStr = cmdStr + ' az_w=' + str(az_w)
if (az_e is not None):
cmdStr = cmdStr + ' az_e=' + str(az_e)
if (alt_w is not None):
cmdStr = cmdStr + ' alt_w=' + str(alt_w)
if (alt_e is not None):
cmdStr = cmdStr + ' alt_e=' + str(alt_e)
moveMsg = sendPC(cmdStr)
return moveMsg
def pntSkyToEnc(az=None,alt=None,noEast=False,noWest=False):
import pointcnfg
pointcnfg = reload(pointcnfg)
if ((az is None) | (alt is None)):
raise Exception("ERROR: Not enough inputs!")
az_w = float(az)
az_e = float(az)
alt_w = float(alt)
alt_e = float(alt)
if (np.less(np.mod(az_e+pointcnfg.eastAzFwrd,360.0),90) | np.greater(np.mod(az_e+pointcnfg.eastAzFwrd,360.0),270)):
az_e = np.mod(az_e + 180,360)
alt_e = 180 - alt_e
eastAzOff = pointcnfg.eastAzRev
eastElOff = pointcnfg.eastElRev
eastFlop = pointcnfg.eastFlopRev
eastSkew = pointcnfg.eastSkewRev
else:
eastAzOff = pointcnfg.eastAzFwrd
eastElOff = pointcnfg.eastElFwrd
eastFlop = pointcnfg.eastFlopFwrd
eastSkew = pointcnfg.eastSkewFwrd
if (np.less(np.mod(az_w+pointcnfg.westAzFwrd,360.0),90) | np.greater(np.mod(az_w+pointcnfg.westAzFwrd,360.0),270)):
az_w = np.mod(az_w + 180,360)
alt_w = 180 - alt_w
westAzOff = pointcnfg.westAzRev
westElOff = pointcnfg.westElRev
westFlop = pointcnfg.westFlopRev
westSkew = pointcnfg.westSkewRev
else:
westAzOff = pointcnfg.westAzFwrd
westElOff = pointcnfg.westElFwrd
westFlop = pointcnfg.westFlopFwrd
westSkew = pointcnfg.westSkewFwrd
alt_ec = alt_e + eastElOff + (eastFlop*np.cos(alt_e*180/np.pi))
az_ec = np.mod(az_e + eastAzOff + eastSkew/np.cos(alt_e*180/np.pi),360)
alt_wc = alt_w + westElOff + (westFlop*np.cos(alt_w*180/np.pi))
az_wc = np.mod(az_w + westAzOff + westSkew/np.cos(alt_w*180/np.pi),360)
if noWest:
az_wc = None
alt_wc = None
if noEast:
az_ec = None
alt_ec = None
pntDict = {'alt_w':alt_wc, 'az_w':az_wc, 'alt_e':alt_ec, 'az_e':az_ec}
return pntDict
def pntTo(alt=None,az=None,noEast=False,noWest=False,ignoreLims=False):
if ((alt is None) | (az is None)):
raise Exception("ERROR: Missing pointing information!")
pntDict = pntSkyToEnc(alt=alt,az=az,noEast=noEast,noWest=noWest)
if not ignoreLims:
if (np.greater(pntDict['alt_e'],87) | np.greater(pntDict['alt_w'],87)):
raise Exception("ERROR: Alt is too high!")
if (np.less(pntDict['alt_e'],15) | np.less(pntDict['alt_w'],15)):
raise Exception("ERROR: Alt is too low!")
pntStatus = moveTo(alt_e=pntDict['alt_e'],alt_w=pntDict['alt_w'],az_e=pntDict['az_e'],az_w=pntDict['az_w'])
print pntStatus
def getJulDay(gmtime=None):
if gmtime is None:
gmtime = time.gmtime()
julian = 367*gmtime.tm_year-int(7*(gmtime.tm_year+int((gmtime.tm_mon+9.0)/12.0))/4.0)+int(275.0*gmtime.tm_mon/9.0) \
+ gmtime.tm_mday +(gmtime.tm_hour/24.0)+(gmtime.tm_min/1440.0)+(gmtime.tm_sec/86400.0) + 1721013.5
return julian
def getLST(lon=-122.254618,date=None,juldate=None):
if ((juldate is None) & (date is None)):
juldate = getJulDay()
elif juldate is None:
juldate = getJulDay(gmtime=date)
cVals = [280.46061837, 360.98564736629, 0.000387933, 38710000.0 ]
jdJ2000 = juldate - 2451545.0
theta = cVals[0] + (cVals[1] * jdJ2000) + ((jdJ2000/36526)**2)*(cVals[2] - (jdJ2000/36425)/ cVals[3] )
lst = np.mod(( theta + (lon))/15.0,24)
return lst
def recordDVM(filename='voltdata.npz',sun=False,moon=False,recordLength=np.inf,verbose=True):
ra = 0
dec = 0
raArr = np.ndarray(0)
decArr = np.ndarray(0)
lstArr = np.ndarray(0)
jdArr = np.ndarray(0)
voltArr = np.ndarray(0)
startTime = time.time()
while np.less(time.time()-startTime,recordLength):
if sun:
raDec = sunPos()
ra = raDec[0]
dec = raDec[1]
startSamp = time.time()
currVolt = getDVMData()
currLST = getLST()
currJulDay = getJulDay()
raArr = np.append(raArr,ra)
decArr = np.append(decArr,ra)
voltArr = np.append(voltArr,currVolt)
lstArr = np.append(lstArr,currLST)
jdArr = np.append(jdArr,currJulDay)
if verbose:
print 'Measuring voltage: ' + str(currVolt) + ' (LST: ' + str(currLST) +' ' + time.asctime() + ')'
np.savez(filename,ra=raArr,dec=decArr,jd=jdArr,lst=lstArr,volts=voltArr)
sys.stdout.flush()
time.sleep(np.max([0,1.0-(time.time()-startSamp)]))
def sunPos(julDay=None):
# Code taken from the Goddard Software library, so I think it can be
# trusted.
if julDay is None:
julDay = getJulDay()
dtor = np.pi/180.0
julCen = (julDay - 2415020.0)/36525.0
solarLon = (279.696678+np.mod((36000.768925*julCen), 360.0))*3600.0
mEarth = 358.475844 + np.mod((35999.049750*julCen), 360.0)
earthCorr = (6910.1 - 17.2*julCen)*np.sin(mEarth*dtor) + 72.3*np.sin(2.0*mEarth*dtor)
solarLon = solarLon + earthCorr
# allow for the Venus perturbations using the mean anomaly of Venus MV
mVenus = 212.603219 +np.mod((58517.803875*julCen), 360.0)
venusCorr = 4.8 * np.cos((299.1017 + mVenus - mEarth)*dtor) + \
5.5 * np.cos((148.3133 + 2.0*mVenus - 2.0*mEarth )*dtor) + \
2.5 * np.cos((315.9433 + 2.0*mVenus - 3.0*mEarth )*dtor) + \
1.6 * np.cos((345.2533 + 3.0*mVenus - 4.0*mEarth )*dtor) + \
1.0 * np.cos((318.15 + 3.0*mVenus - 5.0*mEarth )*dtor)
solarLon = solarLon + venusCorr
mMars = 319.529425 + np.mod(( 19139.858500*julCen), 360.0)
marsCorr = 2.0*np.cos((343.8883 - 2.0*mMars + 2.0*mEarth)*dtor ) + \
1.8*np.cos((200.4017 - 2.0*mMars + mEarth)*dtor)
solarLon = solarLon + marsCorr
mJup = 225.328328 + np.mod(( 3034.6920239*julCen), 360.0)
jupCorr = 7.2*np.cos((179.5317 - mJup + mEarth)*dtor) + \
2.6*np.cos((263.2167 - mJup)*dtor) + \
2.7*np.cos(( 87.1450 - 2.0*mJup + 2.0*mEarth)*dtor) + \
1.6*np.cos((109.4933 - 2.0*mJup + mEarth)*dtor)
solarLon = solarLon + jupCorr
dMoon = 350.7376814 + np.mod((445267.11422*julCen),360.0)
moonCorr = 6.5*np.sin(dMoon*dtor)
solarLon = solarLon + moonCorr
longTerm = 6.4*np.sin((231.19 + 20.20*julCen)*dtor)
solarLon = solarLon + longTerm
solarLon = np.mod((solarLon + 2592000.0),1296000.0)
longMed = solarLon/3600.0
solarLon = solarLon - 20.5
# Allow for Nutation using the longitude of the Moons mean node OMEGA
omega = 259.183275 - np.mod(( 1934.142008*julCen),360.0)
solarLon = solarLon - 17.2*np.sin(omega*dtor)
oblt = 23.452294 - 0.0130125*julCen + (9.2*np.cos(omega*dtor))/3600.0
solarLon = solarLon/3600.0
ra = np.mod(np.arctan2(np.sin(solarLon*dtor)*np.cos(oblt*dtor),np.cos(solarLon*dtor)),2*np.pi)
dec = np.arcsin(np.sin(solarLon*dtor)*np.sin(oblt*dtor))
ra = (ra/dtor)/15.0
dec = dec/dtor
return [ra,dec]