<commit_before># -*- coding: utf-8 -*-
"""Provides programs to process and analyze GOES data."""
from __future__ import absolute_import

import datetime

import matplotlib
from matplotlib import pyplot as plt  
from pandas.io.parsers import read_csv

import sunpy
from sunpy.lightcurve import LightCurve
from sunpy.time import parse_time, TimeRange

__all__ = ['GOESLightCurve']

class GOESLightCurve(LightCurve):
    """GOES light curve definition

    Examples
    --------
    from sunpy import lightcurve as lc
    goes = lc.GOESLightCurve.create()
    goes = lc.GOESLightCurve.create('2012/06/01', '2012/06/05')
    goes.peek()

    References
    ----------
    | http://www.ngdc.noaa.gov/goes/sem
    | http://www.ngdc.noaa.gov/goes/sem/getData/goes15
    """

    def peek(self, title="GOES Xray Flux", **kwargs):
        """Plots GOES light curve is the usual manner"""
        figure = plt.figure()
        axes = plt.gca()

        dates = matplotlib.dates.date2num(self.data.index)

        axes.plot_date(dates, self.data['A_FLUX'], '-', 
                     label='0.5--4.0 $\AA$', color='blue', lw=2)
        axes.plot_date(dates, self.data['B_FLUX'], '-', 
                     label='1.0--8.0 $\AA$', color='red', lw=2)

        axes.set_yscale("log")
        axes.set_ylim(1e-9, 1e-2)
        axes.set_title(title)
        axes.set_ylabel('Watts m$^{-2}$')
        axes.set_xlabel(datetime.datetime.isoformat(self.data.index[0])[0:10])

        ax2 = axes.twinx()
        ax2.set_yscale("log")
        ax2.set_ylim(1e-9, 1e-2)
        ax2.set_yticks((1e-9, 1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2))
        ax2.set_yticklabels((' ','A','B','C','M','X',' '))

        axes.yaxis.grid(True, 'major')
        axes.xaxis.grid(False, 'major')
        axes.legend()

        # @todo: display better tick labels for date range (e.g. 06/01 - 06/05)
        formatter = matplotlib.dates.DateFormatter('%H:%M')
        axes.xaxis.set_major_formatter(formatter)

        axes.fmt_xdata = matplotlib.dates.DateFormatter('%H:%M')
        figure.autofmt_xdate()
        figure.show()

        return figure

    @classmethod
    def _get_default_uri(cls):
        """Retrieve XRS 2s data from yesterday (most recent data available using
        SEM API) if no other data is specified"""
        today = datetime.datetime.today()
        yesterday = today - datetime.timedelta(days=1)
        return cls._get_url_for_date_range(yesterday, today)

    @classmethod
    def _get_goes_sat_num_and_data_type(self,start,end):
        """Parses the query time to determine which GOES satellite to use and the correct data type"""
       
        goes_dict={'goes5_operational':TimeRange('1986-01-01','1987-03-31'),
        'goes5_dformat':'xrs_1m',
        'goes6_operational':TimeRange('1986-01-01','1994-12-31'),
        'goes6_dformat':'xrs_1m',
        'goes7_operational':TimeRange('1987-03-01','1996-08-31'),
        'goes7_dformat':'xrs_1m',
        'goes8_operational':TimeRange('1995-01-01','2003-06-16'),
        'goes8_dformat':'xrs_1m',
        'goes9_operational':TimeRange('1996-04-01','1998-07-31'),
        'goes9_dformat':'xrs_1m',
        'goes10_operational':TimeRange('1998-07-01','2009-12-31'),
        'goes10_dformat':'xrs_1m',
        'goes11_operational':TimeRange('2000-07-01','2011-02-28'),
        'goes11_dformat':'xrs_1m',
        'goes12_operational':TimeRange('2003-01-01','2010-08-31'),
        'goes12_dformat':'xrs_1m',
        'goes13_operational':TimeRange('2006-08-01','2013-11-19'),
        'goes13_dformat':'xrs_2s',
        'goes14_operational':TimeRange('2009-09-01','2012-11-24'),
        'goes14_dformat':'xrs_2s',
        'goes15_operational':TimeRange('2010-03-26',datetime.datetime.utcnow()),
        'goes15_dformat':'xrs_2s'}

        #find out which satellites were available. Start with newest first.
        for sat_num in range(15,5,-1):
            
            if ((start > goes_dict['goes'+str(sat_num)+'_operational'].start() and start < goes_dict['goes'+str(sat_num)+'_operational'].end()) and
                (end > goes_dict['goes'+str(sat_num)+'_operational'].start() and end < goes_dict['goes'+str(sat_num)+'_operational'].end())):
                #if true then the satellite with sat_num is available
                return sat_num,goes_dict['goes'+str(sat_num)+'_dformat']

        #if no satellites were found then raise an exception
        raise Exception, 'No operational GOES satellites found within specified time range'
        

    @staticmethod
    def _get_url_for_date_range(*args, **kwargs):
        """Returns a URL to the GOES data for the specified date.

        Parameters<commit_msg>Simplified code by separating GOES operational dates and data formats into two dictionaries. Added date and data format source to docstring.<commit_after># -*- coding: utf-8 -*-
"""Provides programs to process and analyze GOES data."""
from __future__ import absolute_import

import datetime

import matplotlib
from matplotlib import pyplot as plt  
from pandas.io.parsers import read_csv

import sunpy
from sunpy.lightcurve import LightCurve
from sunpy.time import parse_time, TimeRange

__all__ = ['GOESLightCurve']

class GOESLightCurve(LightCurve):
    """GOES light curve definition

    Examples
    --------
    from sunpy import lightcurve as lc
    goes = lc.GOESLightCurve.create()
    goes = lc.GOESLightCurve.create('2012/06/01', '2012/06/05')
    goes.peek()

    References
    ----------
    | http://www.ngdc.noaa.gov/goes/sem
    | http://www.ngdc.noaa.gov/goes/sem/getData/goes15
    """

    def peek(self, title="GOES Xray Flux", **kwargs):
        """Plots GOES light curve is the usual manner"""
        figure = plt.figure()
        axes = plt.gca()

        dates = matplotlib.dates.date2num(self.data.index)

        axes.plot_date(dates, self.data['A_FLUX'], '-', 
                     label='0.5--4.0 $\AA$', color='blue', lw=2)
        axes.plot_date(dates, self.data['B_FLUX'], '-', 
                     label='1.0--8.0 $\AA$', color='red', lw=2)

        axes.set_yscale("log")
        axes.set_ylim(1e-9, 1e-2)
        axes.set_title(title)
        axes.set_ylabel('Watts m$^{-2}$')
        axes.set_xlabel(datetime.datetime.isoformat(self.data.index[0])[0:10])

        ax2 = axes.twinx()
        ax2.set_yscale("log")
        ax2.set_ylim(1e-9, 1e-2)
        ax2.set_yticks((1e-9, 1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2))
        ax2.set_yticklabels((' ','A','B','C','M','X',' '))

        axes.yaxis.grid(True, 'major')
        axes.xaxis.grid(False, 'major')
        axes.legend()

        # @todo: display better tick labels for date range (e.g. 06/01 - 06/05)
        formatter = matplotlib.dates.DateFormatter('%H:%M')
        axes.xaxis.set_major_formatter(formatter)

        axes.fmt_xdata = matplotlib.dates.DateFormatter('%H:%M')
        figure.autofmt_xdate()
        figure.show()

        return figure

    @classmethod
    def _get_default_uri(cls):
        """Retrieve XRS 2s data from yesterday (most recent data available using
        SEM API) if no other data is specified"""
        today = datetime.datetime.today()
        yesterday = today - datetime.timedelta(days=1)
        return cls._get_url_for_date_range(yesterday, today)

    @classmethod
    def _get_goes_sat_num_and_data_type(self,start,end):
        """Parses the query time to determine which GOES satellite to use and the correct data type
        The operational times and dataformats are sourced from the GOES SEM API site:
        http://www.ngdc.noaa.gov/goes/sem/getData"""
       
        goes_operational={
        5:TimeRange('1986-01-01','1987-03-31'),
        6:TimeRange('1986-01-01','1994-12-31'),
        7:TimeRange('1987-03-01','1996-08-31'),
        8:TimeRange('1995-01-01','2003-06-16'),
        9:TimeRange('1996-04-01','1998-07-31'),
        10:TimeRange('1998-07-01','2009-12-31'),
        11:TimeRange('2000-07-01','2011-02-28'),
        12:TimeRange('2003-01-01','2010-08-31'),
        13:TimeRange('2006-08-01','2013-11-19'),
        14:TimeRange('2009-09-01','2012-11-24'),
        15:TimeRange('2010-03-26',datetime.datetime.utcnow())}

        goes_dformat={5:'xrs_1m', 6:'xrs_1m', 7:'xrs_1m', 8:'xrs_1m', 9:'xrs_1m', 10:'xrs_1m',
                      11:'xrs_1m', 12:'xrs_1m',13:'xrs_2s',14:'xrs_2s',15:'xrs_2s'}

        #find out which satellites were available. Start with newest first.
        for sat_num in range(15,5,-1):
            
            if ((start > goes_operational[sat_num].start() and start < goes_operational[sat_num].end()) and
                (end > goes_operational[sat_num].start() and end < goes_operational[sat_num].end())):
                #if true then the satellite with sat_num is available
                return sat_num,goes_dformat[sat_num]
        
        

        #if no satellites were found then raise an exception
        raise Exception, 'No operational GOES satellites found within specified time range'
        

    @staticmethod
    def _get_url_for_date_range(*args, **kwargs):
        """Returns a URL to the GOES data for the specified date.

        Parameters
{'fraction_non_alphanumeric': 0.14963303757257093, 'fraction_numerical': 0.06375287545185672, 'mean_word_length': 2.7418032786885247, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 5, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4206714', 'n_tokens_mistral': 3498, 'n_tokens_neox': 3114, 'n_words': 605}