示例#1
0
def test_change_epoch():
    date = np.datetime64('2000-01-01')

    with pytest.raises(RuntimeError):
        # this should fail here because there is a sentinel on the epoch
        # if the epoch has been used then it cannot be set.
        mdates.set_epoch('0000-01-01')

    # use private method to clear the epoch and allow it to be set...
    mdates._reset_epoch_test_example()
    mdates.set_epoch('1970-01-01')
    dt = (date - np.datetime64('1970-01-01')).astype('datetime64[D]')
    dt = dt.astype('int')
    np.testing.assert_equal(mdates.date2num(date), float(dt))

    mdates._reset_epoch_test_example()
    mdates.set_epoch('0000-12-31')
    np.testing.assert_equal(mdates.date2num(date), 730120.0)

    mdates._reset_epoch_test_example()
    mdates.set_epoch('1970-01-01T01:00:00')
    np.testing.assert_allclose(mdates.date2num(date), dt - 1. / 24.)
    mdates._reset_epoch_test_example()
    mdates.set_epoch('1970-01-01T00:00:00')
    np.testing.assert_allclose(
        mdates.date2num(np.datetime64('1970-01-01T12:00:00')), 0.5)
示例#2
0
def test_epoch2num():
    mdates._reset_epoch_test_example()
    mdates.set_epoch('0000-12-31')
    assert mdates.epoch2num(86400) == 719164.0
    assert mdates.num2epoch(719165.0) == 86400 * 2
    # set back to the default
    mdates._reset_epoch_test_example()
    mdates.set_epoch('1970-01-01T00:00:00')
    assert mdates.epoch2num(86400) == 1.0
    assert mdates.num2epoch(2.0) == 86400 * 2
def test_epoch2num():
    with _api.suppress_matplotlib_deprecation_warning():
        mdates._reset_epoch_test_example()
        mdates.set_epoch('0000-12-31')
        assert mdates.epoch2num(86400) == 719164.0
        assert mdates.num2epoch(719165.0) == 86400 * 2
        # set back to the default
        mdates._reset_epoch_test_example()
        mdates.set_epoch('1970-01-01T00:00:00')
        assert mdates.epoch2num(86400) == 1.0
        assert mdates.num2epoch(2.0) == 86400 * 2
示例#4
0
def test_julian2num():
    mdates._reset_epoch_test_example()
    mdates.set_epoch('0000-12-31')
    # 2440587.5 is julian date for 1970-01-01T00:00:00
    # https://en.wikipedia.org/wiki/Julian_day
    assert mdates.julian2num(2440588.5) == 719164.0
    assert mdates.num2julian(719165.0) == 2440589.5
    # set back to the default
    mdates._reset_epoch_test_example()
    mdates.set_epoch('1970-01-01T00:00:00')
    assert mdates.julian2num(2440588.5) == 1.0
    assert mdates.num2julian(2.0) == 2440589.5
def test_axhline():
    # make sure that axhline doesn't set the xlimits...
    fig, ax = plt.subplots()
    ax.axhline(1.5)
    ax.plot([np.datetime64('2016-01-01'), np.datetime64('2016-01-02')], [1, 2])
    np.testing.assert_allclose(ax.get_xlim(), [
        mdates.date2num(np.datetime64('2016-01-01')),
        mdates.date2num(np.datetime64('2016-01-02'))
    ])

    mdates._reset_epoch_test_example()
    mdates.set_epoch('0000-12-31')
    fig, ax = plt.subplots()
    ax.axhline(1.5)
    ax.plot([np.datetime64('2016-01-01'), np.datetime64('2016-01-02')], [1, 2])
    np.testing.assert_allclose(ax.get_xlim(), [
        mdates.date2num(np.datetime64('2016-01-01')),
        mdates.date2num(np.datetime64('2016-01-02'))
    ])
    mdates._reset_epoch_test_example()
def test_date_empty():
    # make sure we do the right thing when told to plot dates even
    # if no date data has been presented, cf
    # http://sourceforge.net/tracker/?func=detail&aid=2850075&group_id=80706&atid=560720
    fig, ax = plt.subplots()
    ax.xaxis_date()
    fig.draw_without_rendering()
    np.testing.assert_allclose(ax.get_xlim(), [
        mdates.date2num(np.datetime64('2000-01-01')),
        mdates.date2num(np.datetime64('2010-01-01'))
    ])

    mdates._reset_epoch_test_example()
    mdates.set_epoch('0000-12-31')
    fig, ax = plt.subplots()
    ax.xaxis_date()
    fig.draw_without_rendering()
    np.testing.assert_allclose(ax.get_xlim(), [
        mdates.date2num(np.datetime64('2000-01-01')),
        mdates.date2num(np.datetime64('2010-01-01'))
    ])
    mdates._reset_epoch_test_example()
示例#7
0
 def wrapper():
     mdates._reset_epoch_test_example()
     mdates.set_epoch('2000-01-01')
     thefunc()
     mdates._reset_epoch_test_example()
示例#8
0
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import warnings
import sklearn.metrics as metrics
import config as cfg
import datetime as dt

import math
import pandas as pd
import matplotlib.colors as colors

COLORS = colors.CSS4_COLORS

mdates._reset_epoch_test_example()
mdates.set_epoch('0000-12-31T00:00:00')  # old epoch (pre MPL 3.3)

warnings.simplefilter("ignore")
NR_COLUMNS: int = 3
HEIGHT: int = 4


def choose_grid(nr):
    if nr < NR_COLUMNS:
        return 1, nr
    else:
        return (nr // NR_COLUMNS,
                NR_COLUMNS) if nr % NR_COLUMNS == 0 else (nr // NR_COLUMNS + 1,
                                                          NR_COLUMNS)

    mdates._reset_epoch_test_example()


#############################################################################
# Datetime
# --------
#
# Python `.datetime` objects have microsecond resolution, so with the
# old default matplotlib dates could not round-trip full-resolution datetime
# objects.

old_epoch = '0000-12-31T00:00:00'
new_epoch = '1970-01-01T00:00:00'

_reset_epoch_for_tutorial()  # Don't do this.  Just for this tutorial.
mdates.set_epoch(old_epoch)  # old epoch (pre MPL 3.3)

date1 = datetime.datetime(2000,
                          1,
                          1,
                          0,
                          10,
                          0,
                          12,
                          tzinfo=datetime.timezone.utc)
mdate1 = mdates.date2num(date1)
print('Before Roundtrip: ', date1, 'Matplotlib date:', mdate1)
date2 = mdates.num2date(mdate1)
print('After Roundtrip:  ', date2)

#############################################################################
import sys
sys.path.insert(1, '../') # make sure to use the code in this repo

import matplotlib.dates as mdates
import datetime
import matplotlib.pyplot as plt
import numpy as np
import astropy.io.fits as fits
import scipy

import matplotlib as mpl
# try to use the precise epoch
mpl.rcParams['date.epoch']='1970-01-01T00:00:00'
try:
    mdates.set_epoch('1970-01-01T00:00:00')
except:
    pass
import radioTools as rt
from skimage.transform import probabilistic_hough_line

# frequency [MHz]


def read_fits(fname):
    
    hdu = fits.open(fname)
    dyspec = hdu[0].data
    f_fits = hdu[1].data['FREQ'][:]
    t_fits = hdu[2].data['TIME'][:]
    return (dyspec,t_fits,f_fits,hdu)
def main():
    #Ask for update from user
    print("Update data set?\nY or N: ", end="")
    isUpdate = input()
    copy_to_dir = "./COVID-19-data/owid-covid-data.csv"

    if (isUpdate == "Y"):
        covid_data_dir = "https://covid.ourworldindata.org/data/owid-covid-data.csv"
        print("Fetching latest COVID data")
        urllib.request.urlretrieve(covid_data_dir, copy_to_dir)

    #Get data on the desired nation
    covid_data = pd.read_csv(copy_to_dir)

    print("Enter a nation to display: ", end="")
    nation = input()
    num_locations = covid_data["location"].count()
    i = 0
    start_row = 0
    end_row = 0
    first_time = True
    #Fetch the selected nation's data
    while (i < num_locations):
        x = covid_data.iloc[i]
        if (x["location"] == nation and first_time):
            start_row = i
            end_row = i
            first_time = False
        elif (x["location"] == nation):
            end_row += 1
        i += 1
    #print("start_row: %d \n end_row: %d" %(start_row, end_row))
    nation_data = covid_data.iloc[start_row:end_row, :]

    total_cases = nation_data["total_cases"]
    date = nation_data["date"]

    fig, ax = plt.subplots()
    ax.plot(date, total_cases)
    ax.set_title("Covid cases " + nation)
    ax.set_xlabel("Date")
    ax.set_ylabel("Number of COVID cases")
    """
    ax.xlabel("Date")
    ax.ylabel("Cases")
    ax.set_title("Covid cases")
    
    debugging output
    print(nation_data)
    print(nation_data.describe())
    print(date)
    """

    #date formatting
    months = mdates.MonthLocator()
    years_fmt = mdates.DateFormatter("%Y-%m")

    mdates.set_epoch(date[start_row])
    ax.xaxis.set_major_locator(months)
    ax.xaxis.set_major_formatter(years_fmt)

    # format the coords message box
    ax.format_xdata = mdates.DateFormatter('%Y-%m-%d')
    ax.grid(True, axis="both")

    # rotates and right aligns the x labels, and moves the bottom of the
    # axes up to make room for them
    fig.autofmt_xdate()
    plt.show()
示例#12
0
import matplotlib.dates as mpld

try:
    mpld.set_epoch('0000-12-31T00:00:00')
except:
    pass

from ...core.toolbox import display_message
from matplotlib.dates import date2num, num2date
import numpy as np
from ...core.toolbox import dir_interval, get_increment, get_number_of_loops
from ...core.make_table import create_table
import pandas as pd
from itertools import groupby
from calendar import monthrange
import copy


def to_workability(peakind, fac, index, nyear):
    display_message()


def do_window_stats(filename, time, mag, time_blocking, method, threshold,
                    duration):

    display_message()


def do_exc_stats(filename, time, mag, time_blocking, method, threshold,
                 duration):
示例#13
0
#!/usr/bin/env python3
# prepare schism input
import os, sys
from os.path import join
sys.path.append(join(os.path.dirname(__file__), 'core'))
import glob
import argparse
import yaml
import json
import logging
import dateutil
from matplotlib.dates import num2date, date2num, set_epoch
import matplotlib.dates as mpld
import six

set_epoch('0000-12-31T00:00:00')

from hgrid import HorizontalGrid
from vgrid import VerticalGrid
from param import ModelConfig
from bctide import BCinputs
from datasourcing import download_data
from openbnd import OpenBoundaries
from meteo import Meteo
from ic import InitialConditions
from atmospheric import get_convergence
from station import Station
from hotstart import HotStart

from waves import Wave
示例#14
0
def main():
    #Ask for update from user
    print("Update data set?\nY or N: ", end="")
    isUpdate = input()
    data_dir = "./COVID-19-data/owid-covid-data.csv"

    if (isUpdate.capitalize() == "Y"):
        covid_data_dir = "https://covid.ourworldindata.org/data/owid-covid-data.csv"
        print("Fetching latest COVID data")
        urllib.request.urlretrieve(covid_data_dir, data_dir)

    #Get data on the desired nation
    fig, ax = plt.subplots()

    covid_data = pd.read_csv(data_dir)
    mdates.set_epoch(covid_data["date"][0])
    nation = []
    #Ask for the number of nations to display
    print("Enter the number of nations to display: ", end="")
    numNations = int(input())
    i = 0
    while (i < numNations):
        print("Enter a nation to display: ", end="")
        nation.append(input())
        i += 1

    num_locations = covid_data["location"].count()
    for n in nation:
        print(n)
        start_row = 0
        end_row = 0
        first_time = True
        i = 0
        #Fetch the selected nation's data
        while (i < num_locations):
            x = covid_data.iloc[i]
            if (x["location"] == n and first_time):
                start_row = i
                end_row = i
                first_time = False
            elif (x["location"] == n):
                end_row += 1
            i += 1
        #Now works!
        nation_data = covid_data.iloc[start_row:end_row, :]
        total_cases = nation_data["total_cases"]
        date = nation_data["date"]
        colour = random.randrange(1, 0xFFFFFF)
        hex_string = "#{:02x}".format(colour)
        ax.plot(date, total_cases, color=hex_string, label=n)

    ax.set_title("Covid cases")
    ax.set_xlabel("Date")
    ax.set_ylabel("Number of COVID cases")
    ax.legend()
    """
    debugging output
    print(nation_data)
    print(nation_data.describe())
    print(date)
    """

    #date formatting
    months = mdates.MonthLocator()
    years_fmt = mdates.DateFormatter("%Y-%m")

    ax.xaxis.set_major_locator(months)
    ax.xaxis.set_major_formatter(years_fmt)

    # format the coords message box
    ax.format_xdata = mdates.DateFormatter('%Y-%m-%d')
    ax.grid(True, axis="both")
    # rotates and right aligns the x labels, and moves the bottom of the
    # axes up to make room for them
    fig.autofmt_xdate()
    plt.show()
from sklearn.linear_model import Ridge
from sklearn.linear_model import RidgeCV
from statsmodels.api import Logit
from scipy.stats import spearmanr
import xlsxwriter
from pandas.plotting import register_matplotlib_converters
from sklearn.model_selection import train_test_split
from sklearn.model_selection import LeaveOneOut
from matplotlib import dates as mdates
from sklearn.decomposition import PCA
import plotly.graph_objects as go

# To fix the date f**k-ups
old_epoch = '0000-12-31T00:00:00'
new_epoch = '1970-01-01T00:00:00'
mdates.set_epoch(old_epoch)
register_matplotlib_converters()

os.chdir('/Users/anusarfarooqui/Docs/Matlab/')
# Clock utility function
import time


def TicTocGenerator():
    ti = 0
    tf = time.time()
    while True:
        ti = tf
        tf = time.time()
        yield tf - ti