astronauts_analysis.py 6.66 KB
Newer Older
Maximilian Dolling's avatar
Maximilian Dolling committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
"""
This script analysis a data set about astronauts and creates different
plots as result.
"""

from datetime import date
from os import makedirs
from pathlib import Path

import matplotlib.pyplot as plt
import pandas as pd

plt.style.use("ggplot")
_ASTRONAUT_DATA = "data/astronauts.json"
_OUTPUT_PATH = "results"


##
# Data preparation functions
##
def prepare_data_set(data_frame: pd.DataFrame) -> pd.DataFrame:
    """
    Prepares the raw data by:
        - dropping NaN's
        - setting data types
        - calculating some extra columns

    Args:
       data_frame: A pandas DataFrame.

    Returns:
        A pandas DataFrame with preprocessed data.
    """
    data_frame = rename_columns(data_frame)
    data_frame = data_frame.set_index("astronaut_id")

    # Set pandas dtypes for columns with date or time
    data_frame = data_frame.dropna(subset=["time_in_space"])
    data_frame["time_in_space"] = data_frame["time_in_space"].astype(int)
    data_frame["time_in_space"] = pd.to_timedelta(data_frame["time_in_space"], unit="m")
    data_frame["birthdate"] = pd.to_datetime(data_frame["birthdate"])
    data_frame["date_of_death"] = pd.to_datetime(data_frame["date_of_death"])
    data_frame.sort_values("birthdate", inplace=True)

    # Calculate extra columns from the original data
    data_frame["time_in_space_D"] = data_frame["time_in_space"].astype("timedelta64[D]")
    data_frame["alive"] = data_frame["date_of_death"].apply(is_alive)
    data_frame["age"] = data_frame["birthdate"].apply(calculate_age)
    data_frame["died_with_age"] = data_frame.apply(died_with_age, axis=1)
    return data_frame


def rename_columns(data_frame):
    """
    The original column naming in the data set is not useful
    for programming with pandas. So we rename it.
    """

    name_mapping = {
        "astronaut": "astronaut_id",
        "astronautLabel": "name",
        "birthplaceLabel": "birthplace",
        "sex_or_genderLabel": "sex_or_gender",
    }
    data_frame = data_frame.rename(index=str, columns=name_mapping)
    return data_frame


def is_alive(date_of_death) -> bool:
    """
    Checks, if 'date_of_death' exists or not.

    Args:
       date_of_death: Either a pandas NaTType or a pandas Timestamp.

    Returns:
        bool
    """
    if pd.isnull(date_of_death):
        return True
    return False


def calculate_age(born: pd.Timestamp) -> int:
    """
    Calculates an age from a date.

    Args:
       born: pandas.Timestamp

    Returns:
        int
    """

    if not isinstance(born, pd.Timestamp):
        raise TypeError(f'expected {pd.Timestamp}, got {type(born)}')

    today = date.today()
    return today.year - born.year - ((today.month, today.day) < (born.month, born.day))


def died_with_age(row: pd.Series):
    """
    Calculates an age from a birthdate and date_of_death.

    Args:
       row: pandas.Series with the columns `birthdate` and `date_of_death`

    Returns:
        int
    """
    if pd.isnull(row["date_of_death"]):
        return None
    born = row["birthdate"]
    today = row["date_of_death"]
    return today.year - born.year - ((today.month, today.day) < (born.month, born.day))


##
# Plot functions
##
def create_time_of_x_in_space(data_frame, filename, title):
    """
    This function generated a plot with the summed up time of 'living beings'
    in space over the years by their birthday's.
    """

    reduced_data_frame = data_frame[["birthdate", "time_in_space", "time_in_space_D"]].copy()
    reduced_data_frame["accumulated_time_in_minutes"] = reduced_data_frame["time_in_space"].cumsum()
    reduced_data_frame["accumulated_time_in_days"] = reduced_data_frame["time_in_space_D"].cumsum()
    axs = reduced_data_frame.plot(x="birthdate", y="accumulated_time_in_days")
    axs.set_title(title)
    axs.set_xlabel("Years ")
    axs.set_ylabel("t in days")
    save(axs.get_figure(), filename)


def create_age_histogram(age_data_frame, died_data_frame):
    """
    The function generates a combined histogram of astronauts
    in the categories 'age at dead' and 'age alive'.
    """

    fig, axs = plt.subplots(1, 1)
    axs.hist(
        [died_data_frame["died_with_age"], age_data_frame["age"]],
        bins=70,
        range=(31, 100),
        stacked=True,
    )
    axs.set_xlabel("Age")
    axs.set_ylabel("Number of astronauts")
    axs.set_title("Dead vs. Alive astronauts")
    save(fig, "combined_histogram.png")


def create_age_boxplot(age_data_frame, died_data_frame):
    """
    The function generates a boxplot of astronauts age distribution
    in the categories dead and alive.
    """

    fig, axs = plt.subplots(1, 1)
    axs.boxplot([died_data_frame["died_with_age"], age_data_frame["age"]])
    axs.set_title("Age distribution; Dead vs. Alive astronauts")
    axs.set_xlabel("Category")
    plt.setp(axs, xticks=[1, 2], xticklabels=["Dead", "Alive"])
    axs.set_ylabel("Age")
    save(fig, "boxplot.png")


def save(fig: plt.Figure, filename: str):
    """
    Saves a matplotlib Figure to a file. It overwrites existing files with the same filename.

    Args:
        fig: matplotlib.pyplot.Figure
        filename: str
    """
    fig.savefig(Path(_OUTPUT_PATH).resolve() / Path(filename))


def perform_analysis():
    """ Glues data preparation and plotting. """

    # Set up directory structure and preprocess data
    makedirs(_OUTPUT_PATH, exist_ok=True)
    data_frame = pd.read_json(Path(_ASTRONAUT_DATA).resolve())
    data_frame = prepare_data_set(data_frame)

    # Male humans in space
    data_frame_male = data_frame.loc[
        data_frame["sex_or_gender"] == "male", ["birthdate", "time_in_space", "time_in_space_D"]
    ].copy()
    create_time_of_x_in_space(
        data_frame_male,
        "male_humans_in_space.png",
        "Total time male humans have spend in space",
    )

    # Female humans in space
    data_frame_female = data_frame.loc[
        data_frame["sex_or_gender"] == "female",
        ["birthdate", "time_in_space", "time_in_space_D"],
    ].copy()
    create_time_of_x_in_space(
        data_frame_female,
        "female_humans_in_space.png",
        "Total time female humans have spend in space",
    )

    # Humans in space
    create_time_of_x_in_space(
        data_frame, "humans_in_space.png", "Total time humans have spend in space"
    )

    # Dead and alive astronauts analysis
    died_data_frame = data_frame.loc[data_frame["alive"] == 0, ["died_with_age"]].copy()
    age_data_frame = data_frame.loc[data_frame["alive"] == 1, ["age"]].copy()

    # Combined histogram of dead and alive astronauts
    create_age_histogram(age_data_frame, died_data_frame)

    # Box plots of dead vs alive astronauts
    create_age_boxplot(age_data_frame, died_data_frame)


# Main entry point
if __name__ == "__main__":
    perform_analysis()