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