Astronomical Calculations: The Julian Day

Later I want to post an implementation of how to calculate geocentric solar coordinates for a given date and time based on algorithms published in Astronomical Algorithms by Jean Meeus. But that is very involved and going to be a long post. So I thought it would be wise first to talk about dates and times used by astronomers. This will “prepare the ground” so to speak.

In the West we use the Gregorian calendar which began on 4 Oct 1582 and replaced the Julian calendar. To fix the drift from the Julian calendar that had accumulated over the centuries,  4 Oct was followed by 15 Oct. As you can imagine this led to a lot of confusion since some people still used the old calendar and others referred to the new one. (Think of the Imperial and the metric system in our own time.) Also, not all cultures adopted the new calendar right away. An astronomer in Munich might still be using the Julian calendar while another in Venice used dates that referred to the new Gregorian calendar. So in 1583 a scholar named Joseph Scaliger proposed an abstraction which he called the Julian Period.  The period is 7,980 years and runs from 1 Jan 4713 BCE (which is Year 1) to 31 Dec 3268 CE.  We have a similar system today with POSIX (or Unix) time in which the epoch begins on 1 Jan 1970 UTC and counts the number of elapsed seconds since that moment.

From the Julian Period astronomers refer to the Julian Day (JD) when making calculations in celestial mechanics. A JD value is the number of days since the beginning of the Julian Period. Meeus writes:

The Julian Day number or, more simply, the Julian Day … is a continuous count of days and fractions thereof from the beginning of the year -4712.

Why -4712? Because dates always start at 0 so if 4713 BCE is year one then -4712 is the very beginning of the period for calculation purposes. Civil dates begin at midnight UTC. This is inconvenient for astronomers since celestial events might overlap from one day to the next. For example if you observe a comet at 23:00 hours and report on its movement until 02:00 hours you’d have to use two different dates. So the Julian Day begins at apparent solar noon UTC so that there’s a 12 hour difference from the beginning of the civil date.

So with all of that esoterica out of the way how do we calculate the JD? Here I’ll modify Meeus to show the pseudocode:

Let Y == Year
Let M == Month Number // 1 is Jan, 2 is Feb, etc.
Let D == Day Number // where D is double (64-bit floating-point value)

If M == 1 OR M == 2 Then:
    
    Y == Y - 1
    M == M + 12

// That is if the date is Jan or Feb then the date is the 13th or
// 14th month of the preceding year for calculation purposes.

If the date is on the Gregorian calendar (after 14 Oct 1582) then:

Let A = (int)(Y / 100)
Let B = 2 - A + (int)(A / 4)

If the date is on the Julian calendar (prior to 4 Oct 1582) then:

Let B = 0

So far we’ve set up the variables for the main calculation. D is a double because it could represent a fraction of a day. For example, 4.812 is the 4th day of the month at 19:29 (7:29 PM). Here’s the algorithm for the Julian Day itself:

JD = (int)(365.25 * (Y + 4716)) + (int)(30.6001 * (M + 1)) + D + B - 1524.5

I can implement this in C# as a struct:

/// <summary>
/// A moment is a specific point in time down to the millisecond.
/// </summary>
public struct Moment
{
    public int Year { get; }
    public int Month { get; }
    public int Day { get; }
    public int Hour { get; }
    public int Minute { get; }
    public int Second { get; }
    public int Millisecond { get; }

    /// <summary>
    /// Creates a Moment with known values down to the millisecond.
    /// </summary>
    public Moment(int y, int m, int d, int h, int m, int s = 0, int ms = 0)
    {
        Year = y;
        Month = m;
        Day = d;
        Hour = h;
        Minute = m;
        Second = s;
        Millisecond = ms;
    }

    /// <summary>
    /// A Julian Day (JD) is a continuous count of days and fractions thereof
    /// starting at 1 Jan -4712 at noon UTC to a given point in time thereafter.
    /// </summary>
    public double JulianDay
    {
        get
        {
            int Y = Year;
            int M = Month;
            int B = 0; // Julian calendar default

            // if the date is Jan or Feb then it is considered to be in the 
            // 13th or 14th month of the preceding year.
            switch (M)
            {
                case 1:
                case 2:
                    Y = Y - 1;
                    M = M + 12;
                    break;

                default:
                    break;
            }

            if (!IsJulianDate()) // convert to Gregorian calendar
            {
                var A = Y / 100;
                B = 2 - A + (A / 4);
            }

            return 
                (int)(365.25 * (Y + 4716)) + 
                (int)(30.6001 * (M + 1)) + DayOfMonth + B - 1524.5;
        }
    }


    /// <summary>
    /// Pope Gregory introduced the Gregorian calendar in October 1582 when the 
    /// calendar had drifted 10 days. Dates prior to 4 Oct 1582 are Julian dates
    /// and dates after 15 Oct 1582 are Gregorian dates. Any date in the gap is
    /// invalid on the Gregorian calendar.
    /// </summary>
    /// <returns></returns>
    public bool IsJulianDate()
    {
        if (Year > 1582)
            return false;

        if (Year < 1582)
            return true;

        // year is 1582 so check month
        if (Month > 10)
            return false;

        if (Month < 10)
            return true;

        // month is 10 so check days
        if (Day > 14)
            return false;

        return true;
    }

    public double DayOfMonth
    {
        get
        {
            return 
                Day + 
                (Hour / 24.0) + 
                (Minute / 1440.0) + 
                (Second + Millisecond / 1000.0) / 86400.0;
        }
    }
}

Now i can write a console app to test this implementation:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Calculation of the Julian Day");
        Console.WriteLine(Environment.NewLine);

        var moment = new Moment(1957, 10, 4, 19, 29, 0);  // Sputnik 1 launched (UTC)

        Console.WriteLine("Sputnik 1 launched on 4 Oct 1957 at 19:29 UTC");
        Console.WriteLine("Sputnik 1 JD: " + moment.JulianDay);
        Console.ReadLine();
    }
}

And the output is:

Calculation of the Julian Day

Sputnik 1 launched on 4 Oct 1957 at 19:29 UTC
Sputnik 1 JD: 2436116.31180556

I will be using this struct in a future blog post when I dive headlong into calculating geocentric solar coordinates. That is to say, given any date and time (like the moment Sputnik 1 launched) I can calculate the position of the sun in the sky.

NuGet Package Feeds on Azure DevOps

One of my favorite features of Azure DevOps is its package management feature where you can publish NuGet packages to your own organization’s feed. Packages in your feed can be referenced by other projects in the CI/CD pipeline or through Visual Studio. In this walkthrough I’ll give a simple example of how to use it. I’ll assume you’re comfortable with Azure DevOps. If you’re not familiar with the tool see my four-part series on the subject.

That creamy NuGet center!

Continue reading “NuGet Package Feeds on Azure DevOps”

Let’s Build A Solar Calendar!

If you live in the northern hemisphere like me then this Friday is hibernal or winter solstice. For those of you in the southern hemisphere it will be the summer solstice. Either way happy solstice to all! For those of us in midwinter the Earth’s north pole is at its maximum tilt away from the sun. This means that the apparent height of the sun is at its lowest point in the sky on the winter solstice.

Believe it or not a bunch of people — your friends and neighbors — have no idea what I’m talking about right now. But I suspect you think astronomy is cool or you wouldn’t be reading this right now. So I’m here to help you build an awesome solar calendar in your front yard both to mark the changing of the seasons and to help visualize the sun’s apparent motion across the sky. Your neighbor kids will love it trust me. And it will be fun for you to design and build. After the jump is a photo of the finished product as it looks in the parking strip in front of my house.

Continue reading “Let’s Build A Solar Calendar!”

Now Available: ASP.NET Core 2 HMAC Middleware

I won’t repeat the project home page except to say that if you need good strong security for clients (MVC or otherwise) calling services (micro or otherwise) then this is for you!

Basic authentication middleware is no longer available in Core 2 and I’ve blogged about that before and wrote a SquareWidget.BasicAuth.Core NuGet package. Even with TLS you should probably not use it unless you have no choice. The password goes over the wire in base64 encoding rather than ciphertext, it sits there in the request header for the whole session, the user can cache it permanently in the browser, and anyone on the network can sniff it out before it gets to the web server.

So why do people use basic auth so much? One word: convenience.  Developers fall back on the  tried and true rather than take the time to do the right thing. So my aim with this middleware is to encapsulate all the goodness of HMAC and keep it dead simple so that the developer has no excuse for not using a more secure algorithm.

From Soup to Nuts: Azure DevOps with Visual Studio 2017

This is the introductory post in a four part series walking through the process of creating a project in Visual Studio and building out a complete CI/CD pipeline to get that code into production on Azure using Azure DevOps.

Here’s a rough outline of where I think this series will go. As soon as I have the content ready I’ll link to them from here:

Part 1: Publish to an Azure DevOps Repository

Part 2: Setting up a Build Pipeline in Azure DevOps

Part 3: Setting up a Release Pipeline in Azure DevOps

Part 4: Adding a Database to the Project

A little context… Lately I’ve been using the Eclipse plugin Subversive for source control on my java-based projects, which uses an on-prem SVN server. For C# projects I use the Visual Studio plugin VisualSVN. Back in the old days I used an on-prem TFS server. Before that VSS which I’ll just leave that right there. So I’ve used SVN for many years and I have no complaints about it in particular or concurrent version control systems in general. But this series isn’t about those tools or centralized version control. And it’s not about Git Bash or shelling out to the command line from GitHub Desktop or anything like that.  Download the Pro Git book if you want to dive deep into that area. 

I’ve also used TFS v1.0 and before that NAnt and then CruiseControl somewhere along the line. Currently my place of work uses TeamCity for builds, NUnit for tests, Octopus for deployments and probably other things like DbUp for database scripting. And I’ve deployed straight to Azure from Visual Studio more times than I can count. But guess what? This series isn’t about any of those things either. In this series I want to help you to take your game up to the next level so that your pipeline to production is fully automated. And I want to keep it as simple as possible. So let’s get started at Part 1.

Part 4: Adding a Database to the Project

This is Part 4 in a  series on Azure DevOps.

In  Part 1 I created a simple web app called WidgetApi. I then put it under source control and pushed it up to an Azure DevOps repo. In Part 2 I configured a build pipeline and made a code change to trigger that build with continuous integration. In Part 3 I set up a release pipeline and deployed our build artifacts to Azure. In this part I’m going to add a database to WidgetApi and use a DACPAC file to bundle database changes for deployment in the release pipeline. Finally, I’ll configure a production environment with an approval process.

Continue reading “Part 4: Adding a Database to the Project”

Part 3: Setting up a Release Pipeline in Azure DevOps

This is Part 3 in a  series on Azure DevOps.

In  Part 1 I created a simple web app called WidgetApi. I then put it under source control and pushed it up to an Azure DevOps repo. In Part 2 I configured a build pipeline and made a code change to trigger that build with continuous integration. In this part we’re going to create a release pipeline that deploys our build artifacts to Azure.

Continue reading “Part 3: Setting up a Release Pipeline in Azure DevOps”

Part 2: Setting up a Build Pipeline in Azure DevOps

This is Part 2 in a series on Azure DevOps.

In Part 1 I created a simple web app called WidgetApi. I then put it under source control and pushed it up to an Azure DevOps repo. In this part we’re going to set up a build and then change our code to trigger a continuous integration build. Open the browser and go to your Azure DevOps portal. You should see all your pushed commits there from Part 1. Awesome. Now there’s a couple of housekeeping things to do before we set up the build.

Shout out to https://devrant.com/rants/1535091/ci-cd-in-a-nutshell

Continue reading “Part 2: Setting up a Build Pipeline in Azure DevOps”

Part 1: Publish to an Azure DevOps Repository

In this series I’m going to use the free Visual Studio 2017 Community Edition and the free Azure DevOps to target a full-blown CI/CD pipeline to deploy a web application to Azure.  So in addition to those tools make sure you have an Azure subscription. Last, I’ve got the latest Git for Windows installed (v2.19.1.windows.1). So let’s get started after the jump.

Continue reading “Part 1: Publish to an Azure DevOps Repository”

ASP.NET Core 2.1 Web API Using Multiple Authentication Schemes

There’s very little guidance from Microsoft on writing your own custom authentication handlers for Core 2. If you look at the documentation you’ll find detailed guidance on the built-in Core Identity model that they want you to use. They also provide links to third-party open-source providers like Identity Server which is what I use in this example. There is an article on custom cookie authentication. But generally speaking because security is hard and it’s way too easy to screw up Microsoft would rather you did not roll your own. It’s best to stick to the prescriptive guidance Microsoft offers. Now that I’ve said that I’m going to ignore completely my own advice. Read on if you’re with me.

Continue reading “ASP.NET Core 2.1 Web API Using Multiple Authentication Schemes”