#!/usr/bin/env python
# coding: utf-8

# In[4]:


import http.client
import json
from datetime import datetime
import pandas as pd
import matplotlib.pyplot as plt


# API Key
API_KEY = "***********"

# Define the start date and today's date (present)
start_date = "2019-01-01"
end_date = datetime.today().strftime('%Y-%m-%d')  # gets the current date

# Set up the connection and make the request with the date range
conn = http.client.HTTPSConnection("api.nasa.gov")
conn.request("GET", f"/DONKI/FLR?startDate={start_date}&endDate={end_date}&api_key={API_KEY}")

# Get the response and parse it
response = conn.getresponse()
data = response.read().decode("utf-8")
conn.close()

# Convert the data to JSON format
flr_data = json.loads(data)

# Normalize the JSON data to handle nested structures
df = pd.json_normalize(flr_data)

# Output the structured DataFrame with columns
print(df.tail())


# In[5]:


print(df.tail(10))


# In[22]:


def categorize_event(classType):
    categories = []
    if 'B' in classType:
        categories.append('B')
    if 'C' in classType:
        categories.append('C')
    if 'M' in classType:
        categories.append('M')
    if 'X' in classType:
        categories.append('X')
    return categories

# Create new column with the categories
df['categories'] = df['classType'].apply(categorize_event)

# Flatten the categories and count occurrences of each letter
category_count = df.explode('categories')['categories'].value_counts()

# Plot the bar chart
plt.figure(figsize=(8, 6))
category_count.plot(kind='bar', color=['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728'])


# Add labels and title
plt.xlabel('Solar Event Class')
plt.ylabel('Frequency')
plt.title('Frequency of Certain Solar Events')

# Display the plot
plt.show()


# In[15]:


# Convert 'date' column to datetime, handling errors by setting them to NaT
df['date'] = pd.to_datetime(df['peakTime'], errors='coerce')

# Drop rows with NaT (invalid dates)
df = df.dropna(subset=['date'])

# Extract year from the 'date' column
df['year'] = df['date'].dt.year

# Count occurrences by year
year_counts = df['year'].value_counts().sort_index()

# Create a bar plot
plt.figure(figsize=(8, 6))
plt.bar(year_counts.index, year_counts.values, color='orange')

# Add labels and title
plt.xlabel('Year')
plt.ylabel('Number of Solar Flares')
plt.title('Detected Solar Events by Year')

# Display the plot
plt.show()


# In[ ]:





# In[ ]:Language:Python