PyEphem Rise/Set Azimuths for Stars and Constellations - pyephem

I can't seem to figure out how to calculate an azimuth of a star, let's say Sirius, when it is at alt=0 (star rise/star set).
So essentially in the end I will have two values.
Sirius.az # star rise
Sirius.az # star set
Is this possible?
THANKS!

Simply check the .az attribute of the star once your observer object has determined the moment of rising or setting. For example:
import ephem
s = ephem.star('Sirius')
boston = ephem.Observer()
boston.lat = '42.37'
boston.lon = '-71.03'
boston.next_rising(s)
print s.alt, s.az
boston.next_setting(s)
print s.alt, s.az
Running this script at this moment gives me the encouraging output:
0:00:00.0 112:23:25.2
0:00:00.0 247:36:34.9
As you can see, the rising and setting routines have already established the moment of zero altitude, leaving the azimuth for you to read off and use!

Related

Confused about get_rays function in NeRF

I've been trying to understand NeRF. I finished reading the paper(Tancik) and watched some of the videos. I have been looking at some parts of the code. However, I can't quite wrap my head around what the get_rays function does in terms of the code. Could anybody just run through line-by-line about what each line in the the get_rays function is supposed to do?
def get_rays(H,W , focal, c2w): #c2w is pose
i, j = tf.meshgrid(tf.range(W, dtype=tf.float32), tf.range(H, dtype=tf.float32), indexing='xy')
dirs = tf.stack([(i-W*.5)/focal, -(j-H*.5)/focal, -tf.ones_like(i)], -1)
rays_d = tf.reduce_sum(dirs[..., np.newaxis, :] * c2w[:3,:3], -1)
rays_o = tf.broadcast_to(c2w[:3,-1], tf.shape(rays_d))
return rays_o, rays_d
It creates two lists, rays_o represents points where rays originate (camera centre) and rays_d represents direction vectors of each ray casting through the centre of every pixel of the camera. In this case, all values in the rays_o are the same because the function gets rays from a single camera.

rnd:weighted-one-of-list work doesn't return the distribution I think it should

I trying to use the rnd extension's function weighted-one-of-list.
My list looks like
observer>show female-yr-run-stats
observer: [[117 0.001169] [118 0.002684] [119 0.004697] [120 0.003368] [121 0.004871] [122 0.018738] [123 0.034986] [124 0.070616] [125 0.035608] [126 0.012939] [127 0.011883] [128 0.016594] [129 0.068837] [130 0.044391] [131 0.028422] [132 0.053251] [133 0.023741] [134 0.042111] [135 0.035811] [136 0.022447] [137 0.031563] [138 0.024253] [139 0.030213] [140 0.024372] [141 0.033266] [142 0.059869] [143 0.028711] [144 0.030863] [145 0.04043] [146 0.008819] [147 0.012308] [148 0.008638] [149 0.021345] [150 0.016176] [151 0.009815] [152 0.017242] [153 0.014362] [154 0.010717] [155 0.015868] [156 0.003865] [157 0.008441] [158 0.004358] [159 0.003113] [160 0.002464] [161 0.001768]]
The first item is day-of-the-year and the second is the probability (all sum to one).
I am using the code
repeat 50000[
let tempo first rnd:weighted-one-of-list female-yr-run-stats [ [p] -> last p ]
file-open "C://temp//check_wgt_random.csv"
file-print (word tempo)
file-close
]
to randomly select a day-of-the-year 50000 times to check that the rnd:weighted-one-of-list function is doing what I want it to do. From the results, I get a distribution of day-of-the-year. But when I compare the resulting distribution to the original probability distribution, they are quite different.
I am thinking that the rnd:weighted-one-of-list with my list would be equivalent to randomly drawing from a multinomial distribution like R's rmultinom function. Am I correct? Am I doing something wrong?
Any help would be appreciated.
The graph below shows the comparisons
The rnd:weighted-one-of-list primitive works the way (I think) you think it works. From your data, it draws the value 112 with probability 3.04E-4, value 113 with probability 0.001236 etc. The probabilities don't have to add to 1 (I have assumed that you are correct that yours do). I can't see anything wrong with your use of this primitive for your draws.
But I am not sure about the file construction. You have the file-open and file-close inside the repeat so the file is opened, the new data is appended, the file is closed. It is not clear whether you ever clear the dataset. So perhaps the problem is that you have some data left over from when you were building your code. Do you get the same problem if you clear out all the old data and start again?
Sorry to waste your time. I discovered what happened. I had two probabilities stream mixed up.

Gantt Chart in Matlab

Do you know how to plot a Gantt chart in Matlab without using a third-party software?
At the end I would love to obtain something like this:
What I was able to obtain so far is
using this code:
% Create data for childhood disease cases
measles = [38556 24472 14556 18060 19549 8122 28541 7880 3283 4135 7953 1884]';
mumps = [20178 23536 34561 37395 36072 32237 18597 9408 6005 6268 8963 13882]';
chickenPox = [37140 32169 37533 39103 33244 23269 16737 5411 3435 6052 12825 23332]';
% Create a stacked bar chart using the bar function
fig = figure;
bar(1:12, [measles mumps chickenPox], 0.5, 'stack');
axis([0 13 0 100000]);
title('Childhood diseases by month');
xlabel('Month');
ylabel('Cases (in thousands)');
legend('Measles', 'Mumps', 'Chicken pox');
That is not what I want but, maybe, goes in this direction
Here, I share the solution I have just found (maybe it is not the most elegant one but it works for the purpose I have):
[the main idea is to draw a bar and "delete" the beginning overdrawing up on it another white bar]
Let's say you have two vector:
start =[6907402; 2282194; 4579536; 2300332; 10540; 2307970; 4603492; 0];
stop =[9178344; 9168694;6895050; 4571400; 2280886; 4579044; 6897152 ;2271186];
There are 8 elements in each: every element is a task. In the start array, there is the start time of each task and in stop there is the end of the "execution" of a given task.
barh(stop)
hold on
barh(start,'w')
At the end here you have the Gantt:
UPDATE:
My scripts are evolved of course and, more, on the matlab website, there is more information. Here 2 example more to complete the answer:
Option 1:
Positions=[1,2,3,4];
Gap_Duration=[0,2,5,3,5,3;
3,5,3,5,3,4;
9,3,0,0,12,2;
13,2,2,2,8,3];
barh(Positions,Gap_Duration,'stacked');
Option 2:
Positions=[1,2,3,4];
Gap_Duration=[0,2,5,3,5,3;
3,5,3,5,3,4;
9,3,0,0,12,2;
13,2,2,2,8,3];
barh(Positions,Gap_Duration,'stacked');
set(H([1 3 5]),'Visible','off')

different RA/Decs returned by pyEphem

I using pyEphem to calculate RA/Decs of satellites and I'm confused by the different
values computed and described on
http://rhodesmill.org/pyephem/radec.html
this bit of code
sat=ephem.readtle("SATNAME ", \
"1 38356U 12030A 14148.90924578 .00000000 00000-0 10000-3 0 5678",\
"2 38356 0.0481 47.9760 0002933 358.9451 332.7970 1.00270012 3866")
gatech = ephem.Observer()
gatech.lon, gatech.lat = '-155.47322222', '19.82561111'
gatech.elevation = 4194
gatech.date = '2014/01/02 07:05:52'
sat.compute(gatech)
print 'a_ra=',sat.a_ra,'a_dec=',sat.a_dec,'g_ra=',sat.g_ra,'g_dec=',sat.g_dec,'ra=',sat.ra,'dec=',sat.dec
gives
a_ra= 0:52:40.75 a_dec= -3:15:23.7 g_ra= 1:14:10.55 g_dec= 0:06:09.8 ra= 0:53:23.57 dec= -3:10:50.5
if I change JUST the observers location to say
gatech.lon, gatech.lat = '-5.47322222', '19.82561111'
I get
a_ra= 1:15:36.95 a_dec= -2:32:29.9 g_ra= 1:14:10.55 g_dec= 0:06:09.8 ra= 1:16:19.75 dec= -2:28:04.6
I thought the observers position only came into the calculation of sat.ra and sat.dec
so was suprised to see a_ra and a_dec had changed.
What am I missing?
Thanks
Ad
Per the last paragraph of the “body.compute(observer)” section of the Quick Reference:
http://rhodesmill.org/pyephem/quick.html#body-compute-observer
For earth satellite objects, the astrometric coordinates [meaning a_ra and a_dec] are topocentric instead of geocentric, since there is little point in figuring out where the satellite would appear on a J2000 (or whatever epoch you are using) star chart for an observer sitting at the center of the earth.
And in the issue that has been opened about this behavior, the project is open to suggestions about where this text can appear more prominently to prevent future confusion for users:
https://github.com/brandon-rhodes/pyephem/issues/55

Creating An "Autopilot" For Lander in Perl

I'm using Perl to create a simple Lunar Lander game. All of the elements work (i.e. graphical interface, user implemented controls, etc), but I cannot seem to get the "AutoPilot" function to work. This function should fly the lander to a spot that it can land (or a spot designated as a target for landing), and then safely land there. The restrictions placed on landing are the slope of the place the lander lands and the velocity that the lander has when landing. The only file I can change is AutoPilot.pm. I will post the code I am allowed to work with:
package AutoPilot;
use strict;
use warnings;
# use diagnostics;
=head1 Lunar Lander Autopilot
The autopilot is called on every step of the lunar lander simulation.
It is passed state information as an argument and returns a set of course
correction commands.
The lander world takes the surface of the moon (a circle!)
and maps it onto a rectangular region.
On the x-axis, the lander will wrap around when it hits either the
left or right edge of the region. If the lander goes above the maximum
height of the world, it escapes into the space and thus fails.
Similarly, if the lander's position goes below 0 without ever landing
on some solid surface, it "sinks" and thus fails again.
The simulation is simple in the respect that if the langer goes at a high speed
it may pass through the terrain boundary.
The y-axis has normal gravitational physics.
The goal of the autopilot is to land the craft at (or near) the landing
zone without crashing it (or failing by leaving the world).
=head2 Interface in a nutshell
When the simulation is initialized, AutoPilot::Initialize() is called.
Every clock tick, AutoPilot::ComputeLanding() is called by the simulator.
For more explanation, see below.
=cut
# if you want to keep data between invocations of ComputeLanding, put
# the data in this part of the code. Use Initialize() to handle simulation
# resets.
my $call_count = 0;
my $gravity;
my ($x_min, $y_min, $x_max, $y_max);
my ($lander_width, $lander_height, $center_x, $center_y);
my $target_x;
my ($thrust, $left_right_thrust);
my ($max_rotation, $max_left_right_thrusters, $max_main_thruster);
my $ascend_height = 980;
=head1 AutoPilot::Initialize()
This method is called when a new simulation is started.
The following parameters are passed to initialize:
$gravity, a number, describing the gravity in the world
$space_boundaries, a reference to an array with 4 numerical
elements, ($x_min, $y_min, $x_max, $y_max), describing
the world boundaries
$target_x, a number representing the target landing position
$lander_capabilities, a reference to an array with
5 elements,
($thrust, $left_right_thrust, $max_rotation, $max_left_right_thrusters, $max_main_thruster),
describing the capabilities of the lander.
$lander_dimensions, a reference to an array with
4 elements,
($lander_width, $lander_height, $center_x, $center_y),
describing the dimensions of the lander.
=head2 Details
=head3 Dimensions
The dimensions are given in 'units' (you can think of 'units' as meters).
The actual numbers can take any real value, not only integers.
=head4 World dimensions
The lander world is a square region with a lower left corner at
($x_min,$y_min) and an upper right corner at ($x_max, $y_max).
The measurement units of these dimensions will just be called units
(think about units as meters). By definition, $x_max>$x_min and
$y_max>$y_min.
The default values for the lower left and upper right corners
are (-800,0), and (800,1600), respectively.
=head4 Lander dimensions
The lander is $lander_width units wide and $lander_height high.
The coordinates of the lander are always specified with respect to its center.
The center of the lander relative to the lower left corner of the lander bounding box
is given by $center_x, $center_y. Thus, if ($x,$y) are the coordinates of the lander,
($x-$center_x,$y-$center_y) and ($x-$center_x+$lander_width,$y-$center_y+$lander_height)
specify the corners of the bounding box of the lander. (Think of the lander as completely
filling this box.) The significance of the bounding box of the lander is that a collision
occurs if the bounding box intersects with the terrain or the upper/lower edges of the world.
If a collision occurs, as described earlier, the lander might have just landed,
crashed or 'escaped' (and thus the lander failed).
The constraints on these values are: $lander_width>0, $lander_height>0,
$center_x>0, $center_y>0.
The default value for the width is 60 units, for the height it is 50,
for $center_x it is 30, for $center_y it is 25.
=head4 Forces
The gravitational force is:
$g
The thrust exerted by the engine when fired is:
$thrust
The thrust exerted by the left/right thrusters when fired is:
$left_right_thrust
=head4 Limits to the controls
Within a single timestep there are limits to how many degrees the
lander may rotate in a timestep, and how many times the side thrusters,
and main thruster, can fire. These are stored in:
$max_rotation, $max_left_right_thrusters, $max_main_thruster
=head4 Target
The target landing zone that the lander is supposed to land at:
$target_x
which returns
the string "any" if any safe landing site will do, or
a number giving the x-coordinate of the desired landing site.
Note: there is no guarantee that this is actually a safe spot to land!
For more details about how the lander is controlled, see AutoPilot::ComputeLanding.
=cut
sub Initialize {
my ($space_boundaries, $lander_capabilities,$lander_dimensions);
($gravity, $space_boundaries, $target_x, $lander_capabilities, $lander_dimensions) = #_;
($x_min, $y_min, $x_max, $y_max) = #{$space_boundaries};
( $thrust, $left_right_thrust, $max_rotation,
$max_left_right_thrusters, $max_main_thruster) = #{$lander_capabilities};
($lander_width, $lander_height, $center_x, $center_y) = #{$lander_dimensions};
$call_count = 0;
}
=head1 AutoPilot::ComputeLanding()
This method is called for every clock tick of the simulation.
It is passed the necessary information about the current state
and it must return an array with elements, describing the
actions that the lander should execute in the current tick.
The parameters passed to the method describe the actual state
of the lander, the current terrain below the lander and some
extra information. In particular, the parameters are:
$fuel, a nonnegative integer describing the remaining amount of fuel.
When the fuel runs out, the lander becomes uncontrolled.
$terrain_info, an array describing the terrain below the lander (see below).
$lander_state, an array which contains information about the lander's state.
For more information, see below.
$debug, an integer encoding whether the autopilot should output any debug information.
Effectively, the value supplied on the command line after "-D",
or if this value is not supplied, the value of the variable $autopilot_debug
in the main program.
$time, the time elapsed from the beginning of the simulation.
If the simulation is reset, time is also reset to 0.
=head2 Details of the parameters
=head3 The terrain information
The array referred to by $terrain_info is either empty, or
it describes the terrain element which is just (vertically) below the lander.
It is empty, when there is no terrain element below the lander.
When it is non-empty, it has the following elements:
($x0, $y0, $x1, $y1, $slope, $crashSpeed, $crashSlope)
where
($x0, $y0) is the left coordinate of the terrain segment,
($x1, $y1) is the right coordinate of the terrain segment,
$slope is the left to right slope of the segment (rise/run),
$crashSpeed is the maximum landing speed to avoid a crash,
$crashSlope is the maximum ground slope to avoid a crash.
=head3 The state of the lander
The array referred to by $lander_state contains
the current position, attitude, and velocity of the lander:
($px, $py, $attitude, $vx, $vy, $speed)
where
$px is its x position in the world, in the range [-800, 800],
$py is its y position in the world, in the range [0, 1600],
$attitude is its current attitude angle in unit degrees,
from y axis, where
0 is vertical,
> 0 is to the left (counter clockwise),
< 0 is to the right (clockwise),
$vx is the x velocity in m/s (< 0 is to left, > 0 is to right),
$vy is the y velocity in m/s (< 0 is down, > 0 is up),
$speed is the speed in m/s, where $speed == sqrt($vx*$vx + $vy*$vy)
=head2 The array to be returned
To control the lander you must return an array with 3 values:
($rotation, $left_right_thruster, $main_thruster)
$rotation instructs the lander to rotate the given number of degrees.
A value of 5 will cause the lander to rotate 5 degrees counter clockwise,
-5 will rotate 5 degrees clockwise.
$left_right_thruster instructs the lander to fire either the left or
right thruster. Negative value fire the right thruster, pushing the
lander to the left, positive fire the left thruster, pushing to the right.
The absolute value of the value given is the number of pushes,
so a value of -5 will fire the right thruster 5 times.
$main_thruster instructs the lander to fire the main engine,
a value of 5 will fire the main engine 5 times.
Each firing of either the main engine or a side engine consumes
one unit of fuel.
When the fuel runs out, the lander becomes uncontrolled.
Note that your instructions will only be executed up until the
limits denoted in $max_rotation, $max_side_thrusters, and $max_main_thruster.
If you return a value larger than one of these maximums than the
lander will only execute the value of the maximum.
=cut
sub ComputeLanding {
my ($fuel, $terrain_info, $lander_state, $debug, $time) = #_;
my $rotation = 0;
my $left_right_thruster = 0;
my $main_thruster = 0;
# fetch and update historical information
$call_count++;
if ( ! $terrain_info ) {
# hmm, we are not above any terrain! So do nothing.
return;
}
my ($x0, $y0, $x1, $y1, $slope, $crashSpeed, $crashSlope) =
#{$terrain_info};
my ($px, $py, $attitude, $vx, $vy, $speed) =
#{$lander_state};
if ( $debug ) {
printf "%5d ", $call_count;
printf "%5s ", $target_x;
printf "%4d, (%6.1f, %6.1f), %4d, ",
$fuel, $px, $py, $attitude;
printf "(%5.2f, %5.2f), %5.2f, ",
$vx, $vy, $speed;
printf "(%d %d %d %d, %5.2f), %5.2f, %5.2f\n",
$x0, $y0, $x1, $y1, $slope, $crashSpeed, $crashSlope;
}
# reduce horizontal velocity
if ( $vx < -1 && $attitude > -90 ) {
# going to the left, rotate clockwise, but not past -90!
$rotation = -1;
}
elsif ( 1 < $vx && $attitude < 90 ) {
# going to the right, rotate counterclockwise, but not past 90
$rotation = +1;
}
else {
# we're stable horizontally so make sure we are vertical
$rotation = -$attitude;
}
# reduce vertical velocity
if ($target_x eq "any"){
if (abs($slope) < $crashSlope){
if ($vy < -$crashSpeed + 6){
$main_thruster = 1;
if (int($vx) < 1 && int ($vx) > -1){
$left_right_thruster = 0;
}
if (int($vx) < -1){
$left_right_thruster = 1;
}
if (int($vx) > 1){
$left_right_thruster = -1;
}
}
}
else{
if ( $py < $ascend_height) {
if ($vy < 5){
$main_thruster=2;
}
}
if ($py > $ascend_height){
$left_right_thruster = 1;
if ($vx > 18){
$left_right_thruster = 0;
}
}
}
}
if ($target_x ne "any"){
if ($target_x < $px + 5 && $target_x > $px - 5){
print "I made it here";
if (abs($slope) < $crashSlope){
if ($vy < -$crashSpeed + 1){
$main_thruster = 1;
if (int($vx) < 1 && int ($vx) > -1){
$left_right_thruster = 0;
}
if (int($vx) < -1){
$left_right_thruster = 1;
}
if (int($vx) > 1){
$left_right_thruster = -1;
}
}
}
}
if ($target_x != $px){
if ( $py < $ascend_height) {
if ($vy < 5){
$main_thruster=2;
}
}
if ($py > $ascend_height){
$left_right_thruster = 1;
if ($vx > 10){
$left_right_thruster = 0;
}
}
}
}
return ($rotation, $left_right_thruster, $main_thruster);
}
1; # package ends
Sorry about the length of the code...
So, there are a few things I want this autopilot program to do. In order they are:
Stabilize the lander (reduce attitude and horizontal drift to zero if they are nonzero). Once stabilized:
If above a target and the target's segment is safe to land on then descend on it.
Otherwise ascend to the safe height, which is above 1200 units. You can safely assume that there are no objects at this height or higher and also that during straight ascends from its initial position, the lander will not hit anything.
Once at the safe height, the lander can start going horizontally towards to its target, if a target is given, otherwise it should target the first safe landing spot that is can sense by scanning the terrain in one direction. It is important that the lander maintains its altitude while it moves horizontally, because it cannot sense objects next to it and there could be objects anywhere below this height.
Once the target x coordinate is reached and is found to be safe to land on, start a descend.
If the target x coordinate is is reached, but the terrain is unsafe, if a good spot has been seen while moving towards the target, go back to it, otherwise continue searching for a good spot.
Once a good spot is seen, just land on it nice and safe.
Ok, so, I've updated the code. My code is now able to land the lander in all tests (except one, got fed up, the code works close enough) where there is no target. However, I am having huge troubles figuring out how to get the lander to land at a target. Any ideas with my code so far? (actual used code is found in the ComputeLanding subroutine)
Here's a hint: try approaching the problem from the other end.
Landing is almost equivalent to takeoff with time reversed. The only thing that doesn't get reversed is fuel consumption. (Whether that matters depends on whether the simulation counts fuel as part of the lander's mass. In a realistic sim, it should, but at a glance, it looks like yours might not.)
The optimal way (in terms of fuel efficiency) to take off in a rocket is to fire the engines at maximum power until you're going fast enough, then turn them off. The slower you climb, the more fuel you waste hovering.
Thus, the optimal way to land a rocket is to freefall (after a possible initial burn to correct heading) until the last possible instant, and then fire the engines at full power so that you come to a stop just above the landing pad (or hit the pad at whatever velocity you consider acceptable, if that's greater than zero).
Can you calculate what the right moment to turn on the engines would be? (Even if you can't do it directly, you could always approximate it by binary search. Just pick a point and simulate what happens: if you crash, start the burn earlier; if you stop before hitting the surface, start it later.)
(Ps. This seems like a rather silly exercise for a Perl programming course. Yes, you can certainly solve this in Perl, but there's nothing about Perl that would be particularly well suited for this exercise. Indeed, this isn't even fundamentally a programming problem, but a mathematical one — the only programming aspect to it is translating the mathematical solution, once found, into a working program.)
You could use a genetic algorithm for the lander implementation check out this book AI Techniques for game programming. It has exactly what you need with code examples. However, those examples are in c++.