##// END OF EJS Templates
Improve abs pattern views, templates and plots....
Juan C. Espinoza -
r180:d4783015f56a
parent child
Show More
1 NO CONTENT: new file 100644, binary diff hidden
@@ -1,25 +1,11
1 1 {% load static %}
2 2 {% load bootstrap3 %}
3 3 {% load main_tags %}
4 4
5 5 {% block content %}
6 <style>
7 </style>
8 6
9 7 <div id="PictureOverJRODown" style="float: right">
10 <img id="imgMainDown" src="{% url 'url_plot_down_beam' beam.abs_conf.id beam.id %}" alt="Error in Parameters" style="width:360px;height:270px;">
11 <img id="imgLoaderDown" src="{% static 'images/loading_loading.gif' %}" alt="Error in Parameters" width="50" height="50" align="left">
12
8 <img id="imgMainDown" src="{% url 'url_plot_beam' beam.abs_conf.id beam.id 'down' %}" alt="Error ploting..." style="width:360px;height:360px; background-image: url({% static 'images/loader.gif' %});background-repeat: no-repeat;background-position: 50% 50%;">
13 9 </div>
14 10
15 <script>
16
17 $('#imgMainDown').hide();
18 $('#imgLoaderDown').show();
19 $('#imgMainDown').load(function(){
20 $('#imgLoaderDown').hide();
21 $('#imgMainDown').show();
22 });
23 //window.onload = function () { alert("It's loaded!") }
24 </script>
25 11 {% endblock %}
@@ -1,54 +1,54
1 1 {% extends "dev_conf.html" %}
2 2 {% load static %}
3 3 {% load bootstrap3 %}
4 4 {% load main_tags %}
5 5
6 6 {% block content %}
7 7 <style>
8 8
9 9 </style>
10 10
11 11
12 12
13 13 {% if abs_beams %}
14 14 <div>
15 15 <h4>Beams:</h4>
16 16
17 17 <div class="container">
18 18 <div class="btn-group">
19 19 {% for abs_beam in abs_beams %}
20 20 <button id="bt_beam{{ forloop.counter }}" type="button" class="btn btn-default">{{ forloop.counter }}</button>
21 21 {% endfor %}
22 22 </div>
23 23 </div>
24 24
25 25
26 26 </div>
27 27 <br>
28 28
29 29 {% if beam %}
30 30 {% include "abs_pattern.html" %}
31 31 {% endif %}
32 32
33 33
34 34 {% else %}
35 35 <div>
36 36 <h4>Beams:</h4>
37 37 <p style="color:#b4bcc2; margin-left: 5%;"><i>No Beams...</i></p>
38 38 </div>
39 39 {% endif %}
40 40
41 41
42 42 <script>
43 43 {% for abs_beam in abs_beams %}
44 44 $("#bt_beam{{ forloop.counter }}").click(function() {
45 document.location = "{% url 'url_plot_abs_pattern' abs_beam.abs_conf.id abs_beam.id %}";
45 document.location = "{% url 'url_plot_abs_patterns' abs_beam.abs_conf.id abs_beam.id %}";
46 46 });
47 47 {% endfor %}
48 48 //function ChangeColor() {
49 49 // document.getElementById("button_1").style.backgroundColor = "#2c3e50";
50 50 // document.getElementById("button_1").style.color = "#ecf0f1";
51 51 //}
52 52 </script>
53 53
54 54 {% endblock %}
@@ -1,25 +1,11
1 1 {% load static %}
2 2 {% load bootstrap3 %}
3 3 {% load main_tags %}
4 4
5 5 {% block content %}
6 <style>
7 </style>
8 6
9 7 <div id="PictureOverJROUp" style="float: right">
10 <img id="imgMain" src="{% url 'url_plot_up_beam' beam.abs_conf.id beam.id %}" alt="Error in Parameters" style="width:360px;height:270px;">
11 <img id="imgLoader" src="{% static 'images/loading_loading.gif' %}" alt="Error in Parameters" width="50" height="50">
12
8 <img id="imgMain" src="{% url 'url_plot_beam' beam.abs_conf.id beam.id 'up' %}" alt="Error ploting..." style="width:360px;height:360px; background-image: url({% static 'images/loader.gif' %});background-repeat: no-repeat;background-position: 50% 50%;">
13 9 </div>
14 10
15 <script>
16
17 $('#imgMain').hide();
18 $('#imgLoader').show();
19 $('#imgMain').load(function(){
20 $('#imgLoader').hide();
21 $('#imgMain').show();
22 });
23
24 </script>
25 11 {% endblock %}
@@ -1,18 +1,17
1 1 from django.conf.urls import url
2 2
3 3 from apps.abs import views
4 4
5 5 urlpatterns = (
6 6 url(r'^(?P<id_conf>-?\d+)/$', views.abs_conf, name='url_abs_conf'),
7 7 url(r'^(?P<id_conf>-?\d+)/edit/$', views.abs_conf_edit, name='url_edit_abs_conf'),
8 8 #url(r'^(?P<id_conf>-?\d+)/read/$', views.dev_conf_read, name='url_read_abs_conf'),
9 9 #url(r'^(?P<id_conf>-?\d+)/import/$', views.dev_conf_import, name='url_import_abs_conf'),
10 10 #url(r'^(?P<id_conf>-?\d+)/export/$', views.dev_conf_export, name='url_export_abs_conf'),
11 11 url(r'^(?P<id_conf>-?\d+)/plot/$', views.plot_patterns, name='url_plot_abs_patterns'),
12 url(r'^(?P<id_conf>-?\d+)/plot/(?P<id_beam>-?\d+)/$', views.plot_pattern, name='url_plot_abs_pattern'),
13 url(r'^(?P<id_conf>-?\d+)/plot_up_beam/(?P<id_beam>-?\d+)/$', views.plot_uppattern, name='url_plot_up_beam'),
14 url(r'^(?P<id_conf>-?\d+)/plot_down_beam/(?P<id_beam>-?\d+)/$', views.plot_downpattern, name='url_plot_down_beam'),
12 url(r'^(?P<id_conf>-?\d+)/plot/(?P<id_beam>-?\d+)/$', views.plot_patterns, name='url_plot_abs_patterns'),
13 url(r'^(?P<id_conf>-?\d+)/plot/(?P<id_beam>-?\d+)/(?P<antenna>[\w\-]+)/pattern.png$', views.plot_pattern, name='url_plot_beam'),
15 14 url(r'^(?P<id_conf>-?\d+)/add_beam/$', views.add_beam, name='url_add_abs_beam'),
16 15 url(r'^(?P<id_conf>-?\d+)/beam/(?P<id_beam>-?\d+)/delete/$', views.remove_beam, name='url_remove_abs_beam'),
17 16 url(r'^(?P<id_conf>-?\d+)/beam/(?P<id_beam>-?\d+)/edit/$', views.edit_beam, name='url_edit_abs_beam'),
18 17 )
@@ -1,51 +1,53
1 1 """
2 2 The GRAPHICS_MISC.py module gathers classes and/or functions useful for generation of plots.
3 3
4 4 MODULES CALLED:
5 5 NUMPY, OS
6 6
7 7 MODIFICATION HISTORY:
8 8 Created by Ing. Freddy Galindo (frederickgalindo@gmail.com). ROJ, 13 August 2009.
9 9 """
10 10
11 11 import os
12 12 import numpy
13 13 import sys
14 14
15 15
16 16 class ColorTable:
17 17 def __init__(self,table=1,filepath=None):
18 18 self.table = table
19 19 #set to path for data folder, file: col_koki.dat
20 20 if filepath==None:
21 filepath= './data/'
21 filepath= './apps/abs/utils/data/'
22 22 self.filepath = filepath
23 23
24 24 def readTable(self):
25 25 if self.table>0:
26 26 if self.table==1:
27 f = open(os.path.join(self.filepath,'col_koki.dat'),'rb')
27
28 f = open(os.path.join(self.filepath, './col_koki.dat') ,'rb')
29
28 30
29 31 #f = open('./col_koki.dat','rb')
30 32
31 33 # Reading SkyNoise Power (lineal scale)
32 34 blue = numpy.fromfile(f,numpy.dtype([('var','b')]),256)
33 35 blue = numpy.int32(blue['var'])
34 36 val = numpy.where(blue<0)
35 37 if val[0].size:blue[val] = blue[val] + numpy.int32(256)
36 38
37 39 green = numpy.fromfile(f,numpy.dtype([('var','b')]),256)
38 40 green = numpy.int32(green['var'])
39 41 val = numpy.where(green<0)
40 42 if val[0].size:green[val] = green[val] + numpy.int32(256)
41 43
42 44 red = numpy.fromfile(f,numpy.dtype([('var','b')]),256)
43 45 red = numpy.int32(red['var'])
44 46 val = numpy.where(red<0)
45 47 if val[0].size:red[val] = red[val] + numpy.int32(256)
46 48
47 49 f.close()
48 50
49 51 colortable = numpy.array([red/255.,green/255.,blue/255.])
50 52
51 53 return colortable
@@ -1,563 +1,621
1 1 """
2 2 The module GRAPHICS_OVERJRO.py gathers classes or/and functions to create graphics from OVER-JRO
3 3 project (e.g. antenna patterns, skynoise, ...).
4 4
5 5 MODULES CALLED:
6 6 TIME, NUMPY, MATPLOTLIB, TIMETOOLS
7 7
8 8 MODIFICATION HISTORY:
9 9 Created by Ing. Freddy Galindo (frederickgalindo@gmail.com). ROJ Oct 18, 2009.
10 10 """
11 11
12 12 import time
13 13 import numpy
14 14 import sys
15 15 import os
16 16
17 17 # set HOME environment variable to a directory the httpd server can write to
18 18 #os.environ[ 'HOME' ] = '/usr/local/www/htdocs/overJro/tempReports'
19 19 #os.environ[ 'HOME' ] = '/home/dsuarez/Pictures'
20 20 #os.environ[ 'HOME' ] = '/tmp/'
21 21 import matplotlib
22 22 #if ide==1:
23 23 # matplotlib.use('Qt4Agg')
24 24 #elif ide==2:
25 25 # matplotlib.use("Agg")
26 26 #else:
27 27 # matplotlib.use('TKAgg')
28 28 #matplotlib.use("Agg")
29 29 #matplotlib.interactive(1)
30 30 import matplotlib.pyplot
31 31 #import Numeric
32 32 #import scipy
33 33 import scipy.interpolate
34 34
35 35 import Astro_Coords
36 36 import TimeTools
37 37 import Graphics_Miscens
38 38
39 39 import Misc_Routines
40 40
41 41 class AntPatternPlot:
42 42 def __init__(self):
43 43 """
44 44 AntPatternPlot creates an object to call methods to plot the antenna pattern.
45 45
46 46 Modification History
47 47 --------------------
48 48 Created by Freddy Galindo, ROJ, 06 October 2009.
49 49 """
50 self.figure = None
51 pass
52 50
53 def contPattern(self,iplot=0,gpath='',filename='',mesg='',amp=None ,x=None ,y=None ,getCut=None,title=''):
51 self.fig = matplotlib.pyplot.figure(figsize=(8,8), facecolor='white')
52 self.ax = self.fig.add_subplot(111)
53
54 def contPattern(self,iplot=0,gpath='',filename='',mesg='',amp=None ,x=None ,y=None ,getCut=None,title='', save=True):
54 55 """
55 56 contPattern plots a contour map of the antenna pattern.
56 57
57 58 Parameters
58 59 ----------
59 60 iplot = A integer to specify if the plot is the first, second, ... The default va-
60 61 lue is 0.
61 62
62 63 Examples
63 64 --------
64 65 >> Over_Jro.JroPattern(pattern=2).contPattern()
65 66
66 67 Modification history
67 68 --------------------
68 69 Converted to Python by Freddy R. Galindo, ROJ, 06 October 2009.
69 70 """
70 71
71 72 if getCut == 1:
72 73 return
73 74
74 75 xmax = numpy.max(x)
75 76 xmin = numpy.min(x)
76 77 ymax = numpy.max(y)
77 78 ymin = numpy.min(y)
78 79
79 80 levels = numpy.array([1e-3,1e-2,1e-1,0.5,1.0])
80 81 tmp = numpy.round(10*numpy.log10(levels),decimals=1)
81 82 labels = range(5)
82 83 for i in numpy.arange(5):labels[i] = str(numpy.int(tmp[i]))
83 84
84 if iplot==0:
85 xsize = 8.0
86 if matplotlib.get_backend()=='QT4Agg':xsize = 6.0
87 ysize = 8.0
88 self.figure = matplotlib.pyplot.figure(num=2,figsize=(xsize,ysize))
89 matplotlib.pyplot.clf()
90 85
91 86 colors = ((0,0,1.),(0,170/255.,0),(127/255.,1.,0),(1.,109/255.,0),(128/255.,0,0))
92 CS = matplotlib.pyplot.contour(x,y,amp.transpose(),levels,colors=colors)
87 CS = self.ax.contour(x,y,amp.transpose(),levels,colors=colors)
93 88 fmt = {}
94 for l,s in zip(CS.levels,labels):fmt[l] = s
95
96 matplotlib.pyplot.annotate('Ng',xy=(-0.05,1.04),xytext=(0.01,0.962),xycoords='axes fraction',arrowprops=dict(facecolor='black', width=1.,shrink=0.2),fontsize=15.)
97 matplotlib.pyplot.annotate(mesg,xy=(0,0),xytext=(0.01,0.01),xycoords='figure fraction')
98 matplotlib.pyplot.clabel(CS,CS.levels,inline=True,fmt=fmt,fontsize=10)
99 matplotlib.pyplot.xlim(xmin,xmax)
100 matplotlib.pyplot.ylim(ymin,ymax)
101 matplotlib.pyplot.title("Total Pattern" + title)
102 matplotlib.pyplot.xlabel("West to South")
103 matplotlib.pyplot.ylabel("West to North")
104 matplotlib.pyplot.grid(True)
105 print "SAVE_FIG"
106 print gpath
107 print filename
89 for l,s in zip(CS.levels,labels):
90 fmt[l] = s
91
92 self.ax.annotate('Ng',xy=(-0.05,1.04),xytext=(0.01,0.962),xycoords='axes fraction',arrowprops=dict(facecolor='black', width=1.,shrink=0.2),fontsize=15.)
93 self.ax.annotate(mesg,xy=(0,0),xytext=(0.01,0.01),xycoords='figure fraction')
94 self.ax.clabel(CS,CS.levels,inline=True,fmt=fmt,fontsize=10)
95 self.ax.set_xlim(xmin,xmax)
96 self.ax.set_ylim(ymin,ymax)
97 self.ax.set_title("Total Pattern: " + title)
98 self.ax.set_xlabel("West to South")
99 self.ax.set_ylabel("West to North")
100 self.ax.grid(True)
101
102 if save:
108 103 save_fig = os.path.join(gpath,filename)
109 matplotlib.pyplot.savefig(save_fig,format='png')
104 self.fig.savefig(save_fig,format='png')
105
106
107
108 def close(self):
109
110 matplotlib.pyplot.close(self.fig)
110 111
111 def plotRaDec(self,gpath=None,filename=None,jd=2452640.5,ra_obs=None,xg=None,yg=None,x=None,y=None):
112 def plotRaDec(self,gpath=None,filename=None,jd=2452640.5,ra_obs=None,xg=None,yg=None,x=None,y=None, save=True):
112 113 """
113 114 plotRaDec draws right ascension and declination lines on a JRO plane. This function
114 115 must call after conPattern.
115 116
116 117 Parameters
117 118 ----------
118 119 jd = A scalar giving the Julian date.
119 120 ra_obs = Scalar giving the right ascension of the observatory.
120 121 xg = A 3-element array to specify ..
121 122 yg = A 3-element array to specify ..
122 123
123 124 Examples
124 125 --------
125 126 >> Over_Jro.JroPattern(pattern=2).contPattern()
126 127 >> Over_Jro.JroPattern(pattern=2).plotRaDec(jd=jd,ra_obs=ra_obs,xg=xg,yg=yg)
127 128
128 129 Modification history
129 130 --------------------
130 131 Converted to Python by Freddy R. Galindo, ROJ, 06 October 2009.
131 132 """
132 133
133 134 # Finding RA of observatory for a specific date
134 if ra_obs==None:ra_obs = numpy.array([23.37060849])
135 if xg==None:xg = numpy.array([0.62918474,-0.77725579,0.])
136 if yg==None:yg = numpy.array([0.77700346,0.62898048,0.02547905])
135 if ra_obs is None:ra_obs = numpy.array([23.37060849])
136 if xg is None:xg = numpy.array([0.62918474,-0.77725579,0.])
137 if yg is None:yg = numpy.array([0.77700346,0.62898048,0.02547905])
137 138
138 139 # Getting HA and DEC axes
139 140 mindec = -28; maxdec = 4; incdec = 2.
140 141 ndec = numpy.int((maxdec - mindec)/incdec) + 1
141 142
142 143 minha = -20; maxha = 20; incha = 2.
143 144 nha = numpy.int((maxha - minha)/incha) + 1
144 145
145 mcosx = numpy.zeros((nha,ndec))
146 mcosy = numpy.zeros((nha,ndec))
146 #mcosx = numpy.zeros((nha,ndec))
147 #mcosy = numpy.zeros((nha,ndec))
147 148
148 149 ha_axes = numpy.reshape(numpy.arange(nha)*incha + minha,(nha,1))
149 150 ones_dec = numpy.reshape(numpy.zeros(ndec) + 1,(ndec,1))
150 151 ha_axes = numpy.dot(ha_axes,ones_dec.transpose())
151 152 ha_axes2 = numpy.array(ra_obs - ha_axes)
152 153
153 154 dec_axes = numpy.reshape(numpy.arange(ndec)*incdec + mindec,(ndec,1))
154 155 ones_ra = numpy.reshape(numpy.zeros(nha) + 1,(nha,1))
155 156 dec_axes = numpy.dot(ones_ra,dec_axes.transpose())
156 157 dec_axes2 = numpy.array(dec_axes)
157 158
158 159 ObjHor = Astro_Coords.Equatorial(ha_axes2,dec_axes2,jd)
159 160 [alt,az,ha] = ObjHor.change2AltAz()
160 161
161 162 z = numpy.transpose(alt)*Misc_Routines.CoFactors.d2r ; z = z.flatten()
162 163 az = numpy.transpose(az)*Misc_Routines.CoFactors.d2r ; az = az.flatten()
163 164
164 165 vect = numpy.array([numpy.cos(z)*numpy.sin(az),numpy.cos(z)*numpy.cos(az),numpy.sin(z)])
165 166
166 167 xg = numpy.atleast_2d(xg)
167 168 dcosx = numpy.array(numpy.dot(xg,vect))
168 169 yg = numpy.atleast_2d(yg)
169 170 dcosy = numpy.array(numpy.dot(yg,vect))
170 171
171 172 mcosx = dcosx.reshape(ndec,nha)
172 173 mcosy = dcosy.reshape(ndec,nha)
173 174
174 175 # Defining NAN for points outof limits.
175 176 xmax = numpy.max(x)
176 177 xmin = numpy.min(x)
177 178 ymax = numpy.max(y)
178 179 ymin = numpy.min(y)
179 180
180 181 factor = 1.3
181 182 noval = numpy.where((mcosx>(xmax*factor)) | (mcosx<(xmin*factor)))
182 183 if noval[0].size>0:mcosx[noval] = numpy.nan
183 184 noval = numpy.where((mcosy>(ymax*factor)) | (mcosy<(ymin*factor)))
184 185 if noval[0].size>0:mcosy[noval] = numpy.nan
185 186
186 187 # Plotting HA and declination grid.
187 188 iha0 = numpy.int((0 - minha)/incha)
188 189 idec0 = numpy.int((-14 - mindec)/incdec)
189 190
190 191 colorgrid = (1.,109/255.,0)
191 matplotlib.pyplot.plot(mcosx.transpose(),mcosy.transpose(),color=colorgrid,linestyle='--')
192 self.ax.plot(mcosx.transpose(),mcosy.transpose(),color=colorgrid,linestyle='--')
192 193 for idec in numpy.arange(ndec):
193 194 if idec != idec0:
194 195 valx = (mcosx[idec,iha0]<=xmax) & (mcosx[idec,iha0]>=xmin)
195 196 valy = (mcosy[idec,iha0]<=ymax) & (mcosy[idec,iha0]>=ymin)
196 197 if valx & valy:
197 198 text = str(numpy.int(mindec + incdec*idec))+'$^o$'
198 matplotlib.pyplot.text(mcosx[idec,iha0],mcosy[idec,iha0],text)
199 self.ax.text(mcosx[idec,iha0],mcosy[idec,iha0],text)
199 200
200 201 matplotlib.pyplot.plot(mcosx,mcosy,color=colorgrid,linestyle='--')
201 202 for iha in numpy.arange(nha):
202 203 if iha != iha0:
203 204 valx = (mcosx[idec0,iha]<=xmax) & (mcosx[idec0,iha]>=xmin)
204 205 valy = (mcosy[idec0,iha]<=ymax) & (mcosy[idec0,iha]>=ymin)
205 206 if valx & valy:
206 207 text = str(4*numpy.int(minha + incha*iha))+"'"
207 matplotlib.pyplot.text(mcosx[idec0,iha],mcosy[idec0,iha],text)
208 self.ax.text(mcosx[idec0,iha],mcosy[idec0,iha],text)
208 209
209 matplotlib.pyplot.xlim(xmin,xmax)
210 matplotlib.pyplot.ylim(ymin,ymax)
210 if save:
211 save_fig = os.path.join(gpath,filename)
212 matplotlib.pyplot.savefig(save_fig,format='png')
213
214
215 def plotBField(self,gpath,filename,dcos,alpha, nlon, nlat, dcosxrange, dcosyrange, heights, alpha_i, save=True):
216 """
217 plotBField draws the magnetic field in a directional cosines plot.
211 218
219 Parameters
220 ----------
221 dcos = An 4-dimensional array giving the directional cosines of the magnetic field
222 over the desired place.
223 alpha = An 3-dimensional array giving the angle of the magnetic field over the desi-
224 red place.
225 nlon = An integer to specify the number of elements per longitude.
226 nlat = An integer to specify the number of elements per latitude.
227 dcosxrange = A 2-element array giving the range of the directional cosines in the
228 "x" axis.
229 dcosyrange = A 2-element array giving the range of the directional cosines in the
230 "y" axis.
231 heights = An array giving the heights (km) where the magnetic field will be modeled By default the magnetic field will be computed at 100, 500 and 1000km.
232 alpha_i = Angle to interpolate the magnetic field.
233 Modification History
234 --------------------
235 Converted to Python by Freddy R. Galindo, ROJ, 07 October 2009.
236 """
237
238 handles = []
239 objects = []
240 colors = ['k','m','c','b','g','r','y']
241 marker = ['-+','-*','-D','-x','-s','->','-o','-^']
242
243 alpha_location = numpy.zeros((nlon,2,heights.size))
244
245 for ih in numpy.arange(heights.size):
246 alpha_location[:,0,ih] = dcos[:,0,ih,0]
247 for ilon in numpy.arange(nlon):
248 myx = (alpha[ilon,:,ih])[::-1]
249 myy = (dcos[ilon,:,ih,0])[::-1]
250 tck = scipy.interpolate.splrep(myx,myy,s=0)
251 mydcosx = scipy.interpolate.splev(alpha_i,tck,der=0)
252
253 myx = (alpha[ilon,:,ih])[::-1]
254 myy = (dcos[ilon,:,ih,1])[::-1]
255 tck = scipy.interpolate.splrep(myx,myy,s=0)
256 mydcosy = scipy.interpolate.splev(alpha_i,tck,der=0)
257 alpha_location[ilon,:,ih] = numpy.array([mydcosx, mydcosy])
258
259
260 ObjFig, = self.ax.plot(alpha_location[:,0,ih],alpha_location[:,1,ih],
261 marker[ih % 8],color=colors[numpy.int(ih/8)],ms=4.5,lw=0.5)
262 handles.append(ObjFig)
263 objects.append(numpy.str(heights[ih]) + ' km')
264
265 self.ax.legend(handles,objects,loc="lower right", numpoints=1, handlelength=0.3,
266 handletextpad=0.02, borderpad=0.3, labelspacing=0.1)
267
268 if save:
212 269 save_fig = os.path.join(gpath,filename)
213 270 matplotlib.pyplot.savefig(save_fig,format='png')
214 271
215 272
273
216 274 class BFieldPlot:
217 275 def __init__(self):
218 276 """
219 277 BFieldPlot creates an object for drawing magnetic Field lines over Jicamarca.
220 278
221 279 Modification History
222 280 --------------------
223 281 Created by Freddy Galindo, ROJ, 07 October 2009.
224 282 """
225 283
226 284 self.alpha_location = 1
227 285 # pass
228 286
229 287 def plotBField(self,gpath,filename,dcos,alpha, nlon, nlat, dcosxrange, dcosyrange, heights, alpha_i):
230 288 """
231 289 plotBField draws the magnetic field in a directional cosines plot.
232 290
233 291 Parameters
234 292 ----------
235 293 dcos = An 4-dimensional array giving the directional cosines of the magnetic field
236 294 over the desired place.
237 295 alpha = An 3-dimensional array giving the angle of the magnetic field over the desi-
238 296 red place.
239 297 nlon = An integer to specify the number of elements per longitude.
240 298 nlat = An integer to specify the number of elements per latitude.
241 299 dcosxrange = A 2-element array giving the range of the directional cosines in the
242 300 "x" axis.
243 301 dcosyrange = A 2-element array giving the range of the directional cosines in the
244 302 "y" axis.
245 303 heights = An array giving the heights (km) where the magnetic field will be modeled By default the magnetic field will be computed at 100, 500 and 1000km.
246 304 alpha_i = Angle to interpolate the magnetic field.
247 305 Modification History
248 306 --------------------
249 307 Converted to Python by Freddy R. Galindo, ROJ, 07 October 2009.
250 308 """
251 309
252 310 handles = []
253 311 objects = []
254 312 colors = ['k','m','c','b','g','r','y']
255 313 marker = ['-+','-*','-D','-x','-s','->','-o','-^']
256 314
257 315 alpha_location = numpy.zeros((nlon,2,heights.size))
258 316
259 317 for ih in numpy.arange(heights.size):
260 318 alpha_location[:,0,ih] = dcos[:,0,ih,0]
261 319 for ilon in numpy.arange(nlon):
262 320 myx = (alpha[ilon,:,ih])[::-1]
263 321 myy = (dcos[ilon,:,ih,0])[::-1]
264 322 tck = scipy.interpolate.splrep(myx,myy,s=0)
265 323 mydcosx = scipy.interpolate.splev(alpha_i,tck,der=0)
266 324
267 325 myx = (alpha[ilon,:,ih])[::-1]
268 326 myy = (dcos[ilon,:,ih,1])[::-1]
269 327 tck = scipy.interpolate.splrep(myx,myy,s=0)
270 328 mydcosy = scipy.interpolate.splev(alpha_i,tck,der=0)
271 329 alpha_location[ilon,:,ih] = numpy.array([mydcosx, mydcosy])
272 330
273 331
274 332 ObjFig, = matplotlib.pyplot.plot(alpha_location[:,0,ih],alpha_location[:,1,ih], \
275 333 marker[ih % 8],color=colors[numpy.int(ih/8)],ms=4.5,lw=0.5)
276 334 handles.append(ObjFig)
277 335 objects.append(numpy.str(heights[ih]) + ' km')
278 336
279 337 matplotlib.pyplot.xlim(dcosxrange[0],dcosxrange[1])
280 338 matplotlib.pyplot.ylim(dcosyrange[0],dcosyrange[1])
281 339
282 340 try:
283 341 ObjlegB = matplotlib.pyplot.legend(handles,objects,loc="lower right", numpoints=1, handlelength=0.3, \
284 342 handletextpad=0.02, borderpad=0.3, labelspacing=0.1)
285 343 except:
286 344 ObjlegB = matplotlib.pyplot.legend(handles,objects,loc=[0.01,0.75], numpoints=1, handlelength=0, \
287 345 pad=0.015, handletextsep=0.02,labelsep=0.01)
288 346
289 347 matplotlib.pyplot.setp(ObjlegB.get_texts(),fontsize='small')
290 348 matplotlib.pyplot.gca().add_artist(ObjlegB)
291 349
292 350 save_fig = os.path.join(gpath,filename)
293 351 matplotlib.pyplot.savefig(save_fig,format='png')
294 352 self.alpha_location = alpha_location
295 353
296 354
297 355 class CelestialObjectsPlot:
298 356 def __init__(self,jd,dec,tod,maxha_min,show_object=None):
299 357
300 358 self.jd = jd
301 359 self.dec = dec
302 360 self.tod = tod
303 361 self.maxha_min = maxha_min
304 362
305 363 if show_object==None:show_object=numpy.zeros(4)+2
306 364 self.show_object = show_object
307 365
308 366 self.dcosx_sun = 1
309 367 self.dcosy_sun = 1
310 368 self.ha_sun = 1
311 369 self.time_sun = 1
312 370
313 371 self.dcosx_moon = 1
314 372 self.dcosy_moon = 1
315 373 self.ha_moon = 1
316 374 self.time_moon = 1
317 375
318 376 self.dcosx_hydra = 1
319 377 self.dcosy_hydra = 1
320 378 self.ha_hydra = 1
321 379 self.time_hydra = 1
322 380
323 381 self.dcosx_galaxy = 1
324 382 self.dcosy_galaxy = 1
325 383 self.ha_galaxy = 1
326 384 self.time_galaxy = 1
327 385
328 386 def drawObject(self,glat,glon,xg,yg,dcosxrange,dcosyrange,gpath='',filename=''):
329 387
330 388 jd = self.jd
331 389 main_dec = self.dec
332 390 tod = self.tod
333 391 maxha_min = self.maxha_min
334 392
335 393 mesg = "Drawing celestial objects over Observatory"
336 394 # print mesg
337 395 # if textid!=None:textid.append(mesg)
338 396
339 397 maxlev = 24; minlev = 0; maxcol = 39; mincol = 10
340 398 handles = []
341 399 objects = ['$Sun$','$Moon$','$Hydra$','$Galaxy$']
342 400 marker = ['--^','--s','--*','--o']
343 401
344 402 # Getting RGB table to plot celestial object over Jicamarca
345 403 colortable = Graphics_Miscens.ColorTable(table=1).readTable()
346 404
347 405 for io in (numpy.arange(4)+1):
348 406 if self.show_object[io]!=0:
349 407 ObjBodies = Astro_Coords.CelestialBodies()
350 408 if io==1:
351 409 [ra,dec,sunlon,sunobliq] = ObjBodies.sunpos(jd)
352 410 elif io==2:
353 411 [ra,dec,dist,moonlon,moonlat] = ObjBodies.moonpos(jd)
354 412 elif io==3:
355 413 [ra,dec] = ObjBodies.hydrapos()
356 414 elif io==4:
357 415 [maxra,ra] = ObjBodies.skynoise_jro(dec_cut=main_dec)
358 416 ra = maxra*15.
359 417 dec = main_dec
360 418
361 419 ObjEq = Astro_Coords.Equatorial(ra,dec,jd,lat=glat,lon=glon)
362 420 [alt, az, ha] = ObjEq.change2AltAz()
363 421 vect = numpy.array([az,alt]).transpose()
364 422 vect = Misc_Routines.Vector(vect,direction=0).Polar2Rect()
365 423
366 424 dcosx = numpy.array(numpy.dot(vect,xg))
367 425 dcosy = numpy.array(numpy.dot(vect,yg))
368 426 wrap = numpy.where(ha>=180.)
369 427 if wrap[0].size>0:ha[wrap] = ha[wrap] - 360.
370 428
371 429 val = numpy.where((numpy.abs(ha))<=(maxha_min*0.25))
372 430 if val[0].size>2:
373 431 tod_1 = tod*1.
374 432 shift_1 = numpy.where(tod>12.)
375 433 tod_1[shift_1] = tod_1[shift_1] - 24.
376 434 tod_2 = tod*1.
377 435 shift_2 = numpy.where(tod<12.)
378 436 tod_2[shift_2] = tod_2[shift_2] + 24.
379 437
380 438 diff0 = numpy.nanmax(tod[val]) - numpy.nanmin(tod[val])
381 439 diff1 = numpy.nanmax(tod_1[val]) - numpy.nanmin(tod_1[val])
382 440 diff2 = numpy.nanmax(tod_2[val]) - numpy.nanmin(tod_2[val])
383 441
384 442 if ((diff0<=diff1) & (diff0<=diff2)):
385 443 tod_0 = tod
386 444 elif ((diff1<diff0) & (diff1<diff2)):
387 445 tod_0 = tod_1
388 446 else:
389 447 tod_0 = tod_2
390 448
391 449 if io==1:
392 450 self.dcosx_sun = dcosx[val]
393 451 self.dcosy_sun = dcosy[val]
394 452 self.ha_sun = ha[val]
395 453 self.time_sun = numpy.median(tod_0[val])
396 454 elif io==2:
397 455 self.dcosx_moon = dcosx[val]
398 456 self.dcosy_moon = dcosy[val]
399 457 self.ha_moon = ha[val]
400 458 self.time_moon = numpy.median(tod_0[val])
401 459 elif io==3:
402 460 self.dcosx_hydra = dcosx[val]
403 461 self.dcosy_hydra = dcosy[val]
404 462 self.ha_hydra = ha[val]
405 463 self.time_hydra = numpy.mean(tod_0[val])
406 464 elif io==4:
407 465 self.dcosx_galaxy = dcosx[val]
408 466 self.dcosy_galaxy = dcosy[val]
409 467 self.ha_galaxy = ha[val]
410 468 self.time_galaxy = numpy.mean(tod_0[val])
411 469
412 470 index = numpy.mean(tod_0[val]) - minlev
413 471 index = (index*(maxcol - mincol)/(maxlev - minlev)) + mincol
414 472 index = numpy.int(index)
415 473 figobjects, = matplotlib.pyplot.plot(dcosx[val],dcosy[val],marker[io-1],\
416 474 lw=1,ms=7,mew=0,color=tuple(colortable[:,index]))
417 475 handles.append(figobjects)
418 476
419 477 xmax = numpy.max(dcosxrange[1])
420 478 xmin = numpy.min(dcosxrange[0])
421 479 ymax = numpy.max(dcosyrange[1])
422 480 ymin = numpy.min(dcosyrange[0])
423 481 matplotlib.pyplot.xlim(xmin,xmax)
424 482 matplotlib.pyplot.ylim(ymin,ymax)
425 483
426 484 val = numpy.where(self.show_object[1:]>0)
427 485 objects = numpy.array(objects)
428 486 objects = list(objects[val])
429 487 try:
430 488 ObjlegC = matplotlib.pyplot.legend(handles,objects,loc="lower left", numpoints=1, handlelength=0.3, \
431 489 borderpad=0.3, handletextpad=0.02,labelspacing=0.1)
432 490 except:
433 491 ObjlegC = matplotlib.pyplot.legend(handles,objects,loc=[0.01,0.75], numpoints=1, handlelength=0, \
434 492 pad=0.015, handletextsep=0.02,labelsep=0.01)
435 493
436 494 matplotlib.pyplot.setp(ObjlegC.get_texts(),fontsize='small')
437 495 ObjlegC.isaxes = False
438 496 save_fig = os.path.join(gpath,filename)
439 497 matplotlib.pyplot.savefig(save_fig,format='png')
440 498
441 499
442 500 class PatternCutPlot:
443 501 def __init__(self,nsubplots):
444 502 self.nsubplots = nsubplots
445 503
446 504 self.fig = None
447 505
448 506 self.__plot_width = 8
449 507
450 508 if self.nsubplots == 5:
451 509 self.__plot_height = 11
452 510
453 511 if self.nsubplots == 4:
454 512 self.__plot_height = 9
455 513
456 514 if self.nsubplots == 3:
457 515 self.__plot_height = 7
458 516
459 517 if self.nsubplots == 2:
460 518 self.__plot_height = 5
461 519
462 520 if self.nsubplots == 1:
463 521 self.__plot_height = 3
464 522
465 523 self.fig = matplotlib.pyplot.figure(num = 4,figsize = (self.__plot_width, self.__plot_height))
466 524
467 525 if self.nsubplots < 5:
468 526 self.__height_inch = 1.1 #altura de los subplots (pulgadas)
469 527 top_inch = 1.5/2.7 #espacio entre el primer subplot y el limite superior del plot
470 528 self.__vspace_plot_inch = 1.0#1.5/2 # espacio vertical entre subplots
471 529 self.__left = 0.1
472 530 else:
473 531 self.__height_inch = 1.1 #altura de los subplots (pulgadas)
474 532 top_inch = 1.5/2.7 #espacio entre el primer subplot y el limite superior del plot
475 533 self.__vspace_plot_inch = 1.0 # espacio vertical entre subplots
476 534 self.__left = 0.1
477 535
478 536 self.__bottom_inch = self.__plot_height - (self.__height_inch + top_inch)
479 537 self.__height = self.__height_inch/self.__plot_height
480 538
481 539 self.__width = 0.8
482 540
483 541
484 542 def drawCut(self,io,patterns,npatterns,ha,otitle,subtitle,ptitle):
485 543
486 544 t_cuts = ['B','Sun','Moon','Hydra','Galaxy']
487 545 self.__bottom = self.__bottom_inch/self.__plot_height
488 546
489 547
490 548 subp = self.fig.add_axes([self.__left,self.__bottom,self.__width,self.__height])
491 549
492 550 on_axis_angle = -4.65562
493 551 for icut in numpy.arange(npatterns):
494 552 # Getting Antenna cut.
495 553 pattern = patterns[icut]
496 554 power = numpy.abs(pattern/numpy.nanmax(pattern))
497 555 max_power_db = numpy.round(10.*numpy.log10(numpy.nanmax(pattern)),2)
498 556
499 557 bval = numpy.where(power[:,0]==numpy.nanmax(power))
500 558 beta = -0.25*(ha[bval[0]] + on_axis_angle)
501 559 # print 'Angle (deg): '+"%f"%(beta)
502 560
503 561 subp.plot(ha,power)
504 562
505 563
506 564 xmax = numpy.max(numpy.nanmin(ha))
507 565 xmin = numpy.min(numpy.nanmax(ha))
508 566 ymax = numpy.max(1)
509 567 ymin = numpy.min(0)
510 568
511 569
512 570 subp.set_xlim(xmin, xmax)
513 571
514 572 subp.set_ylim(ymin, ymax)
515 573
516 574 subp.set_title(otitle + ' ' + ptitle,size="medium")
517 575
518 576 subp.text(0.5, 1.26,subtitle[0],
519 577 horizontalalignment='center',
520 578 verticalalignment='center',
521 579 transform = subp.transAxes)
522 580
523 581 xlabels = subp.get_xticks()
524 582
525 583 subp.set_xticklabels(xlabels,size="small")
526 584
527 585 ylabels = subp.get_yticks()
528 586
529 587 subp.set_yticklabels(ylabels,size="small")
530 588
531 589 subp.set_xlabel('Hour angle (min) (+ve to West)',size="small")
532 590
533 591 subp.set_ylabel("Power [Max: " + str(max_power_db) + ' dB]',size="small")
534 592
535 593 subp.grid()
536 594
537 595
538 596 self.__bottom_inch = self.__bottom_inch - (self.__height_inch + self.__vspace_plot_inch)
539 597
540 598
541 599 class SkyNoisePlot:
542 600 def __init__(self,date,powr,time,time_lst):
543 601 """
544 602 SkyNoisePlot class creates an object which represents the SkyNoise Object to genera-
545 603 te a SkyNoise map.
546 604
547 605 Parameters
548 606 ----------
549 607 date = A List of 3 elements to define the desired date ([year, month, day]).
550 608 powr = An array giving the SkyNoise power for the desired time.
551 609 time = An array giving the number of seconds since 1970 to the desired time.
552 610 time_lst = Set this input to an array to define the Local Sidereal Time of the desi-
553 611 red time.
554 612
555 613 Modification History
556 614 --------------------
557 615 Created by Freddy Galindo, ROJ, 18 October 2009.
558 616 """
559 617
560 618 self.date = date
561 619 self.powr = powr
562 620 self.time = time
563 621 self.time_lst = time_lst
@@ -1,1632 +1,1754
1 1 #!/usr/bin/python
2 2
3 3
4 4 import sys, os, os.path
5 5 import traceback
6 6 import cgi, Cookie
7 7 import time, datetime
8 8 import types
9 9 import numpy
10 10 import numpy.fft
11 11 import scipy.linalg
12 12 import scipy.special
13 from StringIO import StringIO
13 14 #import Numeric
14 15
15 16 import Misc_Routines
16 17 import TimeTools
17 18 import JroAntSetup
18 19 import Graphics_OverJro
19 20 import Astro_Coords
20 21
21 22 class JroPattern():
22 23 def __init__(self,pattern=0,path=None,filename=None,nptsx=101,nptsy=101,maxphi=5,fftopt=0, \
23 getcut=0,dcosx=None,dcosy=None,eomwl=6,airwl=4):
24 getcut=0,dcosx=None,dcosy=None,eomwl=6,airwl=4, **kwargs):
24 25 """
25 26 JroPattern class creates an object to represent the useful parameters for beam mode-
26 27 lling of the Jicamarca VHF radar.
27 28
28 29 Parameters
29 30 ----------
30 31 pattern = An integer (See JroAntSetup to know the available values) to load a prede-
31 32 fined configuration. The default value is 0. To use a user-defined configuration
32 33 pattern must be None.
33 34 path = A string giving the directory that contains the user-configuration file. PATH
34 35 will work if pattern is None.
35 36 filename = A string giving the name of the user-configuration file. FILENAME will
36 37 work if pattern is None.
37 38 nptsx = A scalar to specify the number of points used to define the angular resolu-
38 39 tion in the "x" axis. The default value is 101.
39 40 nptsy = A scalar to specify the number of points used to define the angular resolu-
40 41 tion in the "x" axis. The default value is 101.
41 42 maxphi = A scalar giving the maximum (absolute) angle (in degree) to model the ante-
42 43 nna pattern. The default value is 5 degrees.
43 44 fftopt = Set this input to 1 to model the beam using FFT. To model using antenna
44 45 theory set to 0 (default value).
45 46 getcut = Set to 1 to show an antenna cut instead of a contour plot of itself (set to
46 47 0). The defautl value is 0.
47 48 dcosx = An array giving the directional cosines for the x-axis. DCOSX will work if
48 49 getcut is actived.
49 50 dcosy = An array giving the directional cosines for the y-axis. DCOSY will work if
50 51 getcut is actived.
51 52 eomwl = A scalar giving the radar wavelength. The default value is 6m (50 MHZ).
52 53 airwl = Set this input to float (or intger) to specify the wavelength (in meters) of
53 54 the transmitted EOM wave in the air. The default value is 4m.
54 55
55 56 Modification History
56 57 --------------------
57 58 Converted to Object-oriented Programming by Freddy Galindo, ROJ, 20 September 2009.
58 59 """
59 60
60 61
61 62
62 63 # Getting antenna configuration.
64 if filename:
63 65 setup = JroAntSetup.ReturnSetup(path=path,filename=filename,pattern=pattern)
64 66
65 67 ues = setup["ues"]
66 68 phase = setup["phase"]
67 69 gaintx = setup["gaintx"]
68 70 gainrx = setup["gainrx"]
69 71 justrx = setup["justrx"]
72 self.title = setup["title"]
73 else:
74 ues = kwargs["ues"]
75 phase = kwargs["phases"]
76 gaintx = kwargs["gain_tx"]
77 gainrx = kwargs["gain_rx"]
78 justrx = kwargs["just_rx"]
79 self.title = kwargs.get("title", "JRO Pattern")
70 80
71 81 # Defining attributes for JroPattern class.
72 82 # Antenna configuration
83
73 84 self.uestx = ues
74 85 self.phasetx = phase
75 86 self.gaintx = gaintx
76 87 self.uesrx = ues
77 88 self.phaserx = phase
78 89 self.gainrx = gainrx
79 90 self.justrx = justrx
80 91
81 92 # Pattern resolution & method to model
82 93 self.maxphi = maxphi
83 94 self.nptsx = nptsx
84 95 self.nptsy = nptsy
85 96 self.fftopt = fftopt
86 97
87 98 # To get a cut of the pattern.
88 99 self.getcut = getcut
89 100
90 101 maxdcos = numpy.sin(maxphi*Misc_Routines.CoFactors.d2r)
91 102 if dcosx==None:dcosx = ((numpy.arange(nptsx,dtype=float)/(nptsx-1))-0.5)*2*maxdcos
92 103 if dcosy==None:dcosy = ((numpy.arange(nptsy,dtype=float)/(nptsy-1))-0.5)*2*maxdcos
93 104 self.dcosx = dcosx
94 105 self.dcosy = dcosy
95 106 self.nx = dcosx.size
96 107 self.ny = dcosy.size*(getcut==0) + (getcut==1)
97 108
98 109 self.eomwl = eomwl
99 110 self.airwl = airwl
100 111
101 112 self.kk = 2.*numpy.pi/eomwl
102 113
103 114 self.pattern = None
104 115 self.meanpos = None
105 116 self.norpattern = None
106 117 self.maxpattern = None
107 118
108 self.title = setup["title"]
119
109 120
110 121 self.getPattern()
111 122
112 123 def getPattern(self):
113 124 """
114 getpattern method returns the modelled total antenna pattern and its mean position.
125 getpattern method returns the modeled total antenna pattern and its mean position.
115 126
116 127 Return
117 128 ------
118 129 pattern = An array giving the Modelled antenna pattern.
119 130 mean_pos = A 2-elements array giving the mean position of the main beam.
120 131
121 132 Examples
122 133 --------
123 134 >> [pattern, mean_pos] = JroPattern(pattern=2).getPattern()
124 135 >> print meanpos
125 136 [ 8.08728085e-14 -4.78193873e-14]
126 137
127 138 Modification history
128 139 --------------------
129 140 Developed by Jorge L. Chau.
130 141 Converted to Python by Freddy R. Galindo, ROJ, 20 September 2009.
131 142 """
132 143
133 144 if (self.fftopt>0) and (self.getcut>0):
134 145 #print "Conflict bewteen fftopt and getcut"
135 146 #print "To get a cut of the antenna pattern uses ffopt=0"
136 147 return None, None
137 148
138 149 if (self.fftopt==0):
139 150 # Getting antenna pattern using the array method
140 151 self.pattern = self.__usingArray(rx=1)
141 152 if (self.justrx==0):self.pattern = self.pattern*self.__usingArray(rx=0)
142 153
143 154 elif (self.fftopt>0):
144 155 # Getting antenna pattern using FFT method
145 156 self.pattern = self.__usingFFT(rx=1)
146 157 if (self.justrx==0):self.pattern = self.pattern*self.__usingFFT(rx=0)
147 158
148 159 self.maxpattern = numpy.nanmax(self.pattern)
149 160 self.norpattern = self.pattern/self.maxpattern
150 161 if self.getcut==0:self.__getBeamPars()
151 162
152 163 def __usingArray(self,rx):
153 164 """
154 165 __usingArray method returns the Jicamarca antenna pattern computed using array model
155 166
156 167 pattern = dipolepattern x modulepattern
157 168
158 169 Parameters
159 170 ----------
160 171 rx = Set to 1 to use the Rx information. Otherwise set to 0 for Tx.
161 172
162 173 Return
163 174 ------
164 175 pattern = An array giving the modelled antenna pattern using the array model.
165 176
166 177 Modification history
167 178 --------------------
168 179 Developed by Jorge L. Chau.
169 180 Converted to Python by Freddy R. Galindo, ROJ, 20 September 2009.
170 181 """
171 182
172 183 if rx==1:
173 184 ues = self.uesrx
174 185 phase = self.phaserx
175 186 gain = self.gainrx
176 187 elif rx==0:
177 188 ues = self.uestx
178 189 phase = self.phasetx
179 190 gain = self.gaintx
180 191
181 192 ues = ues*360./self.airwl
182 193 phase = phase*360./self.airwl
183 194
184 195 for ii in range(4):
185 196 if ii==0:dim = numpy.array([4,0,8,4]) # WEST
186 197 elif ii==1:dim = numpy.array([0,0,4,4]) # NORTH
187 198 elif ii==2:dim = numpy.array([0,4,4,8]) # EAST
188 199 elif ii==3:dim = numpy.array([4,4,8,8]) # SOUTH
189 200 xi = dim[0]; xf = dim[2]; yi = dim[1]; yf = dim[3]
190 201 phase[xi:xf,yi:yf] = phase[xi:xf,yi:yf] + ues[ii]
191 202
192 203 phase = -phase
193 204
194 205 ar = self.eomwl*numpy.array([[0.5,6., 24.5],[0.5,6.,24.5]])
195 206 nr = numpy.array([[12.,4.,2.],[12.,4.,2.]])
196 207 lr = 0.25*self.eomwl*numpy.array([[0,0.,0],[0.,0,0]])
197 208
198 209 # Computing module and dipole patterns.
199 210 pattern = (numpy.abs(self.__dipPattern(ar,nr,lr)*self.__modPattern(phase,gain)))**2
200 211
201 212 return pattern
202 213
203 214 def __usingFFT(self,rx):
204 215 """
205 216 __usingFFT method returns the Jicamarca antenna pattern computed using The Fast Fou-
206 217 rier Transform.
207 218
208 219 pattern = iFFT(FFT(gain*EXP(j*phase)))
209 220
210 221 Parameters
211 222 ----------
212 223 rx = Set to 1 to use the Rx information. Otherwise set to 0 for Tx.
213 224
214 225 Return
215 226 ------
216 227 pattern = An array giving the modelled antenna pattern using the array model.
217 228
218 229 Modification history
219 230 --------------------
220 231 Developed by Jorge L. Chau.
221 232 Converted to Python by Freddy R. Galindo, ROJ, 20 September 2009.
222 233 """
223 234
224 235 if rx==1:
225 236 ues = self.uesrx
226 237 phase = self.phaserx
227 238 gain = self.gainrx
228 239 elif rx==0:
229 240 ues = self.uestx
230 241 phase = self.phasetx
231 242 gain = self.gaintx
232 243
233 244 ues = ues*360./self.airwl
234 245 phase = phase*360./self.airwl
235 246
236 247 for ii in range(4):
237 248 if ii==0:dim = numpy.array([4,0,8,4]) # WEST
238 249 elif ii==1:dim = numpy.array([0,0,4,4]) # NORTH
239 250 elif ii==2:dim = numpy.array([0,4,4,8]) # EAST
240 251 elif ii==3:dim = numpy.array([4,4,8,8]) # SOUTH
241 252 xi = dim[0]; xf = dim[2]; yi = dim[1]; yf = dim[3]
242 253 phase[xi:xf,yi:yf] = phase[xi:xf,yi:yf] + ues[ii]
243 254
244 255 phase = -phase
245 256
246 257 delta_x = self.eomwl/2.
247 258 delta_y = self.eomwl/2.
248 259
249 260 nxfft = 2048
250 261 nyfft = 2048
251 262 dcosx = (numpy.arange(nxfft) - (0.5*nxfft))/(nxfft*delta_x)*self.eomwl
252 263 dcosy = (numpy.arange(nyfft) - (0.5*nyfft))/(nyfft*delta_y)*self.eomwl
253 264
254 265 fft_gain = numpy.zeros((nxfft,nyfft))
255 266 fft_phase = numpy.zeros((nxfft,nyfft))
256 267
257 268 nx = 8
258 269 ny = 8
259 270 ndx =12
260 271 ndy =12
261 272 for iy in numpy.arange(ny):
262 273 for ix in numpy.arange(nx):
263 274 ix1 = nxfft/2-self.nx/2*ndx+ix*ndx
264 275 if ix<(nx/2):ix1 = ix1 - 1
265 276 if ix>=(nx/2):ix1 = ix1 + 1
266 277
267 278 iy1 = nyfft/2-ny/2*ndx+iy*ndy
268 279 if iy<(ny/2):iy1 = iy1 - 1
269 280 if iy>=(ny/2):iy1 = iy1 + 1
270 281
271 282 fft_gain[ix1:ix1+ndx-1,iy1:iy1+ndy-1] = gain[ix,ny-1-iy]
272 283 fft_phase[ix1:ix1+ndx-1,iy1:iy1+ndy-1] = phase[ix,ny-1-iy]
273 284
274 285
275 286 fft_phase = fft_phase*Misc_Routines.CoFactors.d2r
276 287
277 288 pattern = numpy.abs(numpy.fft.fft2(fft_gain*numpy.exp(numpy.complex(0,1)*fft_phase)))**2
278 289 pattern = numpy.fft.fftshift(pattern)
279 290
280 291 xvals = numpy.where((dcosx>=(numpy.min(self.dcosx))) & (dcosx<=(numpy.max(self.dcosx))))
281 292 yvals = numpy.where((dcosy>=(numpy.min(self.dcosy))) & (dcosy<=(numpy.max(self.dcosy))))
282 293
283 294 pattern = pattern[xvals[0][0]:xvals[0][-1],yvals[0][0]:yvals[0][-1]]
284 295
285 296 return pattern
286 297
287 298 def __readAttenuation(self):
288 299 """
289 300 _readAttenuation reads the attenuations' file and returns an array giving these va-
290 301 lues (dB). The ext file must be in the directory "resource".
291 302
292 303 Return
293 304 ------
294 305 attenuation = An array giving attenuation values read from the text file.
295 306
296 307 Modification history
297 308 --------------------
298 309 Developed by Jorge L. Chau.
299 310 Converted to Python by Freddy R. Galindo, ROJ, 20 September 2009.
300 311 """
301 312
302 313 attenuation = None
303 314 # foldr = sys.path[-1] + os.sep + "resource" + os.sep
304 315 base_path = os.path.dirname(os.path.abspath(__file__))
305 316 #foldr = './resource'
306 317 #filen = "attenuation.txt"
307 318 attenuationFile = os.path.join(base_path,"resource","attenuation.txt")
308 319 #ff = open(os.path.join(foldr,filen),'r')
309 320 ff = open(attenuationFile,'r')
310 321 exec(ff.read())
311 322 ff.close()
312 323
313 324 return attenuation
314 325
315 326 def __dipPattern(self,ar,nr,lr):
316 327 """
317 328 _dipPattern function computes the dipole's pattern to the Jicamarca radar. The next
318 329 equation defines the pattern as a function of the mainlobe direction:
319 330
320 331 sincx = SIN(k/2*n0x*(a0x*SIN(phi)*COS(alpha)))/SIN(k/2*(a0x*SIN(phi)*COS(alpha)))
321 332 sincy = SIN(k/2*n0y*(a0y*SIN(phi)*SIN(alpha)))/SIN(k/2*(a0y*SIN(phi)*SIN(alpha)))
322 333 A0(phi,alpha) = sincx*sincy
323 334 Parameters
324 335 ----------
325 336 ar = ?
326 337 nr = ?
327 338 lr = ?
328 339
329 340 Return
330 341 ------
331 342 dipole = An array giving antenna pattern from the dipole point of view..
332 343
333 344 Modification history
334 345 --------------------
335 346 Developed by Jorge L. Chau.
336 347 Converted to Python by Freddy R. Galindo, ROJ, 20 September 2009.
337 348 """
338 349
339 350 dipole = numpy.zeros((self.nx,self.ny),dtype=complex)
340 351 for iy in range(self.ny):
341 352 for ix in range(self.nx):
342 353 yindex = iy*(self.getcut==0) + ix*(self.getcut==1)
343 354
344 355 argx = ar[0,0]*self.dcosx[ix] - lr[0,0]
356 if argx == 0.0:
357 junkx = nr[0,0]
358 else:
345 359 junkx = numpy.sin(0.5*self.kk*nr[0,0]*argx)/numpy.sin(0.5*self.kk*argx)
346 if argx == 0.0: junkx = nr[0,0]
360
347 361
348 362 argy = ar[1,0]*self.dcosy[yindex] - lr[1,0]
363 if argy == 0.0:
364 junky = nr[1,0]
365 else:
349 366 junky = numpy.sin(0.5*self.kk*nr[1,0]*argy)/numpy.sin(0.5*self.kk*argy)
350 if argy == 0.0: junky = nr[1,0]
367
351 368
352 369 dipole[ix,iy] = junkx*junky
353 370
354 371 return dipole
355 372
356 373 def __modPattern(self,phase,gain):
357 374 """
358 375 ModPattern computes the module's pattern to the Jicamarca radar. The next equation
359 376 defines the pattern as a function mainlobe direction:
360 377
361 378 phasex = pos(x)*SIN(phi)*COS(alpha)
362 379 phasey = pos(y)*SIN(phi)*SIN(alpha)
363 380
364 381 A1(phi,alpha) = TOTAL(gain*EXP(COMPLEX(0,k*(phasex+phasey)+phase)))
365 382
366 383 Parameters
367 384 ----------
368 385 phase = Bidimensional array (8x8) giving the phase (in meters) of each module.
369 386 gain = Bidimensional array (8x8) giving to define modules will be active (ones)
370 387 and which will not (zeros).
371 388
372 389 Return
373 390 ------
374 391 module = An array giving antenna pattern from the module point of view..
375 392
376 393 Modification history
377 394 --------------------
378 395 Developed by Jorge L. Chau.
379 396 Converted to Python by Freddy R. Galindo, ROJ, 20 September 2009.
380 397 """
381 398
382 399 pos = self.eomwl*self.__readAttenuation()
383 400 posx = pos[0,:,:]
384 401 posy = pos[1,:,:]
385 402
386 403 phase = phase*Misc_Routines.CoFactors.d2r
387 404 module = numpy.zeros((self.nx,self.ny),dtype=complex)
388 405 for iy in range(self.ny):
389 406 for ix in range(self.nx):
390 407 yindex = iy*(self.getcut==0) + ix*(self.getcut==1)
391 408 phasex = posx*self.dcosx[ix]
392 409 phasey = posy*self.dcosy[yindex]
393 410 tmp = gain*numpy.exp(numpy.complex(0,1.)*(self.kk*(phasex+phasey)+phase))
394 411 module[ix,iy] = tmp.sum()
395 412
396 413 return module
397 414
398 415 def __getBeamPars(self):
399 416 """
400 417 _getBeamPars computes the main-beam parameters of the antenna.
401 418
402 419 Modification history
403 420 --------------------
404 421 Developed by Jorge L. Chau.
405 422 Converted to Python by Freddy R. Galindo, ROJ, 20 September 2009.
406 423 """
407 424
408 425 dx = self.dcosx[1] - self.dcosx[0]
409 426 dy = self.dcosy[1] - self.dcosy[0]
410 427
411 428 amp = self.norpattern
412 429
413 430 xx = numpy.resize(self.dcosx,(self.nx,self.nx)).transpose()
414 431 yy = numpy.resize(self.dcosy,(self.ny,self.ny))
415 432
416 433 mm0 = amp[numpy.where(amp > 0.5)]
417 434 xx0 = xx[numpy.where(amp > 0.5)]
418 435 yy0 = yy[numpy.where(amp > 0.5)]
419 436
420 437 xc = numpy.sum(mm0*xx0)/numpy.sum(mm0)
421 438 yc = numpy.sum(mm0*yy0)/numpy.sum(mm0)
422 439 rc = numpy.sqrt(mm0.size*dx*dy/numpy.pi)
423 440
424 441 nnx = numpy.where(numpy.abs(self.dcosx - xc) < rc)
425 442 nny = numpy.where(numpy.abs(self.dcosy - yc) < rc)
426 443
427 444 mm1 = amp[numpy.min(nnx):numpy.max(nnx)+1,numpy.min(nny):numpy.max(nny)+1]
428 445 xx1 = self.dcosx[numpy.min(nnx):numpy.max(nnx)+1]
429 446 yy1 = self.dcosy[numpy.min(nny):numpy.max(nny)+1]
430 447
431 448 # fitting data into the main beam.
432 449 import gaussfit
433 450 params = gaussfit.fitgaussian(mm1)
434 451
435 452 # Tranforming from indexes to axis' values
436 453 xcenter = xx1[0] + (((xx1[xx1.size-1] - xx1[0])/(xx1.size -1))*(params[1]))
437 454 ycenter = yy1[0] + (((yy1[yy1.size-1] - yy1[0])/(yy1.size -1))*(params[2]))
438 455 xwidth = ((xx1[xx1.size-1] - xx1[0])/(xx1.size-1))*(params[3])*(1/Misc_Routines.CoFactors.d2r)
439 456 ywidth = ((yy1[yy1.size-1] - yy1[0])/(yy1.size-1))*(params[4])*(1/Misc_Routines.CoFactors.d2r)
440 457 meanwx = (xwidth*ywidth)
441 458 meanpos = numpy.array([xcenter,ycenter])
442 459
443 460 #print 'Position: %f %f' %(xcenter,ycenter)
444 461 #print 'Widths: %f %f' %(xwidth, ywidth)
445 462 #print 'BWHP: %f' %(2*numpy.sqrt(2*meanwx)*numpy.sqrt(-numpy.log(0.5)))
446 463
447 464 self.meanpos = meanpos
448 465
449 466
450 467 class BField():
451 468 def __init__(self,year=None,doy=None,site=1,heights=None,alpha_i=90):
452 469 """
453 470 BField class creates an object to get the Magnetic field for a specific date and
454 471 height(s).
455 472
456 473 Parameters
457 474 ----------
458 475 year = A scalar giving the desired year. If the value is None (default value) then
459 476 the current year will be used.
460 477 doy = A scalar giving the desired day of the year. If the value is None (default va-
461 478 lue) then the current doy will be used.
462 479 site = An integer to choose the geographic coordinates of the place where the magne-
463 480 tic field will be computed. The default value is over Jicamarca (site=1)
464 481 heights = An array giving the heights (km) where the magnetic field will be modeled By default the magnetic field will be computed at 100, 500 and 1000km.
465 482 alpha_i = Angle to interpolate the magnetic field.
466 483
467 484 Modification History
468 485 --------------------
469 486 Converted to Object-oriented Programming by Freddy Galindo, ROJ, 07 October 2009.
470 487 """
471 488
472 489 tmp = time.localtime()
473 490 if year==None: year = tmp[0]
474 491 if doy==None: doy = tmp[7]
475 492 self.year = year
476 493 self.doy = doy
477 494 self.site = site
478 495 if heights==None:heights = numpy.array([100,500,1000])
479 496 self.heights = heights
480 497 self.alpha_i = alpha_i
481 498
482 499 def getBField(self,maglimits=numpy.array([-7,-7,7,7])):
483 500 """
484 501 getBField models the magnetic field for a different heights in a specific date.
485 502
486 503 Parameters
487 504 ----------
488 505 maglimits = An 4-elements array giving ..... The default value is [-7,-7,7,7].
489 506
490 507 Return
491 508 ------
492 509 dcos = An 4-dimensional array giving the directional cosines of the magnetic field
493 510 over the desired place.
494 511 alpha = An 3-dimensional array giving the angle of the magnetic field over the desi-
495 512 red place.
496 513
497 514 Modification History
498 515 --------------------
499 516 Converted to Python by Freddy R. Galindo, ROJ, 07 October 2009.
500 517 """
501 518
502 519 x_ant = numpy.array([1,0,0])
503 520 y_ant = numpy.array([0,1,0])
504 521 z_ant = numpy.array([0,0,1])
505 522
506 523 if self.site==0:
507 524 title_site = "Magnetic equator"
508 525 coord_site = numpy.array([-76+52./60.,-11+57/60.,0.5])
509 526 elif self.site==1:
510 527 title_site = 'Jicamarca'
511 528 coord_site = [-76-52./60.,-11-57/60.,0.5]
512 529 theta = (45+5.35)*numpy.pi/180. # (50.35 and 1.46 from Fleish Thesis)
513 530 delta = -1.46*numpy.pi/180
514 531
515 532 x_ant1 = numpy.roll(self.rotvector(self.rotvector(x_ant,1,delta),3,theta),1)
516 533 y_ant1 = numpy.roll(self.rotvector(self.rotvector(y_ant,1,delta),3,theta),1)
517 534 z_ant1 = numpy.roll(self.rotvector(self.rotvector(z_ant,1,delta),3,theta),1)
518 535
519 536 ang0 = -1*coord_site[0]*numpy.pi/180.
520 537 ang1 = coord_site[1]*numpy.pi/180.
521 538 x_ant = self.rotvector(self.rotvector(x_ant1,2,ang1),3,ang0)
522 539 y_ant = self.rotvector(self.rotvector(y_ant1,2,ang1),3,ang0)
523 540 z_ant = self.rotvector(self.rotvector(z_ant1,2,ang1),3,ang0)
524 541 else:
525 542 # print "No defined Site. Skip..."
526 543 return None
527 544
528 545 nhei = self.heights.size
529 546 pt_intercep = numpy.zeros((nhei,2))
530 547 nfields = 1
531 548
532 549 grid_res = 0.5
533 nlon = numpy.int(maglimits[2] - maglimits[0])/grid_res + 1
534 nlat = numpy.int(maglimits[3] - maglimits[1])/grid_res + 1
550 nlon = int(numpy.int(maglimits[2] - maglimits[0])/grid_res + 1)
551 nlat = int(numpy.int(maglimits[3] - maglimits[1])/grid_res + 1)
535 552
536 553 location = numpy.zeros((nlon,nlat,2))
537 554 mlon = numpy.atleast_2d(numpy.arange(nlon)*grid_res + maglimits[0])
538 555 mrep = numpy.atleast_2d(numpy.zeros(nlat) + 1)
539 556 location0 = numpy.dot(mlon.transpose(),mrep)
540 557
541 558 mlat = numpy.atleast_2d(numpy.arange(nlat)*grid_res + maglimits[1])
542 559 mrep = numpy.atleast_2d(numpy.zeros(nlon) + 1)
543 560 location1 = numpy.dot(mrep.transpose(),mlat)
544 561
545 562 location[:,:,0] = location0
546 563 location[:,:,1] = location1
547 564
548 565 alpha = numpy.zeros((nlon,nlat,nhei))
549 566 rr = numpy.zeros((nlon,nlat,nhei,3))
550 567 dcos = numpy.zeros((nlon,nlat,nhei,2))
551 568
552 569 global first_time
553 570
554 571 first_time = None
555 572 for ilon in numpy.arange(nlon):
556 573 for ilat in numpy.arange(nlat):
557 574 outs = self.__bdotk(self.heights,
558 575 self.year + self.doy/366.,
559 576 coord_site[1],
560 577 coord_site[0],
561 578 coord_site[2],
562 579 coord_site[1]+location[ilon,ilat,1],
563 580 location[ilon,ilat,0]*720./180.)
564 581
565 582 alpha[ilon, ilat,:] = outs[1]
566 583 rr[ilon, ilat,:,:] = outs[3]
567 584
568 585 mrep = numpy.atleast_2d((numpy.zeros(nhei)+1)).transpose()
569 586 tmp = outs[3]*numpy.dot(mrep,numpy.atleast_2d(x_ant))
570 587 tmp = tmp.sum(axis=1)
571 588 dcos[ilon,ilat,:,0] = tmp/numpy.sqrt((outs[3]**2).sum(axis=1))
572 589
573 590 mrep = numpy.atleast_2d((numpy.zeros(nhei)+1)).transpose()
574 591 tmp = outs[3]*numpy.dot(mrep,numpy.atleast_2d(y_ant))
575 592 tmp = tmp.sum(axis=1)
576 593 dcos[ilon,ilat,:,1] = tmp/numpy.sqrt((outs[3]**2).sum(axis=1))
577 594
578 595 return dcos, alpha, nlon, nlat
579 596
580 597
581 598 def __bdotk(self,heights,tm,gdlat=-11.95,gdlon=-76.8667,gdalt=0.0,decd=-12.88, ham=-4.61666667):
582 599
583 600 global first_time
584 601 # Mean Earth radius in Km WGS 84
585 602 a_igrf = 6371.2
586 603
587 604 bk = numpy.zeros(heights.size)
588 605 alpha = numpy.zeros(heights.size)
589 606 bfm = numpy.zeros(heights.size)
590 607 rr = numpy.zeros((heights.size,3))
591 608 rgc = numpy.zeros((heights.size,3))
592 609
593 610 ObjGeodetic = Astro_Coords.Geodetic(gdlat,gdalt)
594 611 [gclat,gcalt] = ObjGeodetic.change2geocentric()
595 612
596 613 gclat = gclat*numpy.pi/180.
597 614 gclon = gdlon*numpy.pi/180.
598 615
599 616 # Antenna position from center of Earth
600 617 ca_vector = [numpy.cos(gclat)*numpy.cos(gclon),numpy.cos(gclat)*numpy.sin(gclon),numpy.sin(gclat)]
601 618 ca_vector = gcalt*numpy.array(ca_vector)
602 619
603 620 dec = decd*numpy.pi/180.
604 621
605 622 # K vector respect to the center of earth.
606 623 klon = gclon + ham*numpy.pi/720.
607 624 k_vector = [numpy.cos(dec)*numpy.cos(klon),numpy.cos(dec)*numpy.sin(klon),numpy.sin(dec)]
608 625 k_vector = numpy.array(k_vector)
609 626
610 627 for ih in numpy.arange(heights.size):
611 628 # Vector from Earth's center to volume of interest
612 629 rr[ih,:] = k_vector*heights[ih]
613 630 cv_vector = numpy.squeeze(ca_vector) + rr[ih,:]
614 631
615 632 cv_gcalt = numpy.sqrt(numpy.sum(cv_vector**2.))
616 633 cvxy = numpy.sqrt(numpy.sum(cv_vector[0:2]**2.))
617 634
618 635 radial = cv_vector/cv_gcalt
619 636 east = numpy.array([-1*cv_vector[1],cv_vector[0],0])/cvxy
620 637 comp1 = east[1]*radial[2] - radial[1]*east[2]
621 638 comp2 = east[2]*radial[0] - radial[2]*east[0]
622 639 comp3 = east[0]*radial[1] - radial[0]*east[1]
623 640 north = -1*numpy.array([comp1, comp2, comp3])
624 641
625 642 rr_k = cv_vector - numpy.squeeze(ca_vector)
626 643 u_rr = rr_k/numpy.sqrt(numpy.sum(rr_k**2.))
627 644
628 645 cv_gclat = numpy.arctan2(cv_vector[2],cvxy)
629 646 cv_gclon = numpy.arctan2(cv_vector[1],cv_vector[0])
630 647
631 648 bhei = cv_gcalt-a_igrf
632 649 blat = cv_gclat*180./numpy.pi
633 650 blon = cv_gclon*180./numpy.pi
634 651 bfield = self.__igrfkudeki(bhei,tm,blat,blon)
635 652
636 653 B = (bfield[0]*north + bfield[1]*east - bfield[2]*radial)*1.0e-5
637 654
638 655 bfm[ih] = numpy.sqrt(numpy.sum(B**2.)) #module
639 656 bk[ih] = numpy.sum(u_rr*B)
640 657 alpha[ih] = numpy.arccos(bk[ih]/bfm[ih])*180/numpy.pi
641 658 rgc[ih,:] = numpy.array([cv_gclon, cv_gclat, cv_gcalt])
642 659
643 660 return bk, alpha, bfm, rr, rgc
644 661
645 662
646 663 def __igrfkudeki(self,heights,time,latitude,longitude,ae=6371.2):
647 664 """
648 665 __igrfkudeki calculates the International Geomagnetic Reference Field for given in-
649 666 put conditions based on IGRF2005 coefficients.
650 667
651 668 Parameters
652 669 ----------
653 670 heights = Scalar or vector giving the height above the Earth of the point in ques-
654 671 tion in kilometers.
655 672 time = Scalar or vector giving the decimal year of time in question (e.g. 1991.2).
656 673 latitude = Latitude of point in question in decimal degrees. Scalar or vector.
657 674 longitude = Longitude of point in question in decimal degrees. Scalar or vector.
658 675 ae =
659 676 first_time =
660 677
661 678 Return
662 679 ------
663 680 bn =
664 681 be =
665 682 bd =
666 683 bmod =
667 684 balpha =
668 685 first_time =
669 686
670 687 Modification History
671 688 --------------------
672 689 Converted to Python by Freddy R. Galindo, ROJ, 03 October 2009.
673 690 """
674 691
675 692 global first_time
676 693 global gs, hs, nvec, mvec, maxcoef
677 694
678 695 heights = numpy.atleast_1d(heights)
679 696 time = numpy.atleast_1d(time)
680 697 latitude = numpy.atleast_1d(latitude)
681 698 longitude = numpy.atleast_1d(longitude)
682 699
683 700 if numpy.max(latitude)==90:
684 701 # print "Field calculations are not supported at geographic poles"
685 702 pass
686 703
687 704 # output arrays
688 705 bn = numpy.zeros(heights.size)
689 706 be = numpy.zeros(heights.size)
690 707 bd = numpy.zeros(heights.size)
691 708
692 709 if first_time==None:first_time=0
693 710
694 711 time0 = time[0]
695 712 if time!=first_time:
696 713 #print "Getting coefficients for", time0
697 714 [periods,g,h ] = self.__readIGRFcoeff()
698 715 top_year = numpy.max(periods)
699 716 nperiod = (top_year - 1900)/5 + 1
700 717
701 718 maxcoef = 10
702 719 if time0>=2000:maxcoef = 12
703 720
704 721
705 722 # Normalization array for Schmidt fucntions
706 723 multer = numpy.zeros((2+maxcoef,1+maxcoef)) + 1
707 724 for cn in (numpy.arange(maxcoef)+1):
708 725 for rm in (numpy.arange(cn)+1):
709 726 tmp = numpy.arange(2*rm) + cn - rm + 1.
710 727 multer[rm+1,cn] = ((-1.)**rm)*numpy.sqrt(2./tmp.prod())
711 728
712 729 schmidt = multer[1:,1:].transpose()
713 730
714 731 # n and m arrays
715 732 nvec = numpy.atleast_2d(numpy.arange(maxcoef)+2)
716 733 mvec = numpy.atleast_2d(numpy.arange(maxcoef+1)).transpose()
717 734
718 735 # Time adjusted igrf g and h with Schmidt normalization
719 736 # IGRF coefficient arrays: g0(n,m), n=1, maxcoeff,m=0, maxcoeff, ...
720 737 if time0<top_year:
721 738 dtime = (time0 - 1900) % 5
722 739 ntime = (time0 - 1900 - dtime)/5
723 740 else:
724 741 # Estimating coefficients for times > top_year
725 742 dtime = (time0 - top_year) + 5
726 743 ntime = g[:,0,0].size - 2
727 744
728 745 g0 = g[ntime,1:maxcoef+1,:maxcoef+1]
729 746 h0 = h[ntime,1:maxcoef+1,:maxcoef+1]
730 747 gdot = g[ntime+1,1:maxcoef+1,:maxcoef+1]-g[ntime,1:maxcoef+1,:maxcoef+1]
731 748 hdot = h[ntime+1,1:maxcoef+1,:maxcoef+1]-h[ntime,1:maxcoef+1,:maxcoef+1]
732 749 gs = (g0 + dtime*(gdot/5.))*schmidt[:maxcoef,0:maxcoef+1]
733 750 hs = (h0 + dtime*(hdot/5.))*schmidt[:maxcoef,0:maxcoef+1]
734 751
735 752 first_time = time0
736 753
737 754 for ii in numpy.arange(heights.size):
738 755 # Height dependence array rad = (ae/(ae+height))**(n+3)
739 756 rad = numpy.atleast_2d((ae/(ae + heights[ii]))**(nvec+1))
740 757
741 758 # Sin and Cos of m times longitude phi arrays
742 759 mphi = mvec*longitude[ii]*numpy.pi/180.
743 760 cosmphi = numpy.atleast_2d(numpy.cos(mphi))
744 761 sinmphi = numpy.atleast_2d(numpy.sin(mphi))
745 762
746 763 # Cos of colatitude theta
747 764 c = numpy.cos((90 - latitude[ii])*numpy.pi/180.)
748 765
749 766 # Legendre functions p(n,m|c)
750 767 [p,dp]= scipy.special.lpmn(maxcoef+1,maxcoef+1,c)
751 768 p = p[:,:-1].transpose()
752 769 s = numpy.sqrt((1. - c)*(1 + c))
753 770
754 771 # Generate derivative array dpdtheta = -s*dpdc
755 772 dpdtheta = c*p/s
756 773 for m in numpy.arange(maxcoef+2): dpdtheta[:,m] = m*dpdtheta[:,m]
757 774 dpdtheta = dpdtheta + numpy.roll(p,-1,axis=1)
758 775
759 776 # Extracting arrays required for field calculations
760 777 p = p[1:maxcoef+1,:maxcoef+1]
761 778 dpdtheta = dpdtheta[1:maxcoef+1,:maxcoef+1]
762 779
763 780 # Weigh p and dpdtheta with gs and hs coefficients.
764 781 gp = gs*p
765 782 hp = hs*p
766 783 gdpdtheta = gs*dpdtheta
767 784 hdpdtheta = hs*dpdtheta
768 785 # Calcultate field components
769 786 matrix0 = numpy.dot(gdpdtheta,cosmphi)
770 787 matrix1 = numpy.dot(hdpdtheta,sinmphi)
771 788 bn[ii] = numpy.dot(rad,(matrix0 + matrix1))
772 789 matrix0 = numpy.dot(hp,(mvec*cosmphi))
773 790 matrix1 = numpy.dot(gp,(mvec*sinmphi))
774 791 be[ii] = numpy.dot((-1*rad),((matrix0 - matrix1)/s))
775 792 matrix0 = numpy.dot(gp,cosmphi)
776 793 matrix1 = numpy.dot(hp,sinmphi)
777 794 bd[ii] = numpy.dot((-1*nvec*rad),(matrix0 + matrix1))
778 795
779 796 bmod = numpy.sqrt(bn**2. + be**2. + bd**2.)
780 797 btheta = numpy.arctan(bd/numpy.sqrt(be**2. + bn**2.))*180/numpy.pi
781 798 balpha = numpy.arctan(be/bn)*180./numpy.pi
782 799
783 800 #bn : north
784 801 #be : east
785 802 #bn : radial
786 803 #bmod : module
787 804
788 805
789 806 return bn, be, bd, bmod, btheta, balpha
790 807
791 808 def str2num(self, datum):
792 809 try:
793 810 return int(datum)
794 811 except:
795 812 try:
796 813 return float(datum)
797 814 except:
798 815 return datum
799 816
800 817 def __readIGRFfile(self, filename):
801 818 list_years=[]
802 819 for i in range(1,24):
803 820 list_years.append(1895.0 + i*5)
804 821
805 822 epochs=list_years
806 823 epochs.append(epochs[-1]+5)
807 824 nepochs = numpy.shape(epochs)
808 825
809 826 gg = numpy.zeros((13,14,nepochs[0]),dtype=float)
810 827 hh = numpy.zeros((13,14,nepochs[0]),dtype=float)
811 828
812 829 coeffs_file=open(filename)
813 830 lines=coeffs_file.readlines()
814 831
815 832 coeffs_file.close()
816 833
817 834 for line in lines:
818 835 items = line.split()
819 836 g_h = items[0]
820 837 n = self.str2num(items[1])
821 838 m = self.str2num(items[2])
822 839
823 840 coeffs = items[3:]
824 841
825 842 for i in range(len(coeffs)-1):
826 843 coeffs[i] = self.str2num(coeffs[i])
827 844
828 845 #coeffs = numpy.array(coeffs)
829 846 ncoeffs = numpy.shape(coeffs)[0]
830 847
831 848 if g_h == 'g':
832 849 # print n," g ",m
833 850 gg[n-1,m,:]=coeffs
834 851 elif g_h=='h':
835 852 # print n," h ",m
836 853 hh[n-1,m,:]=coeffs
837 854 # else :
838 855 # continue
839 856
840 857 # Ultimo Reordenamiento para almacenar .
841 858 gg[:,:,nepochs[0]-1] = gg[:,:,nepochs[0]-2] + 5*gg[:,:,nepochs[0]-1]
842 859 hh[:,:,nepochs[0]-1] = hh[:,:,nepochs[0]-2] + 5*hh[:,:,nepochs[0]-1]
843 860
844 861 # return numpy.array([gg,hh])
845 862 periods = numpy.array(epochs)
846 863 g = gg
847 864 h = hh
848 865 return periods, g, h
849 866
850 867
851 868 def __readIGRFcoeff(self,filename="igrf10coeffs.dat"):
852 869 """
853 870 __readIGRFcoeff reads the coefficients from a binary file which is located in the
854 871 folder "resource."
855 872
856 873 Parameter
857 874 ---------
858 875 filename = A string to specify the name of the file which contains thec coeffs. The
859 876 default value is "igrf10coeffs.dat"
860 877
861 878 Return
862 879 ------
863 880 periods = A lineal array giving...
864 881 g1 =
865 882 h1 =
866 883
867 884 Modification History
868 885 --------------------
869 886 Converted to Python by Freddy R. Galindo, ROJ, 03 October 2009.
870 887 """
871 888
872 889 # # igrfile = sys.path[-1] + os.sep + "resource" + os.sep + filename
873 890 # igrfile = os.path.join('./resource',filename)
874 891 # f = open(igrfile,'rb')
875 892 # #f = open(os.getcwd() + os.sep + "resource" + os.sep + filename,'rb')
876 893 #
877 894 # # Reading SkyNoise Power (lineal scale)
878 895 # periods = numpy.fromfile(f,numpy.dtype([('var','<f4')]),23)
879 896 # periods = periods['var']
880 897 #
881 898 # g = numpy.fromfile(f,numpy.dtype([('var','<f8')]),23*14*14)
882 899 # g = g['var'].reshape((14,14,23)).transpose()
883 900 #
884 901 # h = numpy.fromfile(f,numpy.dtype([('var','<f8')]),23*14*14)
885 902 # h = h['var'].reshape((14,14,23)).transpose()
886 903 #
887 904 # f.close()
888 905 base_path = os.path.dirname(os.path.abspath(__file__))
889 906 filename = os.path.join(base_path,"resource","igrf11coeffs.txt")
890 907
891 908 period_v, g_v, h_v = self.__readIGRFfile(filename)
892 909 g2 = numpy.zeros((14,14,24))
893 910 h2 = numpy.zeros((14,14,24))
894 911 g2[1:14,:,:] = g_v
895 912 h2[1:14,:,:] = h_v
896 913
897 914 g = numpy.transpose(g2, (2,0,1))
898 915 h = numpy.transpose(h2, (2,0,1))
899 916 periods = period_v.copy()
900 917
901 918 return periods, g, h
902 919
903 920 def rotvector(self,vector,axis=1,ang=0):
904 921 """
905 922 rotvector function returns the new vector generated rotating the rectagular coords.
906 923
907 924 Parameters
908 925 ----------
909 926 vector = A lineal 3-elements array (x,y,z).
910 927 axis = A integer to specify the axis used to rotate the coord systems. The default
911 928 value is 1.
912 929 axis = 1 -> Around "x"
913 930 axis = 2 -> Around "y"
914 931 axis = 3 -> Around "z"
915 932 ang = Angle of rotation (in radians). The default value is zero.
916 933
917 934 Return
918 935 ------
919 936 rotvector = A lineal array of 3 elements giving the new coordinates.
920 937
921 938 Modification History
922 939 --------------------
923 940 Converted to Python by Freddy R. Galindo, ROJ, 01 October 2009.
924 941 """
925 942
926 943 if axis==1:
927 944 t = [[1,0,0],[0,numpy.cos(ang),numpy.sin(ang)],[0,-numpy.sin(ang),numpy.cos(ang)]]
928 945 elif axis==2:
929 946 t = [[numpy.cos(ang),0,-numpy.sin(ang)],[0,1,0],[numpy.sin(ang),0,numpy.cos(ang)]]
930 947 elif axis==3:
931 948 t = [[numpy.cos(ang),numpy.sin(ang),0],[-numpy.sin(ang),numpy.cos(ang),0],[0,0,1]]
932 949
933 950 rotvector = numpy.array(numpy.dot(numpy.array(t),numpy.array(vector)))
934 951
935 952 return rotvector
936 953
937 954
938 955 class overJroShow:
939 956
940 957 # __serverdocspath = '/usr/local/www/htdocs'
941 958 # __tmpDir = 'overJro/tempReports'
942 959 # __serverdocspath = '/Users/dsuarez/Pictures'
943 960 # __tmpDir = 'overjro'
944 __serverdocspath = None
945 __tmpDir = None
961 __serverdocspath = ''
962 __tmpDir = ''
946 963
947 def __init__(self):
964 def __init__(self, title=''):
948 965 self.year = None
949 966 self.month = None
950 967 self.dom = None
951 968 self.pattern = None
952 969 self.maxphi = None
953 970 self.heights = None
954 971 self.filename = None
955 972 self.showType = None
956 973 self.path = None
957 974 self.objects = None
958 975 self.nptsx = 101
959 976 self.nptsy = 101
960 977 self.fftopt = 0
961 978 self.site = 1
962 979 self.dcosx = 1
963 980 self.dcosy = 1
964 981 self.dcosxrange = None
965 982 self.dcosyrange = None
966 983 self.maxha_min= 0.
967 984 self.show_object = None
968 985 self.dcosx_mag = None
969 986 self.dcosy_mag = None
970 987 self.ha_mag = None
971 988 self.time_mag = None
972 989 self.main_dec = None
973 990 self.ObjC = None
974 self.ptitle = ''
991 self.ptitle = title
975 992 self.path4plotname = None
976 993 self.plotname0 = None
977 994 self.plotname1 = None
978 995 self.plotname2 = None
979 996 self.scriptHeaders = 0
997 self.glat = -11.95
998 self.glon = -76.8667
999 self.UT = 5 #timezone
1000
1001 self.glat = -11.951481
1002 self.glon = -76.874383
980 1003 # self.outputHead('Show Plot')
981 1004 # self.printBody()
982 1005
983 1006 def setScriptState(self):
984 1007 self.madForm = cgi.FieldStorage()
985 1008
986 1009 if self.madForm.has_key('serverdocspath'):
987 1010 self.__serverdocspath = self.madForm.getvalue('serverdocspath')#'/usr/local/www/htdocs'
988 1011
989 1012 if self.madForm.has_key('tmpdir'):
990 1013 self.__tmpDir = self.madForm.getvalue('tmpdir')#'overJro/tempReports'
991 1014
992 1015 if self.madForm.has_key('showType'):
993 1016 self.showType = int(self.madForm.getvalue('showType'))
994 1017
995 1018 if self.showType == 0 or self.showType == 1:
996 1019
997 1020 # if self.madForm.has_key('year') and \
998 1021 # self.madForm.has_key('month') and \
999 1022 # self.madForm.has_key('dom') and \
1000 1023 # self.madForm.has_key('pattern') and \
1001 1024 # self.madForm.has_key('maxphi') and \
1002 1025 # self.madForm.has_key('objects') and \
1003 1026 # self.madForm.has_key('heights'):
1004 1027
1005 1028 if self.madForm.has_key('year') and \
1006 1029 self.madForm.has_key('month') and \
1007 1030 self.madForm.has_key('dom') and \
1008 1031 self.madForm.has_key('maxphi') and \
1009 1032 self.madForm.has_key('objects') and \
1010 1033 self.madForm.has_key('heights'):
1011 1034
1012 1035 self.year = int(self.madForm.getvalue('year'))
1013 1036 self.month = int(self.madForm.getvalue('month'))
1014 1037 self.dom = int(self.madForm.getvalue('dom'))
1015 1038 self.maxphi = float(self.madForm.getvalue('maxphi'))
1016 1039
1017 1040 if self.madForm.has_key('pattern'):
1018 1041
1019 1042 tmp_pattern = self.madForm.getvalue('pattern') #pattern es predifinido en listado o definido por el usuario
1020 1043 self.pattern=[]
1021 1044 if tmp_pattern[0] == '[':
1022 1045 tmp_pattern=tmp_pattern[1:]
1023 1046
1024 1047 if tmp_pattern[-1] == ']':
1025 1048 tmp_pattern=tmp_pattern[0:len(tmp_pattern)-1]
1026 1049
1027 1050 for s in tmp_pattern.split(','):
1028 1051 self.pattern.append(float(s))
1029 1052 elif self.madForm.has_key('filename'):
1030 1053 if self.madForm.has_key('filename'):
1031 1054 self.filename = self.madForm.getvalue('filename') # nombre de archivo: patron de radiacion definido por el usuario
1032 1055
1033 1056 if self.madForm.has_key('path'):
1034 1057 self.path = self.madForm.getvalue('path') #path donde se encuentra el archivo: patron de radiacion del usuario
1035 1058
1036 1059 else:
1037 1060 print "Content-Type: text/html\n"
1038 1061 print '<h3> This cgi plot script was called without the proper arguments.</h3>'
1039 1062 print '<p> This is a script used to plot Antenna Cuts over Jicamarca Antenna</p>'
1040 1063 print '<p> Required arguments:</p>'
1041 1064 print '<p> pattern - chekbox indicating objects over jicamarca antenna</p>'
1042 1065 print '<p> or'
1043 1066 print '<p> filename - The pattern defined by users is a file text'
1044 1067 print '<p> path - folder with pattern files'
1045 1068 sys.exit(0)
1046 1069
1047 1070
1048 1071 tmp_heights = self.madForm.getvalue('heights')
1049 1072 self.heights=[]
1050 1073 if tmp_heights[0] == '[':
1051 1074 tmp_heights=tmp_heights[1:]
1052 1075
1053 1076 if tmp_heights[-1] == ']':
1054 1077 tmp_heights=tmp_heights[0:len(tmp_heights)-1]
1055 1078
1056 1079 for s in tmp_heights.split(','):
1057 1080 self.heights.append(float(s))
1058 1081 self.heights = numpy.array(self.heights)
1059 1082
1060 1083 tmp_objects = self.madForm.getvalue('objects') #lista con los objetos a graficar en el patron de radiacion
1061 1084 self.objects=[]
1062 1085 if tmp_objects[0] == '[':
1063 1086 tmp_objects=tmp_objects[1:]
1064 1087
1065 1088 if tmp_objects[-1] == ']':
1066 1089 tmp_objects=tmp_objects[0:len(tmp_objects)-1]
1067 1090
1068 1091 for s in tmp_objects.split(','):
1069 1092 self.objects.append(int(s))
1070 1093
1071 1094 if self.showType == 1:
1072 1095 if numpy.sum(self.objects) == 0:
1073 1096 if self.scriptHeaders == 0:
1074 1097 print "Content-Type: text/html\n"
1075 1098 print '<h3> This cgi plot script was called without the proper arguments.</h3>'
1076 1099 print '<p> This is a script used to plot Antenna Cuts over Jicamarca Antenna</p>'
1077 1100 print '<p> Required arguments:</p>'
1078 1101 print '<p> objects - chekbox indicating objects over jicamarca antenna</p>'
1079 1102 print '<p> Please, options in "Select Object" must be checked'
1080 1103 sys.exit(0)
1081 1104
1082 1105 #considerar para futura implementacion
1083 1106 if self.madForm.has_key('filename'):
1084 1107 self.filename = self.madForm.getvalue('filename') # nombre de archivo: patron de radiacion definido por el usuario
1085 1108
1086 1109 if self.madForm.has_key('path'):
1087 1110 self.path = self.madForm.getvalue('path') #path donde se encuentra el archivo: patron de radiacion del usuario
1088 1111
1089 1112
1090 1113 else:
1091 1114 if self.scriptHeaders == 0:
1092 1115 print "Content-Type: text/html\n"
1093 1116
1094 1117 print '<h3> This cgi plot script was called without the proper arguments.</h3>'
1095 1118 print '<p> This is a script used to plot Pattern Field and Celestial Objects over Jicamarca Antenna</p>'
1096 1119 print '<p> Required arguments:</p>'
1097 1120 print '<p> year - year of event</p>'
1098 1121 print '<p> month - month of event</p>'
1099 1122 print '<p> dom - day of month</p>'
1100 1123 print '<p> pattern - pattern is defined by "Select an Experiment" list box</p>'
1101 1124 print '<p> maxphi - maxphi is defined by "Max Angle" text box</p>'
1102 1125 print '<p> objects - objects is a list defined by checkbox in "Select Object"</p>'
1103 1126 print '<p> heights - heights is defined by "Heights" text box, for default heights=[100,500,1000]</p>'
1104 1127 print '<p> showType - showType is a hidden element for show plot of Pattern&Object or Antenna Cuts or Sky Noise</p>'
1105 1128
1106 1129 sys.exit(0)
1107 1130
1108 1131 if self.showType == 2:
1109 1132 if self.madForm.has_key('year') and \
1110 1133 self.madForm.has_key('month') and \
1111 1134 self.madForm.has_key('dom'):
1112 1135
1113 1136 self.year = int(self.madForm.getvalue('year'))
1114 1137 self.month = int(self.madForm.getvalue('month'))
1115 1138 self.dom = int(self.madForm.getvalue('dom'))
1116 1139
1117 1140 else:
1118 1141 if self.scriptHeaders == 0:
1119 1142 print "Content-Type: text/html\n"
1120 1143 print '<h3> This cgi plot script was called without the proper arguments.</h3>'
1121 1144 print '<p> This is a script used to plot Sky Noise over Jicamarca Antenna</p>'
1122 1145 print '<p> Required arguments:</p>'
1123 1146 print '<p> year - year of event</p>'
1124 1147 print '<p> month - month of event</p>'
1125 1148 print '<p> dom - day of month</p>'
1126 1149
1127 1150 sys.exit(0)
1128 1151
1129 1152
1130 1153 def initParameters1(self):
1131 1154
1132 1155 gui=1
1133 1156 if self.pattern==None:
1134 1157 if gui==1: self.filename = self.filename.split(',')
1135 1158
1136 1159 pattern = numpy.atleast_1d(self.pattern)
1137 1160 filename = numpy.atleast_1d(self.filename)
1138 1161
1139 1162 npatterns = numpy.max(numpy.array([pattern.size,filename.size]))
1140 1163
1141 1164 self.pattern = numpy.resize(pattern,npatterns)
1142 1165 self.filename = numpy.resize(filename,npatterns)
1143 1166
1144 1167 self.doy = datetime.datetime(self.year,self.month,self.dom).timetuple().tm_yday
1145 1168
1146 1169
1147 1170 if self.objects==None:
1148 1171 self.objects=numpy.zeros(5)
1149 1172 else:
1150 1173 tmp = numpy.atleast_1d(self.objects)
1151 1174 self.objects = numpy.zeros(5)
1152 1175 self.objects[0:tmp.size] = tmp
1153 1176
1154 1177 self.show_object = self.objects
1155 1178
1156 1179 self.maxha_min = 4*self.maxphi*numpy.sqrt(2)*1.25
1157 1180
1158 1181
1159 1182 if self.heights==None:
1160 1183 self.heights = numpy.array([100.,500.,1000.])
1161 1184
1162 1185
1163 1186
1164 1187 #ROJ geographic coordinates and time zone
1165 1188 self.glat = -11.95
1166 1189 self.glon = -76.8667
1167 1190 self.UT = 5 #timezone
1168 1191
1169 1192 self.glat = -11.951481
1170 1193 self.glon = -76.874383
1171 1194
1172 1195
1173 1196 self.junkjd = TimeTools.Time(self.year,self.month,self.dom).change2julday()
1174 1197 self.junklst = TimeTools.Julian(self.junkjd).change2lst(longitude=self.glon)
1175 1198
1176 1199 # Finding RA of observatory for a specific date
1177 1200 self.ra_obs = self.junklst*Misc_Routines.CoFactors.h2d
1178 1201
1179 1202 def initParameters(self):
1180 1203
1181 1204 # Defining plot filenames
1182 1205 self.path4plotname = os.path.join(self.__serverdocspath,self.__tmpDir)
1183 print "PATH4"
1184 print os.path.join(self.__serverdocspath,self.__tmpDir)
1185 1206 self.plotname0 = 'over_jro_0_%i.png'% (time.time()) #plot pattern & objects
1186 1207 self.plotname1 = 'over_jro_1_%i.png'% (time.time()) #plot antenna cuts
1187 1208 self.plotname2 = 'over_jro_2_%i.png'% (time.time()) #plot sky noise
1188 1209
1189 1210 # Defining antenna axes respect to geographic coordinates (See Ochs report).
1190 1211 # alfa = 1.46*Misc_Routines.CoFactors.d2r
1191 1212 # theta = 51.01*Misc_Routines.CoFactors.d2r
1192 1213
1193 1214 alfa = 1.488312*Misc_Routines.CoFactors.d2r
1194 1215 th = 6.166710 + 45.0
1195 1216 theta = th*Misc_Routines.CoFactors.d2r
1196 1217
1197 1218 sina = numpy.sin(alfa)
1198 1219 cosa = numpy.cos(alfa)
1199 1220 MT1 = numpy.array([[1,0,0],[0,cosa,-sina],[0,sina,cosa]])
1200 1221 sinb = numpy.sin(theta)
1201 1222 cosb = numpy.cos(theta)
1202 1223 MT2 = numpy.array([[cosb,sinb,0],[-sinb,cosb,0],[0,0,1]])
1203 1224 self.MT3 = numpy.array(numpy.dot(MT2, MT1)).transpose()
1204 1225
1205 1226 self.xg = numpy.dot(self.MT3.transpose(),numpy.array([1,0,0]))
1206 1227 self.yg = numpy.dot(self.MT3.transpose(),numpy.array([0,1,0]))
1207 1228 self.zg = numpy.dot(self.MT3.transpose(),numpy.array([0,0,1]))
1208 1229
1230 def plotPattern2(self, date, phases, gain_tx, gain_rx, ues, just_rx):
1231 # Plotting Antenna patterns.
1232
1233 self.initParameters()
1234 self.doy = datetime.datetime(date.year,date.month,date.day).timetuple().tm_yday
1235 self.junkjd = TimeTools.Time(self.year,self.month,self.dom).change2julday()
1236 self.junklst = TimeTools.Julian(self.junkjd).change2lst(longitude=self.glon)
1237 self.ra_obs = self.junklst*Misc_Routines.CoFactors.h2d
1238
1239 date = TimeTools.Time(date.year,date.month,date.day).change2strdate(mode=2)
1240
1241 mesg = 'Over Jicamarca: ' + date[0]
1242
1243 ObjAnt = JroPattern(pattern=0,
1244 filename=None,
1245 path=None,
1246 nptsx=self.nptsx,
1247 nptsy=self.nptsy,
1248 #maxphi=self.maxphi,
1249 fftopt=self.fftopt,
1250 phases=numpy.array(phases),
1251 gain_tx=numpy.array(gain_tx),
1252 gain_rx=numpy.array(gain_rx),
1253 ues=numpy.array(ues),
1254 just_rx=just_rx
1255 )
1256
1257 dum = Graphics_OverJro.AntPatternPlot()
1258
1259 dum.contPattern(iplot=0,
1260 gpath=self.path4plotname,
1261 filename=self.plotname0,
1262 mesg=mesg,
1263 amp=ObjAnt.norpattern,
1264 x=ObjAnt.dcosx,
1265 y=ObjAnt.dcosy,
1266 getCut=ObjAnt.getcut,
1267 title=self.ptitle,
1268 save=False)
1269
1270
1271 dum.plotRaDec(gpath=self.path4plotname,
1272 filename=self.plotname0,
1273 jd=self.junkjd,
1274 ra_obs=self.ra_obs,
1275 xg=self.xg,
1276 yg=self.yg,
1277 x=ObjAnt.dcosx,
1278 y=ObjAnt.dcosy,
1279 save=False)
1280
1281 ObjB = BField(self.year,self.doy,1,self.heights)
1282 [dcos, alpha, nlon, nlat] = ObjB.getBField()
1283
1284 dum.plotBField('', '',dcos,alpha,nlon,nlat,
1285 self.dcosxrange,
1286 self.dcosyrange,
1287 ObjB.heights,
1288 ObjB.alpha_i,
1289 save=False)
1290
1291 return dum.fig
1292
1293
1209 1294 def plotPattern(self):
1210 1295 # Plotting Antenna patterns.
1211 1296 npatterns = numpy.size(self.pattern)
1212 1297
1213 1298 if npatterns==1:
1214 1299 if self.pattern[0] == None: npatterns = self.filename.__len__()
1215 1300
1216 1301 date = TimeTools.Time(self.year,self.month,self.dom).change2strdate(mode=2)
1217 1302
1218 1303 mesg = 'Over Jicamarca: ' + date[0]
1219 1304
1220 1305 title = ''
1221 1306
1222 1307 for ii in numpy.arange(npatterns):
1223 1308 ObjAnt = JroPattern(pattern=self.pattern[ii],
1224 1309 filename=self.filename[ii],
1225 1310 path=self.path,
1226 1311 nptsx=self.nptsx,
1227 1312 nptsy=self.nptsy,
1228 1313 maxphi=self.maxphi,
1229 1314 fftopt=self.fftopt)
1230 1315
1231 1316 title += ObjAnt.title
1232 1317 # Plotting Contour Map
1233 print "Antes de la creacion"
1234 self.path4plotname = '/home/fquino/workspace/radarsys/webapp/apps/abs/static/images'
1235 print self.path4plotname
1236 print self.plotname0
1318
1319 self.path4plotname = '/home/jespinoza/workspace/radarsys/trunk/webapp/apps/abs/static/images'
1237 1320 dum = Graphics_OverJro.AntPatternPlot()
1238 1321 dum.contPattern(iplot=ii,
1239 1322 gpath=self.path4plotname,
1240 1323 filename=self.plotname0,
1241 1324 mesg=mesg,
1242 1325 amp=ObjAnt.norpattern,
1243 1326 x=ObjAnt.dcosx,
1244 1327 y=ObjAnt.dcosy,
1245 1328 getCut=ObjAnt.getcut,
1246 1329 title=title)
1247 1330 # title=ObjAnt.title)
1248 1331 # self.ptitle = ObjAnt.title
1249 if ii==0:
1250 self.figure = dum.figure
1251 1332
1252 1333 if ii != (npatterns-1):
1253 1334 title += '+'
1254 1335
1255 1336
1256 1337 vect_ant = numpy.array([ObjAnt.meanpos[0],ObjAnt.meanpos[1],numpy.sqrt(1-numpy.sum(ObjAnt.meanpos**2.))])
1257 1338
1258 1339 vect_geo = numpy.dot(scipy.linalg.inv(self.MT3),vect_ant)
1259 1340
1260 1341 vect_polar = Misc_Routines.Vector(numpy.array(vect_geo),direction=1).Polar2Rect()
1261 1342
1262 1343 [ra,dec,ha] = Astro_Coords.AltAz(vect_polar[1],vect_polar[0],self.junkjd).change2equatorial()
1263 1344
1264 1345 print'Main beam position (HA(min), DEC(degrees)): %f %f'%(ha*4.,dec)
1265 1346
1266 1347 self.main_dec = dec
1267 1348
1268 1349 self.ptitle = title
1269 1350
1270 Graphics_OverJro.AntPatternPlot().plotRaDec(gpath=self.path4plotname,filename=self.plotname0,jd=self.junkjd, ra_obs=self.ra_obs, xg=self.xg, yg=self.yg, x=ObjAnt.dcosx, y=ObjAnt.dcosy)
1351 Graphics_OverJro.AntPatternPlot().plotRaDec(gpath=self.path4plotname,
1352 filename=self.plotname0,
1353 jd=self.junkjd,
1354 ra_obs=self.ra_obs,
1355 xg=self.xg,
1356 yg=self.yg,
1357 x=ObjAnt.dcosx,
1358 y=ObjAnt.dcosy)
1271 1359
1272 1360 self.dcosx = ObjAnt.dcosx
1273 1361
1274 1362 self.dcosy = ObjAnt.dcosy
1275 1363
1276 1364 self.dcosxrange = [numpy.min(self.dcosx),numpy.max(self.dcosx)]
1277 1365
1278 1366 self.dcosyrange = [numpy.min(self.dcosy),numpy.max(self.dcosy)]
1279 1367
1280 1368 def plotBfield(self):
1281 1369
1282 1370 if self.show_object[0]>0:
1283 1371 # Getting B field
1284 1372 ObjB = BField(self.year,self.doy,self.site,self.heights)
1285 1373
1286 1374
1287 1375 [dcos, alpha, nlon, nlat] = ObjB.getBField()
1288 1376
1289 1377 # Plotting B field.
1290 1378 # print "Drawing magnetic field over Observatory"
1291 1379
1292 1380 Obj = Graphics_OverJro.BFieldPlot()
1293 1381
1294 1382 Obj.plotBField(self.path4plotname,self.plotname0,dcos,alpha,nlon,nlat,self.dcosxrange,self.dcosyrange,ObjB.heights,ObjB.alpha_i)
1295 1383
1296 1384 if self.show_object[0]>1:
1297 1385
1298 1386 Bhei = 0
1299 1387
1300 1388 dcosx = Obj.alpha_location[:,0,Bhei]
1301 1389
1302 1390 dcosy = Obj.alpha_location[:,1,Bhei]
1303 1391
1304 1392 vect_ant = [dcosx,dcosy,numpy.sqrt(1.-(dcosx**2. + dcosy**2.))]
1305 1393
1306 1394 vect_ant = numpy.array(vect_ant)
1307 1395
1308 1396 vect_geo = numpy.dot(scipy.linalg.inv(self.MT3),vect_ant)
1309 1397
1310 1398 vect_geo = numpy.array(vect_geo).transpose()
1311 1399
1312 1400 vect_polar = Misc_Routines.Vector(vect_geo,direction=1).Polar2Rect()
1313 1401
1314 1402 [ra,dec,ha] = Astro_Coords.AltAz(vect_polar[1,:],vect_polar[0,:],self.junkjd).change2equatorial()
1315 1403
1316 1404 val = numpy.where(ha>=180)
1317 1405
1318 1406 if val[0].size>0:ha[val] = ha[val] -360.
1319 1407
1320 1408 val = numpy.where(numpy.abs(ha)<=self.maxphi)
1321 1409
1322 1410 if val[0].size>2:
1323 1411
1324 1412 self.dcosx_mag = dcosx[val]
1325 1413
1326 1414 self.dcosy_mag = dcosy[val]
1327 1415
1328 1416 self.ha_mag = ha[val]
1329 1417
1330 1418 self.time_mag = 0
1331 1419
1332 1420 def plotCelestial(self):
1333 1421
1334 1422 ntod = 24.*16.
1335 1423
1336 1424 tod = numpy.arange(ntod)/ntod*24.
1337 1425
1338 1426 [month,dom] = TimeTools.Doy2Date(self.year,self.doy).change2date()
1339 1427
1340 1428 jd = TimeTools.Time(self.year,month,dom,tod+self.UT).change2julday()
1341 1429
1342 1430 if numpy.sum(self.show_object[1:]>0)!=0:
1343 1431
1344 1432 self.ObjC = Graphics_OverJro.CelestialObjectsPlot(jd,self.main_dec,tod,self.maxha_min,self.show_object)
1345 1433
1346 1434 self.ObjC.drawObject(self.glat,
1347 1435 self.glon,
1348 1436 self.xg,
1349 1437 self.yg,
1350 1438 self.dcosxrange,
1351 1439 self.dcosyrange,
1352 1440 self.path4plotname,
1353 1441 self.plotname0)
1354 1442
1355 1443 def plotAntennaCuts(self):
1356 1444 # print "Drawing antenna cuts"
1357 1445
1358 1446 incha = 0.05 # min
1359 1447 nha = numpy.int32(2*self.maxha_min/incha) + 1.
1360 1448 newha = numpy.arange(nha)/nha*2.*self.maxha_min - self.maxha_min
1361 1449 nha_star = numpy.int32(200./incha)
1362 1450 star_ha = (numpy.arange(nha_star) - (nha_star/2))*nha_star
1363 1451
1364 1452 #Init ObjCut for PatternCutPlot()
1365 1453 view_objects = numpy.where(self.show_object>0)
1366 1454 subplots = len(view_objects[0])
1367 1455 ObjCut = Graphics_OverJro.PatternCutPlot(subplots)
1368 1456
1369 1457 for io in (numpy.arange(5)):
1370 1458 if self.show_object[io]==2:
1371 1459 if io==0:
1372 1460 if self.dcosx_mag.size!=0:
1373 1461 dcosx = self.dcosx_mag
1374 1462 dcosy = self.dcosy_mag
1375 1463 dcosz = 1 - numpy.sqrt(dcosx**2. + dcosy**2.)
1376 1464
1377 1465 # Finding rotation of B respec to antenna coords.
1378 1466 [mm,bb] = scipy.polyfit(dcosx,dcosy,1)
1379 1467 alfa = 0.0
1380 1468 theta = -1.*numpy.arctan(mm)
1381 1469 sina = numpy.sin(alfa); cosa = numpy.cos(alfa)
1382 1470 MT1 = [[1,0,0],[0,cosa,-sina],[0,sina,cosa]]
1383 1471 MT1 = numpy.array(MT1)
1384 1472 sinb = numpy.sin(theta); cosb = numpy.cos(theta)
1385 1473 MT2 = [[cosb,sinb,0],[-sinb,cosb,0],[0,0,1]]
1386 1474 MT2 = numpy.array(MT2)
1387 1475 MT3_mag = numpy.dot(MT2, MT1)
1388 1476 MT3_mag = numpy.array(MT3_mag).transpose()
1389 1477 # Getting dcos respec to B coords
1390 1478 vector = numpy.array([dcosx,dcosy,dcosz])
1391 1479 nvector = numpy.dot(MT3_mag,vector)
1392 1480 nvector = numpy.array(nvector).transpose()
1393 1481
1394 1482 ## print 'Rotation (deg) %f'%(theta/Misc_Routines.CoFactors.d2r)
1395 1483
1396 1484 yoffset = numpy.sum(nvector[:,1])/nvector[:,1].size
1397 1485 # print 'Dcosyoffset %f'%(yoffset)
1398 1486
1399 1487 ha = self.ha_mag*4.
1400 1488 time = self.time_mag
1401 1489 width_star = 0.1 # half width in minutes
1402 1490 otitle = 'B Perp. cut'
1403 1491 # else:
1404 1492 # print "No B perp. over Observatory"
1405 1493 #
1406 1494 #
1407 1495 elif io==1:
1408 1496 if self.ObjC.dcosx_sun.size!=0:
1409 1497 dcosx = self.ObjC.dcosx_sun
1410 1498 dcosy = self.ObjC.dcosy_sun
1411 1499 ha = self.ObjC.ha_sun*4.0
1412 1500 time = self.ObjC.time_sun
1413 1501 width_star = 2. # half width in minutes
1414 1502 otitle = 'Sun cut'
1415 1503 # else:
1416 1504 # print "Sun is not passing over Observatory"
1417 1505
1418 1506 elif io==2:
1419 1507 if self.ObjC.dcosx_moon.size!=0:
1420 1508 dcosx = self.ObjC.dcosx_moon
1421 1509 dcosy = self.ObjC.dcosy_moon
1422 1510 ha = self.ObjC.ha_moon*4
1423 1511 time = self.ObjC.time_moon
1424 1512 m_distance = 404114.6 # distance to the Earth in km
1425 1513 m_diameter = 1734.4 # diameter in km.
1426 1514 width_star = numpy.arctan(m_distance/m_diameter)
1427 1515 width_star = width_star/2./Misc_Routines.CoFactors.d2r*4.
1428 1516 otitle = 'Moon cut'
1429 1517 # else:
1430 1518 # print "Moon is not passing over Observatory"
1431 1519
1432 1520 elif io==3:
1433 1521 if self.ObjC.dcosx_hydra.size!=0:
1434 1522 dcosx = self.ObjC.dcosx_hydra
1435 1523 dcosy = self.ObjC.dcosy_hydra
1436 1524 ha = self.ObjC.ha_hydra*4.
1437 1525 time = self.ObjC.time_hydra
1438 1526 width_star = 0.25 # half width in minutes
1439 1527 otitle = 'Hydra cut'
1440 1528 # else:
1441 1529 # print "Hydra is not passing over Observatory"
1442 1530
1443 1531 elif io==4:
1444 1532 if self.ObjC.dcosx_galaxy.size!=0:
1445 1533 dcosx = self.ObjC.dcosx_galaxy
1446 1534 dcosy = self.ObjC.dcosy_galaxy
1447 1535 ha = self.ObjC.ha_galaxy*4.
1448 1536 time = self.ObjC.time_galaxy
1449 1537 width_star = 25. # half width in minutes
1450 1538 otitle = 'Galaxy cut'
1451 1539 # else:
1452 1540 # print "Galaxy center is not passing over Jicamarca"
1453 1541 #
1454 1542 #
1455 1543 hour = numpy.int32(time)
1456 1544 mins = numpy.int32((time - hour)*60.)
1457 1545 secs = numpy.int32(((time - hour)*60. - mins)*60.)
1458 1546
1459 1547 ObjT = TimeTools.Time(self.year,self.month,self.dom,hour,mins,secs)
1460 1548 subtitle = ObjT.change2strdate()
1461 1549
1462 1550 star_cut = numpy.exp(-(star_ha/width_star)**2./2.)
1463 1551
1464 1552 pol = scipy.polyfit(ha,dcosx,3.)
1465 1553 polx = numpy.poly1d(pol); newdcosx = polx(newha)
1466 1554 pol = scipy.polyfit(ha,dcosy,3.)
1467 1555 poly = numpy.poly1d(pol);newdcosy = poly(newha)
1468 1556
1469 1557 patterns = []
1470 1558 for icut in numpy.arange(self.pattern.size):
1471 1559 # Getting Antenna cut.
1472 1560 Obj = JroPattern(dcosx=newdcosx,
1473 1561 dcosy=newdcosy,
1474 1562 getcut=1,
1475 1563 pattern=self.pattern[icut],
1476 1564 path=self.path,
1477 1565 filename=self.filename[icut])
1478 1566
1479 1567 Obj.getPattern()
1480 1568
1481 1569 patterns.append(Obj.pattern)
1482 1570
1483 1571
1484 1572 ObjCut.drawCut(io,
1485 1573 patterns,
1486 1574 self.pattern.size,
1487 1575 newha,
1488 1576 otitle,
1489 1577 subtitle,
1490 1578 self.ptitle)
1491 1579
1492 1580 ObjCut.saveFig(self.path4plotname,self.plotname1)
1493 1581
1494 1582 def plotSkyNoise(self):
1495 1583 # print 'Creating SkyNoise map over Jicamarca'
1496 1584 dom = self.dom
1497 1585 month = self.month
1498 1586 year = self.year
1499 1587
1500 1588 julian = TimeTools.Time(year,month,dom).change2julday()
1501 1589
1502 1590 [powr,time, lst] = Astro_Coords.CelestialBodies().skyNoise(julian)
1503 1591
1504 1592 Graphics_OverJro.SkyNoisePlot([year,month,dom],powr,time,lst).getPlot(self.path4plotname,self.plotname2)
1505 1593
1506 1594
1507 1595 def outputHead(self,title):
1508 1596 print "Content-Type: text/html"
1509 1597 print
1510 1598 self.scriptHeaders = 1
1511 1599 print '<html>'
1512 1600 print '<head>'
1513 1601 print '\t<title>' + title + '</title>'
1514 1602 print '<style type="text/css">'
1515 1603 print 'body'
1516 1604 print '{'
1517 1605 print 'background-color:#ffffff;'
1518 1606 print '}'
1519 1607 print 'h1'
1520 1608 print '{'
1521 1609 print 'color:black;'
1522 1610 print 'font-size:18px;'
1523 1611 print 'text-align:center;'
1524 1612 print '}'
1525 1613 print 'p'
1526 1614 print '{'
1527 1615 print 'font-family:"Arial";'
1528 1616 print 'font-size:16px;'
1529 1617 print 'color:black;'
1530 1618 print '}'
1531 1619 print '</style>'
1532 1620 # self.printJavaScript()
1533 1621 print '</head>'
1534 1622
1535 1623 def printJavaScript(self):
1536 1624 print
1537 1625
1538 1626 def printBody(self):
1539 1627 print '<body>'
1540 1628 # print '<h1>Test Input Parms</h1>'
1541 1629 # for key in self.madForm.keys():
1542 1630 # #print '<p> name=' + str(key)
1543 1631 # if type(self.madForm.getvalue(key)) == types.ListType:
1544 1632 # for value in self.madForm.getvalue(key):
1545 1633 # print '<p> name=' + str(key) + \
1546 1634 # ' value=' + value + ''
1547 1635 # else:
1548 1636 # print '<p> name=' + str(key) + \
1549 1637 # ' value=' + str(cgi.escape(self.madForm.getvalue(key))) + ''
1550 1638
1551 1639 print '<form name="form1" method="post" target="showFrame">'
1552 1640 print ' <div align="center">'
1553 1641 print ' <table width=98% border="1" cellpadding="1">'
1554 1642 print ' <tr>'
1555 1643 print ' <td colspan="2" align="center">'
1556 1644 if self.showType == 0:
1557 1645 print ' <IMG SRC="%s" BORDER="0" >'%(os.path.join(os.sep + self.__tmpDir,self.plotname0))
1558 1646 if self.showType == 1:
1559 1647 print ' <IMG SRC="%s" BORDER="0" >'%(os.path.join(os.sep + self.__tmpDir,self.plotname1))
1560 1648 if self.showType == 2:
1561 1649 print ' <IMG SRC="%s" BORDER="0" >'%(os.path.join(os.sep + self.__tmpDir,self.plotname2))
1562 1650 print ' </td>'
1563 1651 print ' </tr>'
1564 1652 print ' </table>'
1565 1653 print ' </div>'
1566 1654 print '</form>'
1567 1655
1568 1656 print '</body>'
1569 1657 print '</html>'
1570 1658
1571 1659 #def execute(self, serverdocspath, tmpdir, currentdate, finalpath, showType=0, maxphi=5.0, objects="[1,1]", heights="[150,500,1000]"):
1572 1660 def setInputParameters(self, serverpath, currentdate, finalpath, showType=0, maxphi=5.0, objects="[1,1]", heights="[150,500,1000]"):
1573 1661 self.objects=[]
1574 1662 self.heights=[]
1575 1663 #self.__serverdocspath = serverdocspath
1576 1664 self.__serverdocspath = os.path.split(serverpath)[0]
1577 1665 #self.__tmpDir = tmpdir
1578 1666 self.__tmpDir = os.path.split(serverpath)[1]
1579 1667 self.showType = int(showType)
1580 1668 self.year = int(currentdate.strftime("%Y")) # Get year of currentdate
1581 1669 self.month = int(currentdate.strftime("%m")) # Get month of currentdate
1582 1670 self.dom = int(currentdate.strftime("%d")) # Get day of currentdate
1583 1671 self.filename = os.path.split(finalpath)[1]
1584 1672 self.path = os.path.split(finalpath)[0]
1585 1673 self.maxphi = float(maxphi)
1586 1674
1587 1675 tmp_objects = (objects.replace("[","")).replace("]","")
1588 1676 for s in tmp_objects.split(','):
1589 1677 self.objects.append(int(s))
1590 1678
1591 1679 tmp_heights = (heights.replace("[","")).replace("]","")
1592 1680 for s in tmp_heights.split(','):
1593 1681 self.heights.append(float(s))
1594 1682 self.heights = numpy.array(self.heights)
1595 1683
1596 1684 def setupParameters(self):
1597 1685 self.initParameters()
1598 1686
1599 1687 def initParametersCGI(self):
1600 1688 self.setScriptState()
1601 1689 self.initParameters()
1602 1690
1603 1691 def execute(self):
1604 1692 if self.showType == 0 or self.showType == 1:
1605 1693 self.initParameters1()
1606 1694 self.plotPattern()
1607 1695
1608 1696 if numpy.sum(self.show_object>0) != 0:
1609 1697 self.plotBfield()
1610 1698 self.plotCelestial()
1611 1699
1612 1700 if numpy.sum(self.show_object>1) != 0:
1613 1701 self.plotAntennaCuts()
1614 1702
1615 1703 if self.showType == 2:
1616 1704 self.plotSkyNoise()
1617 1705
1618 1706 def getPlot(self):
1619 print "GETPLot"
1620 print os.path.join(self.__serverdocspath,self.__tmpDir,self.plotname0)
1707
1621 1708 return os.path.join(self.__serverdocspath,self.__tmpDir,self.plotname0)
1622 1709
1623 1710
1624 1711 if __name__ == '__main__':
1625 1712
1626 1713 # Script overJroShow.py
1627 1714 # This script only calls the init function of the class overJroShow()
1628 1715 # All work is done by the init function
1629 1716
1630 newOverJro = overJroShow()
1631 newOverJro.initParametersCGI()
1632 newOverJro.execute()
1717 phases = numpy.array([[2.0,0.0,1.5,1.5,1.0,1.0,1.0,0.5],
1718 [2.0,2.5,2.5,3.5,0.5,1.0,1.0,1.0],
1719 [2.5,2.5,1.0,1.0,0.5,0.5,0.5,0.5],
1720 [1.0,1.0,1.0,1.0,0.5,0.5,0.5,1.0],
1721 [0.5,0.5,0.5,0.5,0.5,0.0,0.0,0.0],
1722 [0.5,0.5,1.0,0.5,0.0,0.0,0.0,0.0],
1723 [0.5,0.5,0.5,1.0,0.0,0.0,0.0,0.0],
1724 [0.5,0.5,0.5,0.5,0.0,0.0,0.0,0.0]])
1725
1726 gain_tx = numpy.array([[0,0,0,0,0,0,0,0],
1727 [0,0,0,0,0,0,0,0],
1728 [0,0,0,0,0,0,0,0],
1729 [0,0,0,0,0,0,0,0],
1730 [0,0,0,0,1,1,1,1],
1731 [0,0,0,0,0,0,0,0],
1732 [0,0,0,0,0,0,0,0],
1733 [0,0,0,0,0,0,0,0]])
1734
1735 gain_rx = numpy.array([[0,0,0,0,0,0,0,0],
1736 [0,0,1,0,0,0,0,0],
1737 [0,0,1,0,0,0,0,0],
1738 [0,0,0,0,0,0,0,0],
1739 [0,0,0,0,0,0,0,0],
1740 [0,0,0,0,0,0,0,0],
1741 [0,0,0,0,0,0,0,0],
1742 [0,0,0,0,0,0,0,0]])
1743
1744 jro = overJroShow()
1745
1746 fig = jro.plotPattern2(datetime.datetime.today(),
1747 phases=phases,
1748 gain_tx=gain_tx,
1749 gain_rx=gain_rx,
1750 ues=numpy.array([0.0,0.0,0.0,0.0]),
1751 just_rx=0)
1752
1753 fig.savefig('./pat.png')
1754
@@ -1,482 +1,365
1 1 from django.shortcuts import render_to_response
2 2 from django.template import RequestContext
3 3 from django.shortcuts import redirect, render, get_object_or_404
4 4 from django.contrib import messages
5 5 from django.conf import settings
6 6 from django.http import HttpResponse
7 7
8 8 from datetime import datetime
9 9 from time import sleep
10 10 import os
11 11
12 12 from apps.main.models import Device, Configuration
13 13 from apps.main.views import sidebar
14 14
15 15 from .models import ABSConfiguration, ABSBeam
16 16 from .forms import ABSConfigurationForm, ABSBeamEditForm, ABSBeamAddForm
17 17
18 18 from .utils.overJroShow import overJroShow
19 19 from .utils.OverJRO import OverJRO
20 20 # Create your views here.
21 21 import json, ast
22 22
23 23
24 24 def get_values_from_form(form_data):
25 25
26 26 sublistup = []
27 27 sublistdown = []
28 28 subtxlistup = []
29 29 subtxlistdown = []
30 30 subrxlistup = []
31 31 subrxlistdown = []
32 32
33 33 up_values_list = []
34 34 down_values_list = []
35 35 up_txvalues_list = []
36 36 down_txvalues_list = []
37 37 up_rxvalues_list = []
38 38 down_rxvalues_list = []
39 39
40 40 values_list = {}
41 41 cont = 1
42 42
43 43 for i in range(1,65):
44 44 x = float(form_data['abs_up'+str(i)])
45 45 y = float(form_data['abs_down'+str(i)])
46 46 sublistup.append(x)
47 47 sublistdown.append(y)
48 48
49 49 if str(i) in form_data.getlist('uptx_checks'):
50 50 subtxlistup.append(1)
51 51 else:
52 52 subtxlistup.append(0)
53 53 if str(i) in form_data.getlist('downtx_checks'):
54 54 subtxlistdown.append(1)
55 55 else:
56 56 subtxlistdown.append(0)
57 57
58 58 if str(i) in form_data.getlist('uprx_checks'):
59 59 subrxlistup.append(1)
60 60 else:
61 61 subrxlistup.append(0)
62 62 if str(i) in form_data.getlist('downrx_checks'):
63 63 subrxlistdown.append(1)
64 64 else:
65 65 subrxlistdown.append(0)
66 66
67 67 cont = cont+1
68 68
69 69 if cont == 9:
70 70 up_values_list.append(sublistup)
71 71 down_values_list.append(sublistdown)
72 72 sublistup = []
73 73 sublistdown = []
74 74
75 75 up_txvalues_list.append(subtxlistup)
76 76 down_txvalues_list.append(subtxlistdown)
77 77 subtxlistup = []
78 78 subtxlistdown = []
79 79 up_rxvalues_list.append(subrxlistup)
80 80 down_rxvalues_list.append(subrxlistdown)
81 81 subrxlistup = []
82 82 subrxlistdown = []
83 83 cont = 1
84 84
85 85
86 86 list_uesup = []
87 87 list_uesdown = []
88 88 for i in range(1,5):
89 89 if form_data['ues_up'+str(i)] == '':
90 90 list_uesup.append(0.0)
91 91 else:
92 92 list_uesup.append(float(form_data['ues_up'+str(i)]))
93 93
94 94 if form_data['ues_down'+str(i)] == '':
95 95 list_uesdown.append(0.0)
96 96 else:
97 97 list_uesdown.append(float(form_data['ues_down'+str(i)]))
98 98
99 99 onlyrx_list = form_data.getlist('onlyrx')
100 100 only_rx = {}
101 101 if '1' in onlyrx_list:
102 102 only_rx['up'] = True
103 103 else:
104 104 only_rx['up'] = False
105 105 if '2' in onlyrx_list:
106 106 only_rx['down'] = True
107 107 else:
108 108 only_rx['down'] = False
109 109
110 110 antenna = {'antenna_up': up_values_list, 'antenna_down': down_values_list}
111 111 tx = {'up': up_txvalues_list, 'down': down_txvalues_list}
112 112 rx = {'up': up_rxvalues_list, 'down': down_rxvalues_list}
113 113 ues = {'up': list_uesup, 'down': list_uesdown}
114 114 name = str(form_data['beam_name'])
115 115
116 116 beam_data = {'name': name, 'antenna': antenna, 'tx': tx, 'rx': rx, 'ues': ues, 'only_rx': only_rx}
117 117
118 118 return beam_data
119 119
120 120
121 121
122 122 def abs_conf(request, id_conf):
123 123
124 124 conf = get_object_or_404(ABSConfiguration, pk=id_conf)
125 125
126 126 beams_dict = ast.literal_eval(conf.beams)
127 127 beams = []
128 128 for beam_id in range(1,len(beams_dict)+1):
129 129 beam = ABSBeam.objects.get(pk=beams_dict['beam'+str(beam_id)])
130 130 beams.append(beam)
131 131
132 132 beams_id = ast.literal_eval(conf.beams)
133 133
134 134 ip=conf.device.ip_address
135 135 port=conf.device.port_address
136 136
137 137 kwargs = {}
138 138 kwargs['status'] = conf.device.get_status_display()
139 139
140 140
141 141 kwargs['dev_conf'] = conf
142 142 kwargs['dev_conf_keys'] = ['name',]
143 143
144 144 kwargs['title'] = 'ABS Configuration'
145 145 kwargs['suptitle'] = 'Details'
146 146 kwargs['no_play'] = True
147 147
148 148 kwargs['button'] = 'Edit Configuration'
149 149
150 150 #kwargs['no_play'] = True
151 151 kwargs['beams_id'] = beams_id
152 152 kwargs['beams'] = beams
153 153 kwargs['beam_selector'] = 0
154 154 #kwargs['my_data'] = simplejson.dumps(beams)
155 155
156 156 kwargs['only_stop'] = True
157 157
158 158 ###### SIDEBAR ######
159 159 kwargs.update(sidebar(conf=conf))
160 160
161 161 return render(request, 'abs_conf.html', kwargs)
162 162
163 163 def abs_conf_edit(request, id_conf):
164 164
165 165 conf = get_object_or_404(ABSConfiguration, pk=id_conf)
166 166 beams_list = ast.literal_eval(conf.beams)
167 167 i = 1
168 168 beams = []
169 169 for b in beams_list:
170 170 beam = ABSBeam.objects.get(pk=beams_list['beam'+str(i)])
171 171 beams.append(beam)
172 172 i=i+1
173 173
174 174 if request.method=='GET':
175 175 form = ABSConfigurationForm(instance=conf)
176 176
177 177 if request.method=='POST':
178 178 form = ABSConfigurationForm(request.POST, instance=conf)
179 179
180 180 if form.is_valid():
181 181 conf = form.save(commit=False)
182 182 conf.save()
183 183 return redirect('url_abs_conf', id_conf=conf.id)
184 184
185 185 ###### SIDEBAR ######
186 186 kwargs = {}
187 187
188 188 kwargs['dev_conf'] = conf
189 189 #kwargs['id_dev'] = conf.id
190 190 kwargs['id_conf'] = conf.id
191 191 kwargs['form'] = form
192 192 kwargs['abs_beams'] = beams
193 193 kwargs['title'] = 'Device Configuration'
194 194 kwargs['suptitle'] = 'Edit'
195 195 kwargs['button'] = 'Save'
196 196
197 197 kwargs['edit'] = True
198 198
199 199 return render(request, 'abs_conf_edit.html', kwargs)
200 200
201 201
202 202
203 203
204 204 def add_beam(request, id_conf):
205 205
206 206 conf = get_object_or_404(ABSConfiguration, pk=id_conf)
207 207 confs = Configuration.objects.all()
208 208
209 209 if request.method=='GET':
210 210 #form = ABSBeamEditForm()
211 211 form = ABSBeamAddForm()
212 212
213 213 if request.method=='POST':
214 214 form = ABSBeamAddForm(request.POST)
215 215
216 216 beam_data = get_values_from_form(request.POST)
217 217
218 218 new_beam = ABSBeam(
219 219 name =beam_data['name'],
220 220 antenna =json.dumps(beam_data['antenna']),
221 221 abs_conf=conf,
222 222 tx =json.dumps(beam_data['tx']),
223 223 rx =json.dumps(beam_data['rx']),
224 224 ues =json.dumps(beam_data['ues']),
225 225 only_rx =json.dumps(beam_data['only_rx'])
226 226 )
227 227 new_beam.save()
228 228 #---Update 6bits configuration and add beam to abs configuration beams list.
229 229 new_beam.modules_6bits()
230 230 new_beam.add_beam2list()
231 231 messages.success(request, 'Beam: "%s" has been added.' % new_beam.name)
232 232
233 233 return redirect('url_edit_abs_conf', conf.id)
234 234
235 235 ###### SIDEBAR ######
236 236 kwargs = {}
237 237
238 238 #kwargs['dev_conf'] = conf.device
239 239 #kwargs['id_dev'] = conf.device
240 240 kwargs['id_conf'] = conf.id
241 241 kwargs['form'] = form
242 242 kwargs['title'] = 'ABS Beams'
243 243 kwargs['suptitle'] = 'Add Beam'
244 244 kwargs['button'] = 'Add'
245 245 kwargs['no_sidebar'] = True
246 246
247 247 #kwargs['previous'] = conf.get_absolute_url_edit()
248 248 kwargs['edit'] = True
249 249
250 250 return render(request, 'abs_add_beam.html', kwargs)
251 251
252 252
253 253 def edit_beam(request, id_conf, id_beam):
254 254
255 255 conf = get_object_or_404(ABSConfiguration, pk=id_conf)
256 256 beam = get_object_or_404(ABSBeam, pk=id_beam)
257 257
258 258 if request.method=='GET':
259 259 form = ABSBeamEditForm(initial={'beam': beam})
260 260
261 261 if request.method=='POST':
262 262 form = ABSBeamEditForm(request.POST)
263 263
264 264 beam_data = get_values_from_form(request.POST)
265 265
266 266 beam.dict_to_parms(beam_data)
267 267 beam.save()
268 268
269 269 messages.success(request, 'Beam: "%s" has been updated.' % beam.name)
270 270
271 271 return redirect('url_edit_abs_conf', conf.id)
272 272
273 273 ###### SIDEBAR ######
274 274 kwargs = {}
275 275
276 276 kwargs['id_conf'] = conf.id
277 277 kwargs['form'] = form
278 278 kwargs['title'] = 'ABS Beams'
279 279 kwargs['suptitle'] = 'Edit Beam'
280 280 kwargs['button'] = 'Save'
281 281 kwargs['no_sidebar'] = True
282 282
283 283 #kwargs['previous'] = conf.get_absolute_url_edit()
284 284 kwargs['edit'] = True
285 285
286 286 return render(request, 'abs_edit_beam.html', kwargs)
287 287
288 288
289 289
290 290 def remove_beam(request, id_conf, id_beam):
291 291
292 292 conf = get_object_or_404(ABSConfiguration, pk=id_conf)
293 293 beam = get_object_or_404(ABSBeam, pk=id_beam)
294 294
295 295 if request.method=='POST':
296 296 if beam:
297 297 try:
298 298 beam.remove_beamfromlist()
299 299 beam.delete()
300 300 messages.success(request, 'Beam: "%s" has been deleted.' % beam)
301 301 except:
302 302 messages.error(request, 'Unable to delete beam: "%s".' % beam)
303 303
304 304 return redirect('url_edit_abs_conf', conf.id)
305 305
306 306 ###### SIDEBAR ######
307 307 kwargs = {}
308 308
309 309 kwargs['object'] = beam
310 310 kwargs['delete'] = True
311 311 kwargs['title'] = 'Delete'
312 312 kwargs['suptitle'] = 'Beam'
313 313 kwargs['previous'] = conf.get_absolute_url_edit()
314 314 return render(request, 'confirm.html', kwargs)
315 315
316 316
317 317
318 def plot_patterns(request, id_conf):
318 def plot_patterns(request, id_conf, id_beam=None):
319 319
320 conf = get_object_or_404(ABSConfiguration, pk=id_conf)
321 beams_list = ast.literal_eval(conf.beams)
322 i = 1
323 beams = []
324 for b in beams_list:
325 beam = ABSBeam.objects.get(pk=beams_list['beam'+str(i)])
326 beams.append(beam)
327 i=i+1
328
329 ###### SIDEBAR ######
330 320 kwargs = {}
331
332 kwargs['dev_conf'] = conf.device
333 kwargs['id_dev'] = conf.device
334 kwargs['id_conf'] = conf.id
335 kwargs['abs_beams'] = beams
336 kwargs['title'] = 'ABS Patterns'
337 kwargs['suptitle'] = conf.name
338 kwargs['no_sidebar'] = True
339
340 return render(request, 'abs_patterns.html', kwargs)
341
342
343 def plot_pattern(request, id_conf, id_beam):
344
345 321 conf = get_object_or_404(ABSConfiguration, pk=id_conf)
322 beams = ABSBeam.objects.filter(abs_conf=conf)
323
324 if id_beam:
346 325 beam = get_object_or_404(ABSBeam, pk=id_beam)
326 kwargs['beam'] = beam
347 327
348 #Lista de Beams de la configuracion con su respectivo ID
349 beams_list = ast.literal_eval(conf.beams)
350 i = 1
351 #Lista de Objetos ABSBeams en el 0rden de su respectiva configuracion
352 beams = []
353 for b in beams_list:
354 beam = ABSBeam.objects.get(pk=beams_list['beam'+str(i)])
355 beams.append(beam)
356 i=i+1
357 328
358 329 ###### SIDEBAR ######
359 beam = get_object_or_404(ABSBeam, pk=id_beam)
360 kwargs = {}
361 330
362 331 kwargs['dev_conf'] = conf.device
363 332 kwargs['id_dev'] = conf.device
364 333 kwargs['id_conf'] = conf.id
365 334 kwargs['abs_beams'] = beams
366 kwargs['beam'] = beam
367 335 kwargs['title'] = 'ABS Patterns'
368 336 kwargs['suptitle'] = conf.name
369 337 kwargs['no_sidebar'] = True
370 338
371 339 return render(request, 'abs_patterns.html', kwargs)
372 340
373 341
342 def plot_pattern(request, id_conf, id_beam, antenna):
374 343
375 def plot_uppattern(request, id_conf, id_beam):
376
377 from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
344 if antenna=='down':
345 sleep(3)
378 346
379 347 conf = get_object_or_404(ABSConfiguration, pk=id_conf)
380 348 beam = get_object_or_404(ABSBeam, pk=id_beam)
381 349
382 exp_name = conf.experiment.name
383
384 just_rx = 0
385
386 only_rx = json.loads(beam.only_rx)
387 if only_rx['up'] == True:
388 just_rx = 1
350 name = conf.experiment.name
389 351
390 antenna = ast.literal_eval(beam.antenna)
391 objAntenna = json.dumps(antenna['antenna_up'])
392 antenna_up = ''.join(str(i) for i in objAntenna)
393 phase_tx = antenna_up.replace(' ','')
352 just_rx = 1 if json.loads(beam.only_rx)[antenna] else 0
353 phases = json.loads(beam.antenna)['antenna_{}'.format(antenna)]
354 gain_tx = json.loads(beam.tx)[antenna]
355 gain_rx = json.loads(beam.rx)[antenna]
356 ues = json.loads(beam.ues)[antenna]
394 357
395 tx = ast.literal_eval(beam.tx)
396 tx = json.dumps(tx['up'])
397 tx = ''.join(str(i) for i in tx)
398 gain_tx = tx.replace(' ','')
358 newOverJro = overJroShow(name)
359 fig = newOverJro.plotPattern2(datetime.today(), phases, gain_tx, gain_rx, ues, just_rx)
399 360
400 rx = ast.literal_eval(beam.rx)
401 rx = json.dumps(rx['up'])
402 rx = ''.join(str(i) for i in rx)
403 gain_rx = rx.replace(' ','')
404
405 ues = json.dumps(beam.get_up_ues)
406 ues = ''.join(str(i) for i in ues)
407 ues_tx = ues.replace(' ','')
408
409 #sleep(1)
410
411 overjro = OverJRO()
412 overjro.setParameters(settings.MEDIA_ROOT, exp_name, phase_tx, gain_tx, gain_rx, ues_tx, just_rx)
413 contentFile = overjro.setTextContent()
414 finalpath = overjro.saveFile(contentFile)
415
416 currentdate = datetime.today()
417 newOverJro = overJroShow()
418 newOverJro.setInputParameters(settings.MEDIA_ROOT, currentdate, finalpath)
419 newOverJro.setupParameters()
420 newOverJro.execute()
421 path = newOverJro.getPlot()
422 path= "apps/abs/media/"+path
423
424
425 canvas=FigureCanvas(newOverJro.figure)
426 361 response=HttpResponse(content_type='image/png')
427 canvas.print_png(response)
428 return response
429 362
430 def plot_downpattern(request, id_conf, id_beam):
363 fig.canvas.print_png(response)
431 364
432 sleep(4)
433 from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
434
435 conf = get_object_or_404(ABSConfiguration, pk=id_conf)
436 beam = get_object_or_404(ABSBeam, pk=id_beam)
437
438 exp_name = conf.experiment.name
439
440 just_rx = 0
441
442 only_rx = json.loads(beam.only_rx)
443 if only_rx['down'] == True:
444 just_rx = 1
445
446 antenna = ast.literal_eval(beam.antenna)
447 objAntenna = json.dumps(antenna['antenna_down'])
448 antenna_down = ''.join(str(i) for i in objAntenna)
449 phase_tx = antenna_down.replace(' ','')
450
451 tx = ast.literal_eval(beam.tx)
452 tx = json.dumps(tx['down'])
453 tx = ''.join(str(i) for i in tx)
454 gain_tx = tx.replace(' ','')
455
456 rx = ast.literal_eval(beam.rx)
457 rx = json.dumps(rx['down'])
458 rx = ''.join(str(i) for i in rx)
459 gain_rx = rx.replace(' ','')
460
461 ues = json.dumps(beam.get_down_ues)
462 ues = ''.join(str(i) for i in ues)
463 ues_tx = ues.replace(' ','')
464
465 overjro = OverJRO()
466 overjro.setParameters(settings.MEDIA_ROOT, exp_name, phase_tx, gain_tx, gain_rx, ues_tx, just_rx)
467 contentFile = overjro.setTextContent()
468 finalpath = overjro.saveFile(contentFile)
469
470 currentdate = datetime.today()
471 newOverJro = overJroShow()
472 newOverJro.setInputParameters(settings.MEDIA_ROOT, currentdate, finalpath)
473 newOverJro.setupParameters()
474 newOverJro.execute()
475 path = newOverJro.getPlot()
476 path= "apps/abs/media/"+path
477
478
479 canvas=FigureCanvas(newOverJro.figure)
480 response=HttpResponse(content_type='image/png')
481 canvas.print_png(response)
482 365 return response
General Comments 0
You need to be logged in to leave comments. Login now