degree_analysis.py 9.06 KB
Newer Older
1
2
import pandas as pd
import math
bhm15's avatar
bhm15 committed
3
import json
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
from script.utils.situations import Situation, EvasionForm


def average_graduation(df):
    total_student = df['MATR_ALUNO'].drop_duplicates().shape[0]
    total_graduate = df[df.FORMA_EVASAO == EvasionForm.EF_FORMATURA].shape[0]

    return total_graduate / total_student


def general_failure(df):
    affect_ira = df[df.SITUACAO.isin(Situation.SITUATION_AFFECT_IRA)]
    failures = affect_ira[affect_ira.SITUACAO.isin(Situation.SITUATION_FAIL)]

    average = failures.shape[0] / affect_ira.shape[0]

    student_courses = affect_ira.groupby(['MATR_ALUNO'], as_index=False)\
                                .aggregate({'SITUACAO': 'count'})
    student_failures = failures.groupby(['MATR_ALUNO'], as_index=False)\
                               .aggregate({'SITUACAO': 'count'})

    merged = pd.merge(student_courses, student_failures, on=['MATR_ALUNO'])
    merged.columns = ['MART_ALUNO', 'FEITAS', 'REPROVADO']
    variance = merged['REPROVADO'].div(merged['FEITAS']).sub(average)\
                                      .pow(2).sum() / merged.shape[0]
    standard_deviation = math.sqrt(variance)
    return (average, standard_deviation)


bhm15's avatar
bhm15 committed
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def current_students_failure(df):
    fixed = df.loc[(df.FORMA_EVASAO == EvasionForm.EF_ATIVO)]
    affect_ira = fixed[fixed.SITUACAO.isin(Situation.SITUATION_AFFECT_IRA)]
    failures = affect_ira[affect_ira.SITUACAO.isin(Situation.SITUATION_FAIL)]

    average = failures.shape[0] / affect_ira.shape[0]

    student_courses = affect_ira.groupby(['MATR_ALUNO'], as_index=False)\
                                .aggregate({'SITUACAO': 'count'})
    student_failures = failures.groupby(['MATR_ALUNO'], as_index=False)\
                               .aggregate({'SITUACAO': 'count'})

    merged = pd.merge(student_courses, student_failures, on=['MATR_ALUNO'])
    merged.columns = ['MART_ALUNO', 'FEITAS', 'REPROVADO']
    variance = merged['REPROVADO'].div(merged['FEITAS']).sub(average)\
                                      .pow(2).sum() / merged.shape[0]
    standard_deviation = math.sqrt(variance)
    return (average, standard_deviation)

52
53
54
55
56
def general_ira(df):
    fixed = df[df.SITUACAO.isin(Situation.SITUATION_AFFECT_IRA)]
    fixed = fixed[fixed.MEDIA_FINAL <= 100]
    return (fixed.MEDIA_FINAL.mean(), fixed.MEDIA_FINAL.std())

bhm15's avatar
bhm15 committed
57
58
59
60
61
62
63
64
65
66
67
68
69
70
def current_ira(df):
    ano_grade = int(df.loc[df['NUM_VERSAO'].idxmax()]['NUM_VERSAO'])
    fixed = df.loc[(df['NUM_VERSAO'] == ano_grade)]
    fixed = fixed[fixed.SITUACAO.isin(Situation.SITUATION_AFFECT_IRA)]
    fixed = fixed[fixed.MEDIA_FINAL <= 100]
    return (fixed.MEDIA_FINAL.mean(), fixed.MEDIA_FINAL.std())

def current_students_ira(df):
    fixed = df.loc[(df.FORMA_EVASAO == EvasionForm.EF_ATIVO)]
    fixed = fixed[fixed.SITUACAO.isin(Situation.SITUATION_AFFECT_IRA)]
    fixed = fixed[fixed.MEDIA_FINAL <= 100]
    return (fixed.MEDIA_FINAL.mean(), fixed.MEDIA_FINAL.std())

def general_evasion_rate(df):
71
72
73
74
75
76
    students = df['MATR_ALUNO'].drop_duplicates()
    total_student = students.shape[0]
    total_evasion = students.loc[(df.FORMA_EVASAO != EvasionForm.EF_ATIVO) & (df.FORMA_EVASAO != EvasionForm.EF_FORMATURA) & (df.FORMA_EVASAO != EvasionForm.EF_REINTEGRACAO)].shape[0]

    return total_evasion / total_student

bhm15's avatar
bhm15 committed
77
78
79
80
81
82
83
84
85
def current_evasion_rate(df):
    ano_grade = int(df.loc[df['NUM_VERSAO'].idxmax()]['NUM_VERSAO'])
    students = df.loc[(df['NUM_VERSAO'] == ano_grade)]
    students = students['MATR_ALUNO'].drop_duplicates()
    total_student = students.shape[0]
    total_evasion = students.loc[(df.FORMA_EVASAO != EvasionForm.EF_ATIVO) & (df.FORMA_EVASAO != EvasionForm.EF_FORMATURA) & (df.FORMA_EVASAO != EvasionForm.EF_REINTEGRACAO)].shape[0]

    return total_evasion / total_student

86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
def average_graduation_time(df):
    graduates = df.loc[(df.FORMA_EVASAO == EvasionForm.EF_FORMATURA)]
    total_graduate = graduates.shape[0]
    average_time = 0
    year_end = int(df['ANO'].max())
    semester_end = graduates['PERIODO'].max()
    for index, row in graduates.iterrows():
        if pd.notnull(row['ANO_EVASAO']):
            year_end = int(row['ANO_EVASAO'])
            try: 
                semester_end = int(row['SEMESTRE_EVASAO'])
            except ValueError:
                semester_end = graduates['PERIODO'].max()
        year = int(row['ANO_INGRESSO'])
        semester = int(row['SEMESTRE_INGRESSO'])
        difference = 2 * (year_end - year) + (semester_end - semester) + 1
        average_time += difference
    average_time /= total_graduate
    average_time /= 2

    return average_time
bhm15's avatar
bhm15 committed
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

def total_students(df):
    return df.drop_duplicates('MATR_ALUNO').shape[0]

def current_total_students(df):
    return df.loc[(df.FORMA_EVASAO == EvasionForm.EF_ATIVO)].drop_duplicates('MATR_ALUNO').shape[0]

def taxa_abandono(df):
    students = df['MATR_ALUNO'].drop_duplicates()
    total_student = students.shape[0]
    total_abandono = students.loc[(df.FORMA_EVASAO == EvasionForm.EF_ABANDONO)].shape[0]

    return total_abandono / total_student

def average_ira_graph(df):
    alunos = df.drop_duplicates('MATR_ALUNO')

    dic = build_dict_ira_medio(alunos)

    return dic

def current_students_average_ira_graph(df):
    alunos_se = df.loc[(df.FORMA_EVASAO == EvasionForm.EF_ATIVO)]
    alunos_se = alunos_se.drop_duplicates('MATR_ALUNO')

    dic_se = build_dict_ira_medio(alunos_se)

    return dic_se

def graduates_average_ira_graph(df):
    alunos_for = df.loc[(df.FORMA_EVASAO == EvasionForm.EF_FORMATURA)]
    alunos_for = alunos_for.drop_duplicates('MATR_ALUNO')

    dic_for = build_dict_ira_medio(alunos_for)

    return dic_for

def period_evasion_graph(df):
    di_qtd = {}
    dic = {}
    evasions_total = 0
148
149
    
    # Discover the minimum and maximum values for year
bhm15's avatar
bhm15 committed
150
151
    year_start = int(df['ANO'].min())
    year_end = int(df['ANO'].max()) + 1
152

bhm15's avatar
bhm15 committed
153
    students = df.drop_duplicates()
154
155
156


    # Iterate between all semester/year possible
bhm15's avatar
bhm15 committed
157
158
    for year in range(year_start, year_end):
        for semester in range(1, 3):
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176

            # Filter the rows and mantain only the registers
            # that match with year and semester of this iteration
            evasions = students.loc[
                (df['ANO_EVASAO'] == str(year)) &
                (df['SEMESTRE_EVASAO'] == str(semester))
            ]

            # Count only one row per student by removing
            # all duplicate rows with same MATR_ALUNO
            # and keeping the first row founded
            # Than, get the number of rows computed
            evasions = evasions.drop_duplicates(
                subset="MATR_ALUNO",
                keep='first'
            ).shape[0]

            # Name of string on dictionary generated
bhm15's avatar
bhm15 committed
177
178
            date = str(year) + ' {}º Período'.format(semester)
            di_qtd[date] = evasions
179
180
181
            
            # Count the total of evasions identified, that will be
            # used to compute the rate
bhm15's avatar
bhm15 committed
182
            evasions_total += evasions
183
184
    
    # If at least one evasion was computed
bhm15's avatar
bhm15 committed
185
    if evasions_total:
186
187
        # Compute the ratio of evasion per
        # semester and name the attributes
bhm15's avatar
bhm15 committed
188
189
        for di in di_qtd:
            qtd = di_qtd[di]
190
191
            dic[di] = {'qtd': qtd, 'taxa': (float(qtd)/evasions_total)*100}
    
bhm15's avatar
bhm15 committed
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
    return dic

def build_dict_ira_medio(alunos):
    dic = {"00-4.9":0, "05-9.9":0, "10-14.9":0, "15-19.9":0, "20-24.9":0, "25-29.9":0, "30-34.9":0,
           "35-39.9":0, "40-44.9":0, "45-49.9":0, "50-54.9":0, "55-59.9":0, "60-64.9":0, "65-69.9":0,
           "70-74.9":0, "75-79.9":0, "80-84.9":0, "85-89.9":0, "90-94.9": 0,"95-100":0}

    iras = []
    for index, row in alunos.iterrows():
        if(row['MEDIA_FINAL'] is not None):
            iras.append(row['MEDIA_FINAL'])

    for d in dic:
        aux = d.split('-')
        v1 = float(aux[0])
        if (v1 == 0.0):
            v1 += 0.01
        v2 = float(aux[1])
        dic[d] = sum((float(num) >= v1) and (float(num) < v2) for num in iras)

    return dic

214
def build_degree_json(path,df):
215
    
bhm15's avatar
bhm15 committed
216
217
218
219
220
    def merge_dicts(dict1, dict2, dict3):
        dict_out = {}
        for key, value in dict1.items():
            v2 = dict2[key] if key in dict2 else None
            v3 = dict3[key] if key in dict3 else None
221
222
223
224
225
226
            dict_out[key] = {
                'ira_medio': value,
                'sem_evasao': v2,
                'formatura': v3
            }
        
bhm15's avatar
bhm15 committed
227
        return dict_out
228
229
230
231
232
233
234

    dic = merge_dicts(
        average_ira_graph(df),
        current_students_average_ira_graph(df),
        graduates_average_ira_graph(df)
    )

bhm15's avatar
bhm15 committed
235
236
237
238
239
240
241
242
243
244
245
246
247
    degree_json = {
        "ira_medio_grafico": json.dumps(sorted(dic.items())),
        "evasao_grafico": json.dumps(sorted(period_evasion_graph(df).items())),
        "ira_atual": current_students_ira(df),
        "ira_medio": general_ira(df),
        "qtd_alunos": total_students(df),
        "qtd_alunos_atuais": current_total_students(df),
        "taxa_evasao": general_evasion_rate(df),
        "taxa_formatura": average_graduation(df),
        "taxa_reprovacao": general_failure(df),
        "taxa_reprovacao_atual": current_students_failure(df),
        "tempo_formatura": average_graduation_time(df),
    }
248
    with open(path+"/degree.json",'w') as f:
bhm15's avatar
bhm15 committed
249
        f.write(json.dumps(degree_json,indent=4))