Skip to content

visualizations.charts

AFSCsChart(instance)

This is a class dedicated to creating "AFSCs Charts" which are all charts that include AFSCs on the x-axis. This is meant to condense the amount of code and increase read-ability of the various kinds of charts.

Source code in afccp/visualizations/charts.py
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
def __init__(self, instance):
    """
    This is a class dedicated to creating "AFSCs Charts" which are all charts
    that include AFSCs on the x-axis. This is meant to condense the amount of code and increase
    read-ability of the various kinds of charts.
    """

    # Load attributes
    self.parameters = instance.parameters
    self.value_parameters, self.vp_name = instance.value_parameters, instance.vp_name
    self.ip = instance.mdl_p  # "instance plot parameters"
    self.solution, self.solution_name = instance.solution, instance.solution_name
    self.data_name, self.data_version = instance.data_name, instance.data_version

    # Dictionaries of instance components (sets of value parameters, solutions)
    self.vp_dict, self.solutions = instance.vp_dict, instance.solutions

    # Initialize the matplotlib figure/axes
    self.fig, self.ax = plt.subplots(figsize=self.ip['figsize'], facecolor=self.ip['facecolor'], tight_layout=True,
                                     dpi=self.ip['dpi'])

    # Label dictionary for AFSC objectives
    self.label_dict = copy.deepcopy(afccp.globals.obj_label_dict)

    # This is going to be a dictionary of all the various chart-specific components we need
    self.c = {"J": self.ip['J'], 'afscs': self.ip['afscs'], 'M': self.ip['M'], 'k': 0,  # Default k
              'y_max': self.ip['y_max'], 'legend_elements': None, 'use_calculated_y_max': False,
              'legend_title': None}

    # If we skip AFSCs
    if self.ip["skip_afscs"]:
        self.c["tick_indices"] = np.arange(1, self.c["M"], 2).astype(int)
    else:
        self.c["tick_indices"] = np.arange(self.c["M"]).astype(int)

    # Where to save the chart
    self.paths = {"Data": instance.export_paths["Analysis & Results"] + "Data Charts/",
                  "Solution": instance.export_paths["Analysis & Results"] + self.solution_name + "/",
                  "Comparison": instance.export_paths["Analysis & Results"] + "Comparison Charts/"}

build(chart_type='Data', printing=True)

Builds the specific chart based on what the user passes within the "instance plot parameters" (ip)

Source code in afccp/visualizations/charts.py
 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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
def build(self, chart_type="Data", printing=True):
    """
    Builds the specific chart based on what the user passes within the "instance plot parameters" (ip)
    """

    # If we don't have that data, just fill this in so this chart still works
    if 'race_categories' not in self.parameters.keys():
        self.parameters['race_categories'] = ['Blank']
    if 'ethnicity_categories' not in self.parameters.keys():
        self.parameters['ethnicity_categories'] = ['Blank']

    # Determine which chart to build
    if chart_type == "Data":
        if self.ip['data_graph'] in ['Average Merit', 'USAFA Proportion', 'Average Utility']:
            self.data_average_chart()
        elif self.ip["data_graph"] == "AFOCD Data":
            self.data_afocd_chart()
        elif self.ip["data_graph"] == "Cadet Preference Analysis":
            self.data_preference_chart()
        elif self.ip["data_graph"] == "Eligible Quota":
            self.data_quota_chart()

        # Get filename
        if self.ip["filename"] is None:
            self.ip["filename"] = \
                self.data_name + " (" + self.data_version + ") " + self.ip["data_graph"] + " (Data).png"

    elif chart_type in ["Solution", "Comparison"]:

        # Only perform the following steps if it's for a "real" VP objective
        if self.ip['objective'] != 'Extra':

            # AFSC objective index and condense the AFSCs if this is an AFOCD objective
            self.c['k'] = np.where(self.value_parameters['objectives'] == self.ip['objective'])[0][0]
            self.condense_afscs_based_on_objective()

        # Need to know number of cadets assigned
        self.c['total_count'] = self.solution["count"][self.c['J']]

        # Determine if we sort the AFSCs by PGL or not
        if self.ip['sort_by_pgl'] and "STEM" not in self.ip['version']:
            quota = np.array([self.parameters['pgl'][j] for j in self.c['J']])

            # Sort the AFSCs by the PGL
            indices = np.argsort(quota)[::-1]
            self.c['afscs'] = self.c['afscs'][indices]
            self.c['total_count'] = self.c['total_count'][indices]
            self.c['J'] = self.c['J'][indices]

        # Sort by STEM AFSCs
        if "STEM" in self.ip['version']:

            # Sort all the AFSCs by the PGL
            sorted_indices = np.argsort(self.parameters['pgl'])[::-1]

            # Sort the AFSCs by "Not STEM", "Hybrid", "STEM" and then by PGL
            sorted_j = []
            for cat in ["Not STEM", "Hybrid", "STEM"]:
                for j in sorted_indices:
                    if j in p['J^' + cat] and j in self.c['J']:
                        sorted_j.append(j)

            # Sort the specific elements of this chart
            indices = np.array(sorted_j)
            self.c['afscs'] = self.c['afscs'][indices]
            self.c['total_count'] = self.c['total_count'][indices]
            self.c['J'] = self.c['J'][indices]

        if self.ip['results_graph'] == 'Solution Comparison':
            self.results_solution_comparison_chart()
        else:

            if self.ip['objective'] != 'Extra':

                # Default y-label
                self.c['y_label'] = self.label_dict[self.ip['objective']]

                # Shared elements
                self.c['measure'] = self.solution['objective_measure'][self.c['J'], self.c['k']]

                # Build the Merit Chart
                if self.ip['objective'] == 'Merit':
                    self.results_merit_chart()

                # Demographic Chart
                elif self.ip['objective'] in ['USAFA Proportion', 'Male', 'Minority']:
                    self.results_demographic_chart()

                # AFOCD Degree Tier Chart
                elif self.ip['objective'] in ['Mandatory', 'Desired', 'Permitted', 'Tier 1', 'Tier 2',
                                              'Tier 3', 'Tier 4']:
                    self.results_degree_tier_chart()

                # Combined Quota Chart
                elif self.ip['objective'] == 'Combined Quota':
                    self.results_quota_chart()

                # Cadet/AFSC Preference Chart
                elif self.ip['objective'] == 'Utility':
                    self.results_preference_chart()
                elif self.ip['objective'] == 'Norm Score':
                    if self.ip['version'] == 'bar':
                        self.results_norm_score_chart()
                    else:
                        self.results_preference_chart()

            else:

                # Demographic Charts
                if self.ip['version'] in ['Race Chart', 'Gender Chart', 'Ethnicity Chart', 'SOC Chart',
                                          'Race Chart_proportion', 'Gender Chart_proportion',
                                          'Ethnicity Chart_proportion', 'SOC Chart_proportion']:

                    # if 'race_categories' not in self.parameters:
                    #     return None  # We're not doing this

                    self.results_demographic_proportion_chart()

        # Get filename
        if self.ip["filename"] is None:
            self.ip["filename"] = self.data_name + " (" + self.data_version + ") " + self.solution_name + " " + \
                                  self.ip['objective'] + ' ' + self.ip["results_graph"] + " [" + \
                                  self.ip['version'] + "] (Results).png"
    else:
        raise ValueError("Error. Invalid AFSC 'main' chart type value of '" +
                         chart_type + "'. Valid inputs are 'Data' or 'Results'.")

    # Put the solution name in the title
    if self.ip["solution_in_title"]:
        self.ip['title'] = self.solution_name + ": " + self.ip['title']

    # Display title
    if self.ip['display_title']:
        self.fig.suptitle(self.ip['title'], fontsize=self.ip['title_size'])

    # Labels
    self.ax.set_ylabel(self.c["y_label"])
    self.ax.yaxis.label.set_size(self.ip['label_size'])
    self.ax.set_xlabel('AFSCs')
    self.ax.xaxis.label.set_size(self.ip['label_size'])

    if self.ip["color_afsc_text_by_grp"]:
        afsc_colors = [self.ip['bar_colors'][self.parameters['acc_grp'][j]] for j in self.c['J']]
    else:
        afsc_colors = ["black" for _ in self.c['afscs']]

    # X axis
    self.ax.tick_params(axis='x', labelsize=self.ip['afsc_tick_size'])
    self.ax.set_xticklabels(self.c["afscs"][self.c["tick_indices"]], rotation=self.ip['afsc_rotation'])
    self.ax.set_xticks(self.c["tick_indices"])
    self.ax.set(xlim=(-0.8, self.c["M"]))

    # Unique AFSC colors potentially based on accessions group
    for index, xtick in enumerate(self.ax.get_xticklabels()):
        xtick.set_color(afsc_colors[index])

    # Y axis
    self.ax.tick_params(axis='y', labelsize=self.ip['yaxis_tick_size'])
    self.ax.set(ylim=(0, self.c["y_max"]))
    if "y_ticks" in self.c and self.c['y_max'] > 50:
        self.ax.set_yticklabels(self.c['y_ticks'])
        self.ax.set_yticks(self.c['y_ticks'])

    # Legend
    if self.ip["add_legend_afsc_chart"] and self.c['legend_elements'] is not None:

        if self.c['legend_title']:
            self.ax.legend(handles=self.c["legend_elements"], edgecolor='black', loc=self.ip['legend_loc'],
                           fontsize=self.ip['legend_size'], ncol=self.ip['ncol'], labelspacing=1, handlelength=0.8,
                           handletextpad=0.2, borderpad=0.2, handleheight=2, title=self.c['legend_title'],
                           title_fontsize=self.ip['legend_fontsize'])
        else:
            self.ax.legend(handles=self.c["legend_elements"], edgecolor='black', loc=self.ip['legend_loc'],
                           fontsize=self.ip['legend_size'], ncol=self.ip['ncol'], labelspacing=1, handlelength=0.8,
                           handletextpad=0.2, borderpad=0.2, handleheight=2)

    # Save the chart
    if self.ip['save']:
        self.fig.savefig(self.paths[chart_type] + self.ip["filename"])

        if printing:
            print("Saved", self.ip["filename"], "Chart to " + self.paths[chart_type] + ".")
    else:
        if printing:
            print("Created", self.ip["filename"], "Chart.")

    # Return the full chart object
    return self

condense_afscs_based_on_objective()

This method reduces the AFSCs we're looking at based on the AFSCs that have a non-zero objective weight for AFOCD objectives

Source code in afccp/visualizations/charts.py
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
def condense_afscs_based_on_objective(self):
    """
    This method reduces the AFSCs we're looking at based on the AFSCs that have a non-zero objective weight
    for AFOCD objectives
    """

    # If it's an AFOCD objective, we only take the AFSCs that have that objective
    if self.ip['objective'] in ['Mandatory', 'Desired', 'Permitted', 'Tier 1', 'Tier 2', 'Tier 3', 'Tier 4']:
        self.c['J'] = np.array([j for j in self.c['J'] if self.c['k'] in self.value_parameters['K^A'][j]]).astype(int)
        self.c['afscs'] = self.parameters['afscs'][self.c['J']]
        self.c['M'] = len(self.c['afscs'])

        # Make sure we're not skipping AFSCs at this point
        self.c["tick_indices"] = np.arange(self.c["M"]).astype(int)

    # Make sure at least one AFSC has this objective selected
    if self.c['M'] == 0:
        raise ValueError("Error. No AFSCs have objective '" + self.ip["objective"] + "'.")

determine_y_max_and_y_ticks()

This method calculates the correct y_max and y_ticks for this chart in place

Source code in afccp/visualizations/charts.py
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
def determine_y_max_and_y_ticks(self):
    """
    This method calculates the correct y_max and y_ticks for this chart in place
    """
    # Y max
    if self.ip['y_exact_max'] is None:
        self.c['y_max'] = self.ip['y_max'] * max(self.c['total_count'])
    else:
        self.c['y_max'] = self.ip['y_max'] * self.ip['y_exact_max']

    if 100 <= self.c['y_max'] < 150:
        self.c['y_ticks'] = [50, 100, 150]
    elif 150 <= self.c['y_max'] < 200:
        self.c['y_ticks'] = [50, 100, 150, 200]
    elif 200 <= self.c['y_max'] < 250:
        self.c['y_ticks'] = [50, 100, 150, 200, 250]
    elif 250 <= self.c['y_max'] < 300:
        self.c['y_ticks'] = [50, 100, 150, 200, 250, 300]
    elif 250 <= self.c['y_max'] < 300:
        self.c['y_ticks'] = [50, 100, 150, 200, 250, 300, 350]
    elif self.c['y_max'] >= 500:
        self.c['y_ticks'] = [100, 200, 300, 400, 500, 600]
    else:
        self.c['y_ticks'] = [50]

construct_gradient_chart(parameter_to_use='cadet_utility')

Constructs the gradient chart with "DIY color bar"

Source code in afccp/visualizations/charts.py
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
def construct_gradient_chart(self, parameter_to_use='cadet_utility'):
    """
    Constructs the gradient chart with "DIY color bar"
    """

    # Shorthand
    p = self.parameters

    for index, j in enumerate(self.c['J']):
        cadets = np.where(self.solution['j_array'] == j)[0]

        # What are we plotting
        if 'parameter_to_use' == 'cadet_utility':
            measure = p["utility"][cadets, j]
        else:
            measure = p["merit"][cadets]

        # Plot the bar
        uq = np.unique(measure)
        count_sum = 0
        for val in uq:
            count = len(np.where(measure == val)[0])

            if parameter_to_use == 'cadet_utility':
                c = (1 - val, 0, val)  # Blue to Red
            else:
                c = str(val)  # Grayscale
            self.ax.bar([index], count, bottom=count_sum, color=c)
            count_sum += count

        # Add the text
        self.ax.text(index, self.c['total_count'][index] + self.ip['bar_text_offset'], int(self.c['total_count'][index]),
                     fontsize=self.ip["text_size"], horizontalalignment='center')

    # DIY Colorbar
    h = (100 / 245) * self.c['y_max']
    w1 = 0.8
    w2 = 0.74
    vals = np.arange(101) / 100
    current_height = (150 / 245) * self.c['y_max']
    self.ax.add_patch(Rectangle((self.c['M'] - 2, current_height), w1, h, edgecolor='black', facecolor='black',
                                fill=True, lw=2))
    self.ax.text(self.c['M'] - 3.3, (245 / 245) * self.c['y_max'], '100%', fontsize=self.ip["xaxis_tick_size"])
    self.ax.text(self.c['M'] - 2.8, current_height, '0%', fontsize=self.ip["xaxis_tick_size"])
    self.ax.text((self.c['M'] - 0.95), (166 / 245) * self.c['y_max'], 'Cadet Satisfaction',
                fontsize=self.ip["xaxis_tick_size"], rotation=270)
    for val in vals:
        if parameter_to_use == 'cadet_utility':
            c = (1 - val, 0, val)  # Blue to Red
        else:
            c = str(val)  # Grayscale
        self.ax.add_patch(Rectangle((self.c['M'] - 1.95, current_height), w2, h / 101, facecolor=c, fill=True))
        current_height += h / 101

data_average_chart()

This method builds the "Average Merit", "USAFA Proportion", and "Average Utility" data graph charts. They are all in a very similar format and are therefore combined

Source code in afccp/visualizations/charts.py
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
def data_average_chart(self):
    """
    This method builds the "Average Merit", "USAFA Proportion", and "Average Utility" data graph charts. They are
    all in a very similar format and are therefore combined
    """

    # Shorthand
    p = self.parameters

    # Get correct solution and targets
    if self.ip['data_graph'] == "Average Merit":
        metric = np.array([np.mean(p['merit'][p['I^E'][j]]) for j in self.c["J"]])
        target = 0.5
    elif self.ip['data_graph'] == 'USAFA Proportion':
        metric = np.array([len(p['I^D']['USAFA Proportion'][j]) / len(p['I^E'][j]) for j in self.c["J"]])
        target = p['usafa_proportion']
    else:
        if self.ip["eligibility"]:
            metric = np.array([np.mean(p['utility'][p['I^E'][j], j]) for j in self.c["J"]])
        else:
            metric = np.array([np.mean(p['utility'][:, j]) for j in self.c["J"]])
        target = None

    # Axis Adjustments
    self.ax.set(ylim=(0, 1))

    # Bar Chart
    self.ax.bar(self.c['afscs'], metric, color=self.ip["bar_color"], alpha=self.ip["alpha"], edgecolor='black')

    # Add a "target" line
    if target is not None:
        self.ax.axhline(y=target, color='black', linestyle='--', alpha=self.ip["alpha"])

    # Get correct label, title
    self.c['y_label'] = self.ip['data_graph']
    if self.ip['title'] is None:
        self.ip['title'] = self.ip['data_graph'] + ' Across '
        if self.ip['data_graph'] == 'Average Utility' and not self.ip['eligibility']:
            self.ip['title'] += 'All Cadets'
        else:
            self.ip['title'] += 'Eligible Cadets'
        if self.ip['eligibility_limit'] != p['N']:
            self.ip['title'] += ' for AFSCs with <= ' + \
                                str(self.ip['eligibility_limit']) + ' Eligible Cadets'

data_afocd_chart()

This method builds the "AFOCD Data" data graph chart.

Source code in afccp/visualizations/charts.py
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
def data_afocd_chart(self):
    """
    This method builds the "AFOCD Data" data graph chart.
    """

    # Shorthand
    p = self.parameters

    # Legend
    self.c["legend_elements"] = [
        Patch(facecolor=self.ip["bar_colors"]["Permitted"], label='Permitted', edgecolor='black'),
        Patch(facecolor=self.ip["bar_colors"]["Desired"], label='Desired', edgecolor='black'),
        Patch(facecolor=self.ip["bar_colors"]["Mandatory"], label='Mandatory', edgecolor='black')]

    # Get solution
    mandatory_count = np.array([np.sum(p['mandatory'][:, j]) for j in self.c["J"]])
    desired_count = np.array([np.sum(p['desired'][:, j]) for j in self.c["J"]])
    permitted_count = np.array([np.sum(p['permitted'][:, j]) for j in self.c["J"]])

    # Bar Chart
    self.ax.bar(self.c["afscs"], mandatory_count, color=self.ip["bar_colors"]["Mandatory"], edgecolor='black')
    self.ax.bar(self.c["afscs"], desired_count, bottom=mandatory_count,
                color=self.ip["bar_colors"]["Desired"], edgecolor='black')
    self.ax.bar(self.c["afscs"], permitted_count, bottom=mandatory_count + desired_count,
                color=self.ip["bar_colors"]["Permitted"], edgecolor='black')

    # Axis Adjustments
    self.ax.set(ylim=(0, self.ip['eligibility_limit'] + self.ip['eligibility_limit'] / 100))

    # Get correct text
    self.c["y_label"] = "Number of Cadets"
    if self.ip['title'] is None:
        self.ip['title'] = 'AFOCD Degree Tier Breakdown'
        if self.ip['eligibility_limit'] != p['N']:
            self.ip['title'] += ' for AFSCs with <= ' + \
                                str(self.ip['eligibility_limit']) + ' Eligible Cadets'

data_preference_chart()

This method generates the "Cadet Preference" charts based on the version specified

Source code in afccp/visualizations/charts.py
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
def data_preference_chart(self):
    """
    This method generates the "Cadet Preference" charts based on the version
    specified
    """

    # Shorthand
    p = self.parameters

    # Choice Counts
    top_3_count = np.array([sum(p["Choice Count"][choice][j] for choice in [0, 1, 2]) for j in p["J"]])
    next_3_count = np.array([sum(p["Choice Count"][choice][j] for choice in [3, 4, 5]) for j in p["J"]])

    # Sets of cadets that have the AFSC in their top 3 choices and are eligible for the AFSC
    top_3_cadets = {}
    top_3_eligible_cadets = {}
    for j in p["J"]:
        top_3_cadets[j] = []
        top_3_eligible_cadets[j] = []
        for i in p["I"]:
            for choice in [0, 1, 2]:
                if i in p["I^Choice"][choice][j]:
                    top_3_cadets[j].append(i)
                    if i in p["I^E"][j]:
                        top_3_eligible_cadets[j].append(i)
        top_3_cadets[j] = np.array(top_3_cadets[j])
        top_3_eligible_cadets[j] = np.array(top_3_eligible_cadets[j])

    # AFOCD solution
    mandatory_count = np.array([np.sum(p['mandatory'][top_3_cadets[j], j]) for j in p["J"]])
    desired_count = np.array([np.sum(p['desired'][top_3_cadets[j], j]) for j in p["J"]])
    permitted_count = np.array([np.sum(p['permitted'][top_3_cadets[j], j]) for j in p["J"]])
    ineligible_count = np.array([np.sum(p['ineligible'][top_3_cadets[j], j]) for j in p["J"]])

    # Version 1
    if self.ip["version"] == "1":
        self.c["legend_elements"] = [
            Patch(facecolor=self.ip['bar_colors']["top_choices"], label='Top 3 Choices', edgecolor='black'),
            Patch(facecolor=self.ip['bar_colors']["mid_choices"], label='Next 3 Choices', edgecolor='black')]

        # Bar Chart
        self.ax.bar(self.c["afscs"], next_3_count, color=self.ip['bar_colors']["mid_choices"], edgecolor='black')
        self.ax.bar(self.c["afscs"], top_3_count, bottom=next_3_count, color=self.ip['bar_colors']["top_choices"],
                    edgecolor='black')

        # Y max used for axis adjustments
        self.c["y_max"] = np.max(top_3_count + next_3_count)

        if self.ip['title'] is None:
            self.ip['title'] = "Cadet Preferences Placed on Each AFSC (Before Match)"

    # Version 2
    elif self.ip["version"] == "2":
        self.c["legend_elements"] = [
            Patch(facecolor=self.ip['bar_colors']["top_choices"], label='Top 3 Choices', edgecolor='black')]

        # Bar Chart
        self.ax.bar(self.c["afscs"], top_3_count, color=self.ip['bar_colors']["top_choices"], edgecolor='black')

        # Y max used for axis adjustments
        self.c["y_max"] = np.max(top_3_count)

        if self.ip['title'] is None:
            self.ip['title'] = "Cadet Top 3 Preferences Placed on Each AFSC (Before Match)"

    # Version 3
    elif self.ip["version"] == "3":
        self.c["legend_elements"] = [Patch(facecolor=self.ip['bar_colors'][objective], label=objective) for
                                     objective in ["Ineligible", "Permitted", "Desired", "Mandatory"]]

        # Bar Chart
        self.ax.bar(self.c["afscs"], mandatory_count, color=self.ip['bar_colors']["Mandatory"], edgecolor='black')
        self.ax.bar(self.c["afscs"], desired_count, bottom=mandatory_count, color=self.ip['bar_colors']["Desired"],
               edgecolor='black')
        self.ax.bar(self.c["afscs"], permitted_count, bottom=desired_count + mandatory_count,
                    color=self.ip['bar_colors']["Permitted"], edgecolor='black')
        self.ax.bar(self.c["afscs"], ineligible_count, bottom=permitted_count + desired_count + mandatory_count,
               color=self.ip['bar_colors']["Ineligible"], edgecolor='black')

        # Y max used for axis adjustments
        self.c["y_max"] = np.max(top_3_count)

        if self.ip['title'] is None:
            self.ip['title'] = "Cadet Degree Eligibility of Preferred Cadets on Each AFSC (Before Match)"

    # Version 4
    elif self.ip["version"] == "4":
        self.c["legend_elements"] = [Patch(facecolor=self.ip['bar_colors'][objective], label=objective) for
                                     objective in ["Permitted", "Desired", "Mandatory"]]

        # Bar Chart
        self.ax.bar(self.c["afscs"], mandatory_count, color=self.ip['bar_colors']["Mandatory"],
                    edgecolor='black')
        self.ax.bar(self.c["afscs"], desired_count, bottom=mandatory_count,
                    color=self.ip['bar_colors']["Desired"],
                    edgecolor='black')
        self.ax.bar(self.c["afscs"], permitted_count, bottom=desired_count + mandatory_count,
                    color=self.ip['bar_colors']["Permitted"], edgecolor='black')

        # Y max used for axis adjustments
        self.c["y_max"] = np.max(top_3_count)

        if self.ip['title'] is None:
            self.ip['title'] = "Cadet Degree Eligibility of Preferred Cadets on Each AFSC (Before Match)"

    # Version 5
    elif self.ip["version"] == "5":

        # Build a gradient
        for j in p["J"]:
            merit = p["merit"][top_3_eligible_cadets[j]]
            uq = np.unique(merit)
            count_sum = 0
            for val in uq:
                count = len(np.where(merit == val)[0])
                c = str(val)  # Grayscale
                self.ax.bar([j], count, bottom=count_sum, color=c, zorder=2)
                count_sum += count

            # Add the text and an outline
            self.ax.text(j, len(top_3_eligible_cadets[j]) + 4, round(np.mean(merit), 2),
                         fontsize=self.ip["text_size"], horizontalalignment='center')
            self.ax.bar([j], len(top_3_eligible_cadets[j]), color="black", zorder=1, edgecolor="black")

        # Y max used for axis adjustments
        self.c["y_max"] = np.max(top_3_count)

        # DIY Colorbar
        h = (100 / 245) * self.c["y_max"]
        w1 = 0.8
        w2 = 0.74
        current_height = (150 / 245) * self.c["y_max"]
        self.ax.add_patch(Rectangle((self.c["M"] - 2, current_height), w1, h, edgecolor='black', facecolor='black',
                                    fill=True, lw=2))
        self.ax.text(self.c["M"] - 3.3, (245 / 245) * self.c["y_max"], '100%', fontsize=self.ip["text_size"])
        self.ax.text(self.c["M"] - 2.8, current_height, '0%', fontsize=self.ip["text_size"])
        self.ax.text((self.c["M"] - 0.95), (166 / 245) * self.c["y_max"], 'Cadet Percentile',
                     fontsize=self.ip["text_size"], rotation=270)
        vals = np.arange(101) / 100
        for val in vals:
            c = str(val)  # Grayscale
            self.ax.add_patch(Rectangle((self.c["M"] - 1.95, current_height), w2, h / 101, color=c, fill=True))
            current_height += h / 101

        # Y max used for axis adjustments
        self.c["y_max"] = np.max(top_3_count)

        if self.ip['title'] is None:
            self.ip['title'] = "Merit of Preferred Cadets on Each AFSC (Before Match)"

    # Version 6
    elif self.ip["version"] == "6":
        self.c["legend_elements"] = [
            Patch(facecolor=self.ip['bar_colors']["usafa"], label='USAFA'),
            Patch(facecolor=self.ip['bar_colors']["rotc"], label='ROTC'),
            mlines.Line2D([], [], color="red", linestyle='-', linewidth=3, label="Baseline")]

        # USAFA/ROTC Numbers
        rotc_baseline = np.array([len(top_3_eligible_cadets[j]) - (
                len(top_3_eligible_cadets[j]) * p["usafa_proportion"]) for j in p["J"]])
        usafa_count = np.array([np.sum(p['usafa'][top_3_eligible_cadets[j]]) for j in p["J"]])
        rotc_count = np.array([len(top_3_eligible_cadets[j]) - usafa_count[j] for j in p["J"]])

        # Bar Chart
        self.ax.bar(self.c["afscs"], rotc_count, color=self.ip['bar_colors']["rotc"], edgecolor='black')
        self.ax.bar(self.c["afscs"], usafa_count, bottom=rotc_count, color=self.ip['bar_colors']["usafa"],
                    edgecolor='black')

        # Add the baseline marks
        for j in p["J"]:
            self.ax.plot((j - 0.4, j + 0.4), (rotc_baseline[j], rotc_baseline[j]),
                    color="red", linestyle="-", zorder=2, linewidth=3)

        # Y max used for axis adjustments
        self.c["y_max"] = np.max(top_3_count)

        if self.ip['title'] is None:
            self.ip['title'] = "USAFA/ROTC Breakdown of Preferred Cadets on Each AFSC (Before Match)"

    # Version 7
    elif self.ip["version"] == "7":
        self.c["legend_elements"] = [
            Patch(facecolor=self.ip['bar_colors']["male"], label='Male'),
            Patch(facecolor=self.ip['bar_colors']["female"], label='Female'),
            mlines.Line2D([], [], color="red", linestyle='-', linewidth=3, label="Baseline")]

        # USAFA/ROTC Numbers
        female_baseline = np.array([len(top_3_eligible_cadets[j]) - (
                len(top_3_eligible_cadets[j]) * p["male_proportion"]) for j in p["J"]])
        male_count = np.array([np.sum(p['male'][top_3_eligible_cadets[j]]) for j in p["J"]])
        female_count = np.array([len(top_3_eligible_cadets[j]) - male_count[j] for j in p["J"]])

        # Bar Chart
        self.ax.bar(self.c["afscs"], female_count, color=self.ip['bar_colors']["female"], edgecolor='black')
        self.ax.bar(self.c["afscs"], male_count, bottom=female_count, color=self.ip['bar_colors']["male"],
                    edgecolor='black')

        # Add the baseline marks
        for j in p["J"]:
            self.ax.plot((j - 0.4, j + 0.4), (female_baseline[j], female_baseline[j]),
                         color="red", linestyle="-", zorder=2, linewidth=3)

        # Y max used for axis adjustments
        self.c["y_max"] = np.max(top_3_count)

        if self.ip['title'] is None:
            self.ip['title'] = "Male/Female Breakdown of Preferred Cadets on Each AFSC (Before Match)"

    else:
        raise ValueError("Version '" + str(
            self.ip["version"]) + "' is not valid for the Cadet Preference Analysis data graph.")

    # Axis Adjustments
    self.ax.set(ylim=(0, self.c["y_max"] * self.ip["y_max"]))

    # Get correct y-label
    self.c["y_label"] = "Number of Cadets"

    # Get filename
    if self.ip["filename"] is None:
        self.ip["filename"] = self.data_name + " (" + self.data_version + \
                              ") Cadet Preference Analysis Version " + self.ip["version"] + " (Data).png"

data_quota_chart()

This method builds the "Eligible Quota" data graph chart.

Source code in afccp/visualizations/charts.py
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
def data_quota_chart(self):
    """
    This method builds the "Eligible Quota" data graph chart.
    """

    # Shorthand
    p = self.parameters

    # Legend
    self.c["legend_elements"] = [Patch(facecolor='blue', label='Eligible Cadets', edgecolor='black'),
                                 Patch(facecolor='black', alpha=0.5, label='AFSC Quota', edgecolor='black')]

    # Get solution
    eligible_count = p["num_eligible"][self.c["J"]]
    quota = p['pgl'][self.c["J"]]

    # Bar Chart
    self.ax.bar(self.c["afscs"], eligible_count, color='blue', edgecolor='black')
    self.ax.bar(self.c["afscs"], quota, color='black', edgecolor='black', alpha=0.5)

    # Axis Adjustments
    self.ax.set(ylim=(0, self.ip['eligibility_limit'] + self.ip['eligibility_limit'] / 100))

    # Get correct text
    self.c["y_label"] = "Number of Cadets"
    if self.ip['title'] is None:
        self.ip['title'] = 'Eligible Cadets and Quotas'
        if self.ip['eligibility_limit'] != p['N']:
            self.ip['title'] += ' for AFSCs with <= ' + \
                           str(self.ip['eligibility_limit']) + ' Eligible Cadets'

results_solution_comparison_chart()

This method plots the solution comparison chart for the chosen objective specified

Source code in afccp/visualizations/charts.py
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
def results_solution_comparison_chart(self):
    """
    This method plots the solution comparison chart for the chosen objective specified
    """

    # Shorthand
    p, vp = self.parameters, self.value_parameters
    k = self.c['k']

    # Make sure at least one AFSC has this objective selected
    if self.c['M'] == 0:
        raise ValueError("Error. No AFSCs have objective '" + ip["objective"] + "'.")

    # Keep track of useful variables
    x_under, x_over = [], []
    quota_percent_filled, max_quota_percent = np.zeros(self.c['M']), np.zeros(self.c['M'])
    self.c['legend_elements'] = []
    max_measure = np.zeros(self.c['M'])
    y_top = 0

    if self.ip['ncol'] != 1:
        self.ip['ncol'] = len(self.ip['solution_names'])

    # Loop through each solution
    for s, solution in enumerate(self.ip["solution_names"]):

        # Calculate objective measure
        if self.ip['version'] == 'median_preference':
            cadets = [np.where(self.solutions[solution]['j_array'] == j)[0] for j in p['J']]
            measure = np.array([np.median(p['c_pref_matrix'][cadets[j], j]) for j in self.c['J']])
            self.label_dict[self.ip['objective']] = 'Median Cadet Choice'
        elif self.ip['version'] == 'mean_preference':
            cadets = [np.where(self.solutions[solution]['j_array'] == j)[0] for j in p['J']]
            measure = np.array([np.mean(p['c_pref_matrix'][cadets[j], j]) for j in self.c['J']])
            self.label_dict[self.ip['objective']] = 'Average Cadet Choice'
        elif self.ip['version'] == 'Race Chart':
            measure = np.array([self.solutions[solution]['simpson_index'][j] for j in self.c['J']])
            self.label_dict[self.ip['objective']] = 'Simpson Diversity Index'
        else:
            measure = self.solutions[solution]["objective_measure"][self.c['J'], k]
        if self.ip["objective"] == "Combined Quota":
            self.label_dict[self.ip["objective"]] = 'Proportion of PGL Target Met'  # Adjust Label

            # Assign the right color to the AFSCs
            for idx, j in enumerate(self.c['J']):

                # Get bounds
                value_list = vp['objective_value_min'][j, k].split(",")
                ub = float(value_list[1].strip())  # upper bound
                quota = p["pgl"][j]

                # Constraint violations
                if quota > measure[idx]:
                    x_under.append(idx)
                elif measure[idx] > ub:
                    x_over.append(idx)

                quota_percent_filled[idx] = measure[idx] / quota
                max_quota_percent[idx] = ub / quota

            # Top dot location
            y_top = max(y_top, max(quota_percent_filled))

            # Plot the points
            self.ax.scatter(self.c['afscs'], quota_percent_filled, color=self.ip["colors"][solution],
                            marker=self.ip["markers"][solution], alpha=self.ip["alpha"], edgecolor='black',
                            s=self.ip["dot_size"], zorder=self.ip["zorder"][solution])

        else:

            # Plot the points
            self.ax.scatter(self.c['afscs'], measure, color=self.ip["colors"][solution],
                            marker=self.ip["markers"][solution], alpha=self.ip["alpha"], edgecolor='black',
                            s=self.ip["dot_size"], zorder=self.ip["zorder"][solution])

        max_measure = np.array([max(max_measure[idx], measure[idx]) for idx in range(self.c['M'])])
        element = mlines.Line2D([], [], color=self.ip["colors"][solution], marker=self.ip["markers"][solution],
                                linestyle='None', markeredgecolor='black', markersize=self.ip['legend_dot_size'],
                                label=solution, alpha=self.ip["alpha"])
        self.c['legend_elements'].append(element)

    # Lines to the top solution's dot
    if self.ip["objective"] not in ["Combined Quota", "Mandatory", "Desired", "Permitted", 'Tier 1', 'Tier 2',
                                    'Tier 3', 'Tier 4']:
        for idx in range(self.c['M']):
            self.ax.plot((idx, idx), (0, max_measure[idx]), color='black', linestyle='--', zorder=1, alpha=0.5,
                          linewidth=2)

    # Objective Specific elements
    if self.ip["objective"] == "Merit":

        # Tick marks and extra lines
        self.c['y_ticks'] = [0, 0.35, 0.50, 0.65, 0.80, 1]
        self.ax.plot((-1, 50), (0.65, 0.65), color='blue', linestyle='-', zorder=1, alpha=0.5, linewidth=1.5)
        self.ax.plot((-1, 50), (0.5, 0.5), color='black', linestyle='--', zorder=1, alpha=0.5, linewidth=1.5)
        self.ax.plot((-1, 50), (0.35, 0.35), color='blue', linestyle='-', zorder=1, alpha=0.5, linewidth=1.5)

        # Set the max for the y-axis
        self.c['y_max'] = self.ip['y_max'] * np.max(max_measure)

    elif self.ip['version'] == 'Race Chart':
        baseline = self.parameters['baseline_simpson_index']
        self.c['y_ticks'] = [0, baseline, 1]
        self.ax.plot((-1, 50), (baseline, baseline), color='black', linestyle='--', zorder=1, alpha=0.5,
                     linewidth=1.5)

        # Set the max for the y-axis
        self.c['y_max'] = self.ip['y_max'] * np.max(max_measure)

    elif self.ip["objective"] in ["USAFA Proportion", "Male", "Minority"]:

        # Demographic Proportion elements
        prop_dict = {"USAFA Proportion": "usafa_proportion", "Male": "male_proportion",
                     "Minority": "minority_proportion"}
        up_lb = round(p[prop_dict[self.ip["objective"]]] - 0.15, 2)
        up_ub = round(p[prop_dict[self.ip["objective"]]] + 0.15, 2)
        up = round(p[prop_dict[self.ip["objective"]]], 2)
        self.c['y_ticks'] = [0, up_lb, up, up_ub, 1]

        # Add lines for the ranges
        self.ax.axhline(y=up, color='black', linestyle='--', alpha=0.5)
        self.ax.axhline(y=up_lb, color='blue', linestyle='-', alpha=0.5)
        self.ax.axhline(y=up_ub, color='blue', linestyle='-', alpha=0.5)

        # Set the max for the y-axis
        self.c['y_max'] = self.ip['y_max'] * np.max(max_measure)

    elif self.ip["objective"] in ["Mandatory", "Desired", "Permitted", "Tier 1", "Tier 2", 'Tier 3', "Tier 4"]:

        # Degree Tier elements
        self.c['y_ticks'] = [0, 0.2, 0.4, 0.6, 0.8, 1]
        minimums = np.zeros(self.c['M'])
        maximums = np.zeros(self.c['M'])

        # Assign the right color to the AFSCs
        for idx, j in enumerate(self.c['J']):
            if "Increasing" in vp["value_functions"][j, k]:
                minimums[idx] = vp['objective_target'][j, k]
                maximums[idx] = 1
            else:
                minimums[idx] = 0
                maximums[idx] = vp['objective_target'][j, k]

        # Calculate ranges
        y = [(minimums[idx], maximums[idx]) for idx in range(self.c['M'])]
        y_lines = [(0, minimums[idx]) for idx in range(self.c['M'])]

        # Plot bounds
        self.ax.scatter(range(self.c['M']), minimums, c="black", marker="_", linewidth=2, zorder=1)
        self.ax.scatter(range(self.c['M']), maximums, c="black", marker="_", linewidth=2, zorder=1)

        # Constraint Range
        self.ax.plot((range(self.c['M']), range(self.c['M'])), ([i for (i, j) in y], [j for (i, j) in y]),
                      c="black", zorder=1)

        # Line from x-axis to constraint range
        self.ax.plot((range(self.c['M']), range(self.c['M'])), ([i for (i, j) in y_lines], [j for (i, j) in y_lines]),
                      c="black", zorder=1, alpha=0.5, linestyle='--', linewidth=2)

    elif self.ip["objective"] == "Combined Quota":

        # Y axis adjustments
        self.c['y_ticks'] = [0, 0.5, 1, 1.5, 2]
        self.c['y_max'] = self.ip['y_max'] * y_top

        # Lines
        y_mins = np.repeat(1, self.c['M'])
        y_maxs = max_quota_percent
        y = [(y_mins[idx], y_maxs[idx]) for idx in range(self.c['M'])]
        y_under = [(quota_percent_filled[idx], 1) for idx in x_under]
        y_over = [(max_quota_percent[idx], quota_percent_filled[idx]) for idx in x_over]

        # Plot Bounds
        self.ax.scatter(self.c['afscs'], y_mins, c=np.repeat('black', self.c['M']), marker="_", linewidth=2, zorder=1)
        self.ax.scatter(self.c['afscs'], y_maxs, c=np.repeat('black', self.c['M']), marker="_", linewidth=2, zorder=1)

        # Plot Range Lines
        self.ax.plot((range(self.c['M']), range(self.c['M'])), ([i for (i, j) in y], [j for (i, j) in y]),
                     c='black', zorder=1)
        self.ax.plot((x_under, x_under), ([i for (i, j) in y_under], [j for (i, j) in y_under]), c='black',
                     linestyle='--', zorder=1)
        self.ax.plot((x_over, x_over), ([i for (i, j) in y_over], [j for (i, j) in y_over]), c='black',
                      linestyle='--', zorder=1)
        self.ax.plot((range(self.c['M']), range(self.c['M'])), (np.zeros(self.c['M']), np.ones(self.c['M'])),
                     c='black', linestyle='--', alpha=0.3, zorder=1)

        # Quota Line
        self.ax.axhline(y=1, color='black', linestyle='-', alpha=0.5, zorder=1)

    elif self.ip["objective"] in ["Utility", "Norm Score"] and self.ip['version'] == 'dot':

        # Fix some things for this chart (y_ticks and label)
        self.c['y_ticks'] = [0, 0.2, 0.4, 0.6, 0.8, 1]
        self.label_dict[self.ip['objective']] = afccp.globals.obj_label_dict[self.ip['objective']]

    # Set the max for the y-axis
    if self.ip['version'] in ['median_preference', 'mean_preference']:
        self.c['y_max'] = self.ip['y_max'] * np.max(max_measure)

    # Get y-label
    self.c['y_label'] = self.label_dict[self.ip['objective']]

    # Get names of Solutions
    solution_names = ', '.join(self.ip["solution_names"])

    # Create the title!
    if self.ip["title"] is None:
        self.ip['title'] = solution_names + ' ' + self.label_dict[self.ip["objective"]] + " Across Each AFSC"

    # Update the version of the data using the solution names
    self.ip['version'] = solution_names + ' ' + self.ip['version']

results_merit_chart()

This method constructs the different charts showing the "Balance Merit" objective

Source code in afccp/visualizations/charts.py
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
def results_merit_chart(self):
    """
    This method constructs the different charts showing the "Balance Merit" objective
    """

    # Shorthand
    p, vp, solution = self.parameters, self.value_parameters, self.solution
    k, quota, measure = self.c['k'], p['pgl'][self.c['J']], self.c['measure']
    colors, afscs = np.array([self.ip['bar_colors']["small_afscs"] for _ in self.c['J']]), self.c['afscs']

    if self.ip["version"] == "large_only_bar":

        # Get the title
        self.ip["title"] = "Average Merit Across Each Large AFSC"

        # Y-axis
        self.c['use_calculated_y_max'] = True
        self.c['y_max'] = self.ip['y_max']  # * np.max(measure)

        # Assign the right color to the AFSCs
        for j in range(self.c['M']):
            if 0.35 <= measure[j] <= 0.65:
                colors[j] = self.ip['bar_colors']["merit_within"]
            elif measure[j] > 0.65:
                colors[j] = self.ip['bar_colors']["merit_above"]
            else:
                colors[j] = self.ip['bar_colors']["merit_below"]

        # Add lines for the ranges
        self.ax.axhline(y=0.5, color='black', linestyle='--', alpha=0.5)

        # Bound lines
        if self.ip['add_bound_lines']:
            self.c['y_ticks'] = [0, 0.35, 0.50, 0.65, 0.80, 1]
            self.ax.axhline(y=0.35, color='blue', linestyle='-', alpha=0.5)
            self.ax.axhline(y=0.65, color='blue', linestyle='-', alpha=0.5)
        else:
            self.c['y_ticks'] = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]

        # Bar Chart
        self.ax.bar(afscs, measure, color=colors, edgecolor='black', alpha=self.ip["alpha"])

    elif self.ip["version"] == "bar":

        # Get the title
        self.ip["title"] = "Average Merit Across Each AFSC"

        # Set the max for the y-axis
        self.c['use_calculated_y_max'] = True
        self.c['y_max'] = self.ip['y_max']  # * np.max(measure)

        # Merit elements
        if self.ip['large_afsc_distinction']:
            self.c['legend_elements'] = [Patch(facecolor=self.ip['bar_colors']["small_afscs"], label='Small AFSC'),
                                         Patch(facecolor=self.ip['bar_colors']["large_afscs"], label='Large AFSC')]

        # Assign the right color to the AFSCs
        for j in range(self.c['M']):

            # Colors
            if self.ip['large_afsc_distinction']:
                if quota[j] >= 40:
                    colors[j] = self.ip['bar_colors']["large_afscs"]
                else:
                    colors[j] = self.ip['bar_colors']["small_afscs"]
            else:
                colors[j] = self.ip['bar_color']

            # Add the text
            self.ax.text(j, measure[j] + 0.013, round(measure[j], 2),
                         fontsize=self.ip["text_size"], horizontalalignment='center')

        # Add lines for the ranges
        self.ax.axhline(y=0.5, color='black', linestyle='--', alpha=0.5)

        # Bound lines
        if self.ip['add_bound_lines']:
            self.c['legend_elements'].append(mlines.Line2D([], [], color="blue", linestyle='-', label="Bound"))
            self.c['y_ticks'] = [0, 0.35, 0.50, 0.65, 0.80, 1]
            self.ax.axhline(y=0.35, color='blue', linestyle='-', alpha=0.5)
            self.ax.axhline(y=0.65, color='blue', linestyle='-', alpha=0.5)
        else:
            self.c['y_ticks'] = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]

        # Bar Chart
        self.ax.bar(afscs, measure, color=colors, edgecolor='black', alpha=self.ip["alpha"])

    elif self.ip["version"] == "quantity_bar_gradient":

        # Get the title and label
        self.ip["title"] = "Cadet Merit Breakdown Across Each AFSC"
        self.c['y_label'] = "Number of Cadets"

        # Calculate y-axis attributes
        self.determine_y_max_and_y_ticks()

        # Build the gradient chart
        self.construct_gradient_chart(parameter_to_use='merit')

    else:  # quantity_bar_proportion  (Quartiles in this case)

        # Update the title
        self.ip["title"] = "Cadet Quartiles Across Each AFSC"
        self.c['y_label'] = "Number of Cadets"

        # Legend
        self.c['legend_elements'] = [Patch(facecolor=self.ip['bar_colors']["quartile_1"], label='1st Quartile'),
                                     Patch(facecolor=self.ip['bar_colors']["quartile_2"], label='2nd Quartile'),
                                     Patch(facecolor=self.ip['bar_colors']["quartile_3"], label='3rd Quartile'),
                                     Patch(facecolor=self.ip['bar_colors']["quartile_4"], label='4th Quartile')]

        # Calculate y-axis attributes
        self.determine_y_max_and_y_ticks()

        percentile_dict = {1: (0.75, 1), 2: (0.5, 0.75), 3: (0.25, 0.5), 4: (0, 0.25)}
        for index, j in enumerate(self.c['J']):
            cadets = np.where(self.solution['j_array'] == j)[0]
            merit = p["merit"][cadets]

            # Loop through each quartile
            count_sum = 0
            for q in [4, 3, 2, 1]:
                lb, ub = percentile_dict[q][0], percentile_dict[q][1]
                count = len(np.where((merit <= ub) & (merit > lb))[0])
                self.ax.bar([index], count, bottom=count_sum,
                            color=self.ip['bar_colors']["quartile_" + str(q)], zorder=2)
                count_sum += count

                # Put a number on the bar
                if count >= 10:
                    if q == 1:
                        c = "white"
                    else:
                        c = "black"
                    self.ax.text(index, (count_sum - count / 2 - 2), int(count), color=c,
                                 zorder=3, fontsize=self.ip["bar_text_size"], horizontalalignment='center')

            # Add the text and an outline
            self.ax.text(index, self.c['total_count'][index] + self.ip['bar_text_offset'], int(self.c['total_count'][index]),
                         fontsize=self.ip["text_size"], horizontalalignment='center')
            self.ax.bar([index], self.c['total_count'][index], color="black", zorder=1, edgecolor="black")

results_demographic_chart()

Chart to visualize the demographics of the solution

Source code in afccp/visualizations/charts.py
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
def results_demographic_chart(self):
    """
    Chart to visualize the demographics of the solution
    """

    # Shorthand
    p, vp, solution = self.parameters, self.value_parameters, self.solution
    k, quota, measure = self.c['k'], p['pgl'][self.c['J']], self.c['measure']
    colors, afscs = np.array([self.ip['bar_colors']["small_afscs"] for _ in self.c['J']]), self.c['afscs']

    # Demographic Proportion elements
    prop_dict = {"USAFA Proportion": "usafa_proportion", "Male": "male_proportion",
                 "Minority": "minority_proportion"}
    legend_dict = {"USAFA Proportion": "USAFA Proportion", "Male": "Male Proportion",
                   "Minority": "Minority Proportion"}
    up_lb = round(p[prop_dict[self.ip["objective"]]] - 0.15, 2)
    up_ub = round(p[prop_dict[self.ip["objective"]]] + 0.15, 2)
    up = round(p[prop_dict[self.ip["objective"]]], 2)

    if self.ip["version"] == "large_only_bar":

        # Get the title and filename
        self.ip["title"] = legend_dict[self.ip["objective"]] + " Across Large AFSCs"

        # Set the max for the y-axis
        self.c['use_calculated_y_max'] = True
        self.c['y_max'] = self.ip['y_max']  # * np.max(measure)
        self.c['y_ticks'] = [0, up_lb, up, up_ub, 1]

        # Legend elements
        self.c['legend_elements'] = [
            Patch(facecolor=self.ip['bar_colors']["large_within"], label=str(up_lb) + ' < ' + legend_dict[
                self.ip["objective"]] + ' < ' + str(up_ub)), Patch(facecolor=self.ip['bar_colors']["large_else"],
                                                                   label='Otherwise')]

        # Assign the right color to the AFSCs
        for j in range(self.c['M']):
            if up_lb <= measure[j] <= up_ub:
                colors[j] = self.ip['bar_colors']["large_within"]
            else:
                colors[j] = self.ip['bar_colors']["large_else"]

        # Add lines for the ranges
        self.ax.axhline(y=up, color='black', linestyle='--', alpha=0.5)
        self.ax.axhline(y=up_lb, color='blue', linestyle='-', alpha=0.5)
        self.ax.axhline(y=up_ub, color='blue', linestyle='-', alpha=0.5)

        # Bar Chart
        self.ax.bar(afscs, measure, color=colors, edgecolor='black', alpha=self.ip["alpha"])

    elif self.ip["version"] == "bar":

        # Get the title and filename
        self.ip["title"] = legend_dict[self.ip["objective"]] + " Across Each AFSC"

        # Y-axis
        self.c['use_calculated_y_max'] = True
        self.c['y_max'] = self.ip['y_max']  # * np.max(measure)
        self.c['y_ticks'] = [0, up_lb, up, up_ub, 1]

        # Legend elements
        self.c['legend_elements'] = [Patch(facecolor=self.ip['bar_colors']["small_afscs"], label='Small AFSC'),
                                     Patch(facecolor=self.ip['bar_colors']["large_afscs"], label='Large AFSC'),
                                     mlines.Line2D([], [], color="blue", linestyle='-', label="Bound")]

        # Assign the right color to the AFSCs
        for j in range(self.c['M']):
            if quota[j] >= 40:
                colors[j] = self.ip['bar_colors']["large_afscs"]
            else:
                colors[j] = self.ip['bar_colors']["small_afscs"]

            # Add the text
            self.ax.text(j, measure[j] + 0.013, round(measure[j], 2),
                         fontsize=self.ip["text_size"], horizontalalignment='center')

        # Add lines for the ranges
        self.ax.axhline(y=up, color='black', linestyle='--', alpha=0.5)
        self.ax.axhline(y=up_lb, color='blue', linestyle='-', alpha=0.5)
        self.ax.axhline(y=up_ub, color='blue', linestyle='-', alpha=0.5)

        # Bar Chart
        self.ax.bar(afscs, measure, color=colors, edgecolor='black', alpha=self.ip["alpha"])

    elif self.ip["version"] == "preference_chart":
        self.c['y_label'] = "Number of Cadets"

        # Objective specific components
        if self.ip["objective"] == "USAFA Proportion":

            # Get the title
            self.ip["title"] = "USAFA/ROTC 7+ Choice Across Each AFSC"
            classes = ["USAFA", "ROTC"]

        elif self.ip["objective"] == "Male":

            # Get the title
            self.ip["title"] = "Male/Female 7+ Choice Across Each AFSC"
            classes = ["Male", "Female"]

        else:  # Minority

            # Get the title
            self.ip["title"] = "Minority/Non-Minority 7+ Choice Across Each AFSC"
            classes = ["Minority", "Non-Minority"]

        # Calculate y-axis attributes
        self.determine_y_max_and_y_ticks()

        # Categories! (Volunteers/Non-Volunteers)
        categories = ["Top 6 Choices", "7+ Choice"]

        # Get the counts for each category and class
        counts = {cls: {cat: np.zeros(self.c['M']) for cat in categories} for cls in classes}
        dem = classes[0].lower()  # reference demographic (male, usafa, minority, etc.)
        for index, afsc in enumerate(afscs):
            j = np.where(p["afscs"] == afsc)[0][0]
            cadets_assigned = np.where(self.solution['j_array'] == j)[0]
            cadets_with_demographic = np.where(p[dem] == 1)[0]
            cadets_class = {classes[0]: np.intersect1d(cadets_assigned, cadets_with_demographic),
                            classes[1]: np.array([cadet for cadet in cadets_assigned if
                                                  cadet not in cadets_with_demographic])}

            # Determine volunteer status
            if categories == ["Top 6 Choices", "7+ Choice"]:
                cadets_with_category = np.where(p['c_pref_matrix'][:, j] < 7)[0]
                cadets_cat = {"Top 6 Choices": np.intersect1d(cadets_assigned, cadets_with_category),
                              "7+ Choice": np.array(
                                  [cadet for cadet in cadets_assigned if cadet not in cadets_with_category])}

            # Loop through each demographic
            for cls in classes:
                for cat in categories:
                    counts[cls][cat][index] = len(np.intersect1d(cadets_class[cls], cadets_cat[cat]))

        # Legend
        self.c['legend_elements'] = [Patch(facecolor=self.ip['bar_colors'][cls.lower()],
                                           label=cls, edgecolor='black') for cls in classes]
        self.c['legend_elements'].append(
            Patch(facecolor=self.ip['bar_colors']["7+ Choice"], label="7+ Choice"))

        # Loop through each AFSC to plot the bars
        for index, afsc in enumerate(afscs):

            # Plot the AFOCD bars
            count_sum = 0
            for cls in classes[::-1]:
                for cat in categories[::-1]:

                    if cat == "Top 6 Choices":
                        color = self.ip["bar_colors"][cls.lower()]
                    else:
                        color = self.ip['bar_colors'][cat]

                    # Plot the bars
                    count = counts[cls][cat][index]
                    self.ax.bar([index], count, bottom=count_sum, edgecolor="black", color=color)
                    count_sum += count

                    # Put a number on the bar
                    if count >= 10:

                        if cls in ["Male", "USAFA", "Minority"]:
                            color = "white"
                        else:
                            color = "black"
                        self.ax.text(index, (count_sum - count / 2 - 2), int(count), color=color,
                                     zorder=2, fontsize=self.ip["bar_text_size"], horizontalalignment='center')

            # Add the text
            self.ax.text(index, self.c['total_count'][index] + self.ip['bar_text_offset'], int(self.c['total_count'][index]),
                         fontsize=self.ip["text_size"], horizontalalignment='center')

    else:  # Sorted Sized Bar Chart
        self.c['y_label'] = "Number of Cadets"

        # Objective specific components
        if self.ip["objective"] == "USAFA Proportion":
            self.ip["title"] = "Source of Commissioning Breakdown Across Each AFSC"
            class_1_color = self.ip['bar_colors']["usafa"]
            class_2_color = self.ip['bar_colors']["rotc"]

            # Legend
            self.c['legend_elements'] = [Patch(facecolor=class_1_color, label='USAFA'),
                                         Patch(facecolor=class_2_color, label='ROTC')]

        elif self.ip["objective"] == "Minority":
            self.ip["title"] = "Minority/Non-Minority Breakdown Across Each AFSC"
            class_1_color = self.ip['bar_colors']["minority"]
            class_2_color = self.ip['bar_colors']["non-minority"]

            # Legend
            self.c['legend_elements'] = [Patch(facecolor=class_1_color, label='Minority'),
                                         Patch(facecolor=class_2_color, label='Non-Minority')]

        else:
            self.ip["title"] = "Gender Breakdown Across Each AFSC"
            class_1_color = self.ip['bar_colors']["male"]
            class_2_color = self.ip['bar_colors']["female"]

            # Legend
            self.c['legend_elements'] = [Patch(facecolor=class_1_color, label='Male'),
                                         Patch(facecolor=class_2_color, label='Female')]

        # Calculate y-axis attributes
        self.determine_y_max_and_y_ticks()

        # Get "class" objective measures (number of cadets with demographic)
        class_1 = measure * self.c['total_count']
        class_2 = (1 - measure) * self.c['total_count']
        self.ax.bar(afscs, class_2, color=class_2_color, zorder=2, edgecolor="black")
        self.ax.bar(afscs, class_1, bottom=class_2, color=class_1_color, zorder=2, edgecolor="black")
        for j, afsc in enumerate(afscs):
            if class_2[j] >= 10:
                self.ax.text(j, class_2[j] / 2, int(class_2[j]), color="black",
                             zorder=3, fontsize=self.ip["bar_text_size"], horizontalalignment='center')
            if class_1[j] >= 10:
                self.ax.text(j, class_2[j] + class_1[j] / 2, int(class_1[j]), color="white", zorder=3,
                             fontsize=self.ip["bar_text_size"], horizontalalignment='center')

            # Add the text and an outline
            self.ax.text(j, self.c['total_count'][j] + self.ip['bar_text_offset'], round(measure[j], 2), fontsize=self.ip["text_size"],
                         horizontalalignment='center')

results_demographic_proportion_chart()

Chart to visualize the demographics of the solution across each AFSC

Source code in afccp/visualizations/charts.py
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
def results_demographic_proportion_chart(self):
    """
    Chart to visualize the demographics of the solution across each AFSC
    """

    # Shorthand
    p, vp, solution = self.parameters, self.value_parameters, self.solution

    # Category Dictionary
    category_dict = {"Race Chart": p['race_categories'], 'Ethnicity Chart': p['ethnicity_categories'],
                     'Gender Chart': ['Male', 'Female'], 'SOC Chart': ['USAFA', 'ROTC']}
    title_dict = {"Race Chart": 'Racial Demographics Across Each AFSC',
                  'Ethnicity Chart': 'Ethnicity Demographics Across Each AFSC',
                  'Gender Chart': 'Gender Breakdown Across Each AFSC',
                  'SOC Chart': 'Source of Commissioning Breakdown Across Each AFSC'}
    afsc_num_dict = {"Race Chart": "simpson_index", "Ethnicity Chart": "simpson_index_eth",
                     "Gender Chart": "male_proportion_afscs", "SOC Chart": "usafa_proportion_afscs"}
    baseline_dict = {"Gender Chart": "male_proportion", "SOC Chart": "usafa_proportion",
                     "Race Chart": "baseline_simpson_index", "Ethnicity Chart": "baseline_simpson_index_eth"}

    # Proportion Chart
    if '_proportion' in self.ip['version']:
        proportion_chart = True
        version = self.ip['version'][:-11]
    else:
        proportion_chart = False
        version = self.ip['version']

    # Extract the specific information for this chart from the dictionaries above
    self.ip['title'] = title_dict[version]
    categories = category_dict[version]
    afsc_num_dict_s = afsc_num_dict[version]
    baseline_p = baseline_dict[version]

    # Legend elements
    self.c['legend_elements'] = []
    for cat in categories[::-1]:  # Flip the legend
        color = self.ip['bar_colors'][cat]
        self.c['legend_elements'].append(Patch(facecolor=color, label=cat, edgecolor='black'))

    # Calculate y-axis attributes
    if proportion_chart:

        # Get y axis characteristics
        self.c['use_calculated_y_max'] = True
        self.c['y_ticks'] = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
        self.c['y_label'] = "Proportion of Cadets"
        self.c['y_max'] *= 1.03  # expand it a little
        self.ip['legend_size'] = self.ip['proportion_legend_size']  # Change the size of the legend
        self.ip['ncol'] = 20  # Adjust number of columns for legend (Arbitrarily large number for horizontal legend)
        self.ip['text_bar_threshold'] = self.ip['proportion_text_bar_threshold']  # Adjust this threshold

        # Baseline
        if len(categories) == 2:
            self.c['legend_elements'].append(mlines.Line2D([], [], color="black", linestyle='--', label="Baseline"))
            self.ax.axhline(y=p[baseline_p], color='black', linestyle='--', alpha=1, zorder=4)
            self.c['y_ticks'] = [0, round(p[baseline_p], 2), 1]
    else:
        self.determine_y_max_and_y_ticks()
        self.c['y_label'] = "Number of Cadets"

    # Loop through each category and AFSC pair
    quantities, proportions = {}, {}
    for cat in categories:
        quantities[cat], proportions[cat] = np.zeros(self.c['M']), np.zeros(self.c['M'])
        for idx, j in enumerate(self.c['J']):
            cadets = np.intersect1d(p['I^' + cat], solution['cadets_assigned'][j])

            # Load metrics
            quantities[cat][idx] = int(len(cadets))
            proportions[cat][idx] = len(cadets) / len(solution['cadets_assigned'][j])

    # Loop through each AFSC to add the text above the bars
    for idx, j in enumerate(self.c['J']):

        # Get the text for the top of the bar
        txt = str(solution[afsc_num_dict_s][j])
        if txt[0] == '0' and txt != '0.0':
            txt = txt[1:]
        elif txt == 'nan':
            txt = ''

        # Add the text
        if proportion_chart:
            self.ax.text(idx, 1.005, txt, verticalalignment='bottom', fontsize=self.ip["text_size"],
                         horizontalalignment='center')
        else:
            self.ax.text(idx, solution['count'][j] + self.ip['bar_text_offset'], txt, verticalalignment='bottom',
                         fontsize=self.ip["text_size"], horizontalalignment='center')

    # Plot the data
    totals = np.zeros(self.c['M'])
    for cat in quantities:
        color = self.ip['bar_colors'][cat]

        if proportion_chart:
            self.ax.bar(range(self.c['M']), proportions[cat], bottom=totals, color=color, zorder=2,
                        edgecolor='black')
            totals += proportions[cat]
        else:
            self.ax.bar(range(self.c['M']), quantities[cat], bottom=totals, color=color, zorder=2,
                        edgecolor='black')
            totals += quantities[cat]

        # If it's a dark color, change text color to white
        if 'Black' in cat or "Male" in cat:
            text_color = 'white'
        else:
            text_color = 'black'

        # Put a number on the bar
        for idx, j in enumerate(self.c['J']):
            if proportion_chart:
                if proportions[cat][idx] >= self.ip['text_bar_threshold'] / max(solution['count']):

                    # Rotate triple digit text
                    if quantities[cat][idx] >= 100:
                        rotation = 90
                    else:
                        rotation = 0

                    # Place the text
                    self.ax.text(idx, (totals[idx] - proportions[cat][idx] / 2), int(quantities[cat][idx]),
                                 color=text_color, zorder=2, fontsize=self.ip["text_size"],
                                 horizontalalignment='center', verticalalignment='center', rotation=rotation)
            else:
                if proportions[cat][idx] >= self.ip['text_bar_threshold'] / max(solution['count']):

                    # Place the text
                    self.ax.text(idx, (totals[idx] - quantities[cat][idx] / 2), int(quantities[cat][idx]),
                                 color=text_color, zorder=2, fontsize=self.ip["text_size"],
                                 horizontalalignment='center', verticalalignment='center')

results_degree_tier_chart()

Builds the degree tier results chart

Source code in afccp/visualizations/charts.py
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
def results_degree_tier_chart(self):
    """
    Builds the degree tier results chart
    """

    # Shorthand
    p, vp, solution = self.parameters, self.value_parameters, self.solution
    k, quota, measure = self.c['k'], p['pgl'][self.c['J']], self.c['measure']
    colors, afscs = np.array([self.ip['bar_colors']["small_afscs"] for _ in self.c['J']]), self.c['afscs']

    # Get the title
    self.ip["title"] = self.ip["objective"] + " Proportion Across Each AFSC"

    # Set the max for the y-axis
    self.c['use_calculated_y_max'] = True
    self.c['y_max'] = self.ip['y_max']  # * np.max(measure)

    minimums = np.zeros(self.c['M'])
    maximums = np.zeros(self.c['M'])
    x_under = []
    x_over = []
    x_within = []

    # Assign the right color to the AFSCs
    for index, j in enumerate(self.c['J']):
        if "Increasing" in vp["value_functions"][j, k]:
            minimums[index] = vp['objective_target'][j, k]
            maximums[index] = 1
        else:
            minimums[index] = 0
            maximums[index] = vp['objective_target'][j, k]

        if minimums[index] <= measure[index] <= maximums[index]:
            colors[index] = "blue"
            x_within.append(index)
        else:
            colors[index] = "red"
            if measure[index] < minimums[index]:
                x_under.append(index)
            else:
                x_over.append(index)

    # Plot points
    self.ax.scatter(afscs, measure, c=colors, linewidths=4, s=self.ip["dot_size"], zorder=3)

    # Calculate ranges
    y_within = [(minimums[j], maximums[j]) for j in x_within]
    y_under_ranges = [(minimums[j], maximums[j]) for j in x_under]
    y_over_ranges = [(minimums[j], maximums[j]) for j in x_over]
    y_under = [(measure[j], minimums[j]) for j in x_under]
    y_over = [(maximums[j], measure[j]) for j in x_over]

    # Plot bounds
    self.ax.scatter(afscs, minimums, c="black", marker="_", linewidth=2)
    self.ax.scatter(afscs, maximums, c="black", marker="_", linewidth=2)

    # Plot Ranges
    self.ax.plot((x_within, x_within), ([i for (i, j) in y_within], [j for (i, j) in y_within]),
                 c="black")
    self.ax.plot((x_under, x_under), ([i for (i, j) in y_under_ranges], [j for (i, j) in y_under_ranges]),
                 c="black")
    self.ax.plot((x_over, x_over),([i for (i, j) in y_over_ranges], [j for (i, j) in y_over_ranges]), c="black")

    # How far off
    self.ax.plot((x_under, x_under), ([i for (i, j) in y_under], [j for (i, j) in y_under]), c='red', linestyle='--')
    self.ax.plot((x_over, x_over), ([i for (i, j) in y_over], [j for (i, j) in y_over]), c='red', linestyle='--')

results_quota_chart()

This method produces the "Combined Quota" chart for each AFSC

Source code in afccp/visualizations/charts.py
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
def results_quota_chart(self):
    """
    This method produces the "Combined Quota" chart for each AFSC
    """

    # Shorthand
    p, vp, solution = self.parameters, self.value_parameters, self.solution
    k, quota, measure = self.c['k'], p['pgl'][self.c['J']], self.c['measure']
    colors, afscs = np.array([self.ip['bar_colors']["small_afscs"] for _ in self.c['J']]), self.c['afscs']

    if self.ip["version"] == "dot":

        # Get the title and label
        self.ip["title"] = "Percent of PGL Target Met Across Each AFSC"
        self.c['y_label'] = "Percent of PGL Target Met"  # Manual change from objective label dictionary

        # Set the max for the y-axis
        self.c['use_calculated_y_max'] = True
        self.c['y_ticks'] = [0, 0.5, 1, 1.5, 2]

        # Degree Tier elements
        x_under = []
        x_over = []
        x_within = []
        quota_percent_filled = np.zeros(self.c['M'])
        max_quota_percent = np.zeros(self.c['M'])

        # Assign the right color to the AFSCs
        for index, j in enumerate(self.c['J']):

            # Get bounds
            value_list = vp['objective_value_min'][j, k].split(",")
            max_measure = float(value_list[1].strip())
            if quota[index] > measure[index]:
                colors[index] = "red"
                x_under.append(index)
            elif quota[index] <= measure[index] <= max_measure:
                colors[index] = "blue"
                x_within.append(index)
            else:
                colors[index] = "orange"
                x_over.append(index)

            quota_percent_filled[index] = measure[index] / quota[index]
            max_quota_percent[index] = max_measure / quota[index]

        # Plot points
        self.ax.scatter(afscs, quota_percent_filled, c=colors, linewidths=4, s=self.ip["dot_size"], zorder=3)

        # Set the max for the y-axis
        self.c['y_max'] = self.ip['y_max'] * np.max(quota_percent_filled)

        # Lines
        y_mins = np.repeat(1, self.c['M'])
        y_maxs = max_quota_percent
        y = [(y_mins[j], y_maxs[j]) for j in range(self.c['M'])]
        y_under = [(quota_percent_filled[j], 1) for j in x_under]
        y_over = [(max_quota_percent[j], quota_percent_filled[j]) for j in x_over]

        # Plot Bounds
        self.ax.scatter(afscs, y_mins, c=np.repeat('blue', self.c['M']), marker="_", linewidth=2)
        self.ax.scatter(afscs, y_maxs, c=np.repeat('blue', self.c['M']), marker="_", linewidth=2)

        # Plot Range Lines
        self.ax.plot((np.arange(self.c['M']), np.arange(self.c['M'])), ([i for (i, j) in y], [j for (i, j) in y]),
                     c='blue')
        self.ax.plot((x_under, x_under), ([i for (i, j) in y_under], [j for (i, j) in y_under]), c='red',
                linestyle='--')
        self.ax.plot((x_over, x_over), ([i for (i, j) in y_over], [j for (i, j) in y_over]), c='orange',
                linestyle='--')
        self.ax.plot((np.arange(self.c['M']), np.arange(self.c['M'])), (np.zeros(self.c['M']), np.ones(self.c['M'])),
                     c='black', linestyle='--', alpha=0.3)

        # Quota Line
        self.ax.axhline(y=1, color='black', linestyle='-', alpha=0.5)

        # Put quota text
        y_top = round(max(quota_percent_filled))
        y_spacing = (y_top / 80)
        for j in range(self.c['M']):
            if int(measure[j]) >= 100:
                self.ax.text(j, quota_percent_filled[j] + 1.4 * y_spacing, int(measure[j]),
                             fontsize=self.ip["xaxis_tick_size"], multialignment='right',
                             horizontalalignment='center')
            elif int(measure[j]) >= 10:
                self.ax.text(j, quota_percent_filled[j] + y_spacing, int(measure[j]),
                             fontsize=self.ip["xaxis_tick_size"], multialignment='right',
                             horizontalalignment='center')
            else:
                self.ax.text(j, quota_percent_filled[j] + y_spacing, int(measure[j]),
                             fontsize=self.ip["xaxis_tick_size"], multialignment='right',
                             horizontalalignment='center')

    else:  # quantity_bar

        # Get the title and label
        self.ip["title"] = "Number of Cadets Assigned to Each AFSC against PGL"
        self.c['y_label'] = self.label_dict[self.ip["objective"]]

        # Calculate y-axis attributes
        self.determine_y_max_and_y_ticks()

        # Legend
        self.c['legend_elements'] = [Patch(facecolor=self.ip['bar_colors']["pgl"], label='PGL Target',
                                           edgecolor="black"),
                                     Patch(facecolor=self.ip['bar_colors']["surplus"],
                                           label='Cadets Exceeding PGL Target', edgecolor="black"),
                                     Patch(facecolor=self.ip['bar_colors']["failed_pgl"], label='PGL Target Not Met',
                                           edgecolor="black")]

        # Add the text and quota lines
        for j in range(self.c['M']):

            # Add the text
            self.ax.text(j, measure[j] + self.ip['bar_text_offset'], int(measure[j]),
                         fontsize=self.ip["text_size"], horizontalalignment='center')

            # Determine which category the AFSC falls into
            line_color = "black"
            if measure[j] > quota[j]:
                self.ax.bar([j], quota[j], color=self.ip['bar_colors']["pgl"], edgecolor="black")
                self.ax.bar([j], measure[j] - quota[j], bottom=quota[j],
                            color=self.ip['bar_colors']["surplus"], edgecolor="black")
            elif measure[j] < quota[j]:
                self.ax.bar([j], measure[j], color=self.ip['bar_colors']["failed_pgl"], edgecolor="black")
                self.ax.plot((j - 0.4, j - 0.4), (quota[j], measure[j]),
                        color=self.ip['bar_colors']["failed_pgl"], linestyle="--", zorder=2)
                self.ax.plot((j + 0.4, j + 0.4), (quota[j], measure[j]),
                        color=self.ip['bar_colors']["failed_pgl"], linestyle="--", zorder=2)
                line_color = self.ip['bar_colors']["failed_pgl"]
            else:
                self.ax.bar([j], measure[j], color=self.ip['bar_colors']["pgl"], edgecolor="black")

            # Add the PGL lines
            self.ax.plot((j - 0.4, j + 0.4), (quota[j], quota[j]), color=line_color, linestyle="-", zorder=2)

results_preference_chart()

This method builds the charts for cadet/AFSC preferences

Source code in afccp/visualizations/charts.py
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
def results_preference_chart(self):
    """
    This method builds the charts for cadet/AFSC preferences
    """

    # Shorthand
    p, vp, solution = self.parameters, self.value_parameters, self.solution
    k, quota, measure = self.c['k'], p['pgl'][self.c['J']], self.c['measure']
    colors, afscs = np.array([self.ip['bar_colors']["small_afscs"] for _ in self.c['J']]), self.c['afscs']

    if self.ip["version"] in ["quantity_bar_proportion", "quantity_bar_choice"]:

        # Counts
        counts = {"bottom_choices": np.zeros(self.c['M']), "mid_choices": np.zeros(self.c['M']),
                  "top_choices": np.zeros(self.c['M'])}

        # Colors
        colors = self.ip['bar_colors']

        if self.ip["objective"] == "Utility":

            # Get the title
            self.ip["title"] = "Cadet Preference Breakdown Across Each AFSC"

            if self.ip["version"] == 'quantity_bar_choice':

                # Legend (and colors)
                self.c['legend_elements'] = []
                self.ip['legend_size'] = int(self.ip['legend_size'] * 0.7)
                colors = {}
                for choice in range(p['P'])[:10]:
                    colors[str(choice + 1)] = self.ip['choice_colors'][choice + 1]
                    self.c['legend_elements'].append(Patch(facecolor=colors[str(choice + 1)],
                                                           label=str(choice + 1), edgecolor='black'))
                colors['All Others'] = self.ip['all_other_choice_colors']
                self.c['legend_elements'].append(Patch(facecolor=colors['All Others'],
                                                       label='All Others', edgecolor='black'))

                # Add the title of the legend
                self.c['legend_title'] = 'Cadet Choice'

                # Counts
                counts = {"All Others": np.zeros(self.c['M'])}
                for choice in range(p['P'])[:10][::-1]:
                    counts[str(choice + 1)] = np.zeros(self.c['M'])
                for index, j in enumerate(self.c['J']):
                    afsc = p['afscs'][j]
                    total = 0
                    for choice in range(p['P'])[:10]:
                        counts[str(choice + 1)][index] = solution["choice_counts"]["TOTAL"][afsc][choice]
                        total += counts[str(choice + 1)][index]
                    counts['All Others'][index] = self.c['total_count'][index] - total

            else:

                # Legend
                self.c['legend_elements'] = [Patch(facecolor=self.ip['bar_colors']["top_choices"],
                                                   label='Top 3 Choices', edgecolor='black'),
                                             Patch(facecolor=self.ip['bar_colors']["mid_choices"],
                                                   label='Next 3 Choices', edgecolor='black'),
                                             Patch(facecolor=self.ip['bar_colors']["bottom_choices"],
                                                   label='All Others', edgecolor='black')]

                # Cadet Choice Counts
                for index, j in enumerate(self.c['J']):
                    counts['top_choices'][index] = solution['choice_counts']['TOTAL']['Top 3'][j]
                    counts['mid_choices'][index] = solution['choice_counts']['TOTAL']['Next 3'][j]
                    counts['bottom_choices'][index] = solution['choice_counts']['TOTAL']['All Others'][j]

        else:

            # Get the title
            self.ip["title"] = "AFSC Preference Breakdown"

            if self.ip["version"] == 'quantity_bar_choice':

                # Legend (and colors)
                self.c['legend_elements'] = []
                self.ip['legend_size'] = int(self.ip['legend_size'] * 0.7)
                colors = {}
                cat_choice_dict = {'90-100%': 1, '80-89%': 2, '70-79%': 3, '60-69%': 4, '50-59%': 5,
                                   '40-49%': 6, '30-39%': 7, '20-29%': 8, '10-19%': 9, '0-10%': 10}
                for cat, choice in cat_choice_dict.items():
                    colors[cat] = self.ip['choice_colors'][choice]
                    self.c['legend_elements'].append(Patch(facecolor=colors[cat],
                                                           label=cat, edgecolor='black'))

                # Add the title of the legend
                self.c['legend_title'] = 'AFSC Rank\nPercentile'

                # Counts
                counts = {}
                cat_dem_dict = {'90-100%': 0.9, '80-89%': 0.8, '70-79%': 0.7, '60-69%': 0.6, '50-59%': 0.5,
                                '40-49%': 0.4, '30-39%': 0.3, '20-29%': 0.2, '10-19%': 0.1, '0-10%': 0}
                categories = list(cat_dem_dict.keys())
                for cat in categories[::-1]:
                    counts[cat] = np.zeros(self.c['M'])
                for index, j in enumerate(self.c['J']):
                    afsc = p['afscs'][j]
                    total = 0
                    for cat, dem in cat_dem_dict.items():
                        counts[cat][index] = solution["afsc_choice_counts"][afsc][cat]
                        total += counts[cat][index]

            else:

                # Legend
                self.c['legend_elements'] = [Patch(facecolor=self.ip['bar_colors']["top_choices"], label='Top Third',
                                                   edgecolor='black'),
                                             Patch(facecolor=self.ip['bar_colors']["mid_choices"], label='Middle Third',
                                                   edgecolor='black'),
                                             Patch(facecolor=self.ip['bar_colors']["bottom_choices"],
                                                   label='Bottom Third', edgecolor='black')]

                # AFSC Choice Counts
                for i, j in enumerate(self.solution['j_array']):
                    if j in self.c['J']:
                        index = np.where(self.c['J'] == j)[0][0]
                        if p["afsc_utility"][i, j] < 1 / 3:
                            counts["bottom_choices"][index] += 1
                        elif p["afsc_utility"][i, j] < 2 / 3:
                            counts["mid_choices"][index] += 1
                        else:
                            counts["top_choices"][index] += 1

        # Set label
        self.c['y_label'] = "Number of Cadets"

        # Calculate y-axis attributes
        self.determine_y_max_and_y_ticks()

        # Loop through each AFSC to plot the bars
        for index, j in enumerate(self.c["J"]):

            count_sum = 0
            for cat in counts:
                text_color = "black"

                # Plot the bars
                count = counts[cat][index]
                self.ax.bar([index], count, bottom=count_sum, edgecolor="black", color=colors[cat])
                count_sum += count

                # Put a number on the bar
                if count >= self.ip['text_bar_threshold']:
                    self.ax.text(index, (count_sum - count / 2 - 2), int(count), color=text_color, zorder=2,
                                 fontsize=self.ip["bar_text_size"], horizontalalignment='center')

            # Add the text
            self.ax.text(index, self.c['total_count'][index] + self.ip['bar_text_offset'], int(self.c['total_count'][index]),
                         fontsize=self.ip["text_size"], horizontalalignment='center')

    elif self.ip["version"] in ["dot", "bar"]:

        # Get the title
        self.ip["title"] = self.label_dict[self.ip["objective"]] + " Across Each AFSC"

        # Average Utility Chart (simple)
        self.c['y_ticks'] = [0, 0.2, 0.4, 0.6, 0.8, 1]
        self.c['use_calculated_y_max'] = True
        self.ax.bar(afscs, measure, color="black", edgecolor='black', alpha=self.ip["alpha"])

        for j in range(self.c['M']):

            # Add the text
            self.ax.text(j, measure[j] + 0.013, round(measure[j], 2), fontsize=self.ip["text_size"],
                         horizontalalignment='center')

    elif self.ip["version"] == "quantity_bar_gradient":

        # Get the title and label
        self.ip["title"] = "Cadet Satisfaction Breakdown Across Each AFSC"
        self.c['y_label'] = 'Number of Cadets'

        # Calculate y-axis attributes
        self.determine_y_max_and_y_ticks()

        # Build the gradient chart
        self.construct_gradient_chart(parameter_to_use='cadet_utility')

results_norm_score_chart()

This method constructs the different charts showing the "Norm Score" objective

Source code in afccp/visualizations/charts.py
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
def results_norm_score_chart(self):
    """
    This method constructs the different charts showing the "Norm Score" objective
    """

    # Shorthand
    p, vp, solution = self.parameters, self.value_parameters, self.solution
    k, quota, measure = self.c['k'], p['pgl'][self.c['J']], self.c['measure']
    colors, afscs = np.array([self.ip["bar_color"] for _ in self.c['J']]), self.c['afscs']

    if self.ip["version"] == "bar":

        # Get the title and label
        self.ip["title"] = "Normalized Score Across Each AFSC"

        # Y-axis
        self.c['use_calculated_y_max'] = True
        self.c['y_max'] = self.ip['y_max']
        self.c['y_ticks'] = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]

        # Add the text
        for j in range(self.c['M']):

            # Add the text
            self.ax.text(j, measure[j] + 0.013, round(measure[j], 2),
                         fontsize=self.ip["text_size"], horizontalalignment='center')

        # Bar Chart
        self.ax.bar(afscs, measure, color=colors, edgecolor='black', alpha=self.ip["alpha"])

CadetUtilityGraph(instance)

Parameters:

Name Type Description Default
instance
required
Source code in afccp/visualizations/charts.py
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
def __init__(self, instance):
    """

    :param instance:
    """

    # Load attributes
    self.parameters = instance.parameters
    self.value_parameters, self.vp_name = instance.value_parameters, instance.vp_name
    self.ip = instance.mdl_p  # "instance plot parameters"
    self.data_name, self.data_version = instance.data_name, instance.data_version

    # Initialize the matplotlib figure/axes
    self.fig, self.ax = plt.subplots(figsize=self.ip['figsize'], facecolor=self.ip['facecolor'], tight_layout=True,
                                     dpi=self.ip['dpi'])

    # Where to save the chart
    self.path = instance.export_paths["Analysis & Results"] + "Data Charts/"

    # Shorthand
    i, p = self.ip['cadet'], self.parameters
    J = p['cadet_preferences'][i]
    afscs, M = p['afscs'][J], len(J)

    # Utility categories
    categories = ['Utility Ascribed', 'Normalized Rank', 'Not Bottom 3', 'Not Last Choice']
    legend_elements = []
    for cat in categories:
        legend_elements.append(Patch(facecolor=self.ip['bar_colors'][cat], label=cat,
                                     edgecolor='black'))

    # AFSCs the cadet is eligible for and selected (ordered appropriately)
    intersection = np.intersect1d(p['J^Selected'][i], J)
    intersection = np.array([j for j in p['cadet_preferences'][i] if j in intersection])
    num_selected = len(intersection)

    # 1, 2, 3, 4, ..., N  (Pure rankings)
    rankings = np.arange(num_selected) + 1

    # 1, 0.8, 0.6, 0.4, ..., 1 / N  (Scale rankings to range from 1 to 0)
    normalized_rankings = 1 - (rankings / np.max(rankings)) + (1 / np.max(rankings))

    # Create dictionary of normalized ordinal rankings
    norm_ord_rankings_dict = {j: normalized_rankings[index] for index, j in enumerate(intersection)}

    # A: AFSC is NOT the LAST choice
    a = np.array([(j != p['J^Last Choice'][i]) * 1 for j in J])

    # B: AFSC is NOT in the bottom 3 choices
    b = np.array([((j not in p['J^Bottom 2 Choices'][i]) and (j != p['J^Last Choice'][i])) * 1 for j in J])

    # C: AFSC was selected as a preference
    c = np.array([(j in p['J^Selected'][i]) * 1 for j in J])

    # D: AFSC was selected as a preference and has a utility assigned
    d = np.array([(p['utility'][i, j] > 0) * 1 for j in J])

    # X: Normalized ordinal ranking of the AFSC
    x = np.array([norm_ord_rankings_dict[j] if j in norm_ord_rankings_dict else 0 for j in J])

    # Y: Utility value the cadet assigned to the AFSC
    y = p['utility'][i, J]

    # # Execute the formula and load it into the cadet utility matrix
    # p['cadet_utility'][i, j] = 0.05 * a + 0.05 * b + 0.9 * (0.3 * c * x + 0.7 * d * y)

    # Plot the bars
    total = np.zeros(M)
    self.ax.bar(np.arange(M), a * 0.05, color=self.ip['bar_colors']["Not Last Choice"], edgecolor='black')
    total += a * 0.05
    self.ax.bar(np.arange(M), b * 0.05, bottom=total, color=self.ip['bar_colors']["Not Bottom 3"], edgecolor='black')
    total += b * 0.05
    self.ax.bar(np.arange(M), c * x  * 0.3 * 0.9, bottom=total, color=self.ip['bar_colors']["Normalized Rank"],
                edgecolor='black')
    total += c * x  * 0.3 * 0.9
    self.ax.bar(np.arange(M), d * y * 0.7 * 0.9, bottom=total, color=self.ip['bar_colors']["Utility Ascribed"],
                edgecolor='black')

    # Put text on the bars
    for index, j in enumerate(J):

        # Final utility above bar
        self.ax.text(index, p['cadet_utility'][i, j] + 0.005,
                     np.around(100 * p['cadet_utility'][i, j], 1).astype(str) + "%", fontsize=self.ip["bar_text_size"],
                     horizontalalignment='center')

        # Reported utility in bar
        val = y[index] * 0.7 * 0.9
        if d[index] == 1 and val > 0.02:
            y_pt = 0.1 + x[index] * 0.3 * 0.9 + val / 2
            self.ax.text(index, y_pt,
                         np.around(p['utility'][i, j], 2), fontsize=self.ip["bar_text_size"],
                         horizontalalignment='center', verticalalignment='center')

        # Normalized ranking val in bar
        val = x[index] * 0.3 * 0.9
        if c[index] == 1 and val > 0.02:
            y_pt = 0.1 + val / 2
            self.ax.text(index, y_pt,
                         np.around(norm_ord_rankings_dict[j], 2), fontsize=self.ip["bar_text_size"],
                         horizontalalignment='center', verticalalignment='center')

    # # Put text above the bar
    # self.ax.text(np.arange(M), p['cadet_utility'][i, J] + 0.02,
    #              np.around(p['cadet_utility'][i, J], 3).astype(str), fontsize=self.ip["bar_text_size"],
    #              horizontalalignment='center')

    # Display title
    self.ip['title'] = 'Cadet "' + str(i) + '" Utility Chart'
    if self.ip['display_title']:
        self.fig.suptitle(self.ip['title'], fontsize=self.ip['title_size'])

    # Labels
    self.ax.set_ylabel("Utility")
    self.ax.yaxis.label.set_size(self.ip['label_size'])
    self.ax.set_xlabel('AFSCs')
    self.ax.xaxis.label.set_size(self.ip['label_size'])

    # Color the AFSCs on the x axis
    if self.ip["color_afsc_text_by_grp"]:
        afsc_colors = [self.ip['bar_colors'][p['acc_grp'][j]] for j in p['cadet_preferences'][i]]
    else:
        afsc_colors = ["black" for _ in afscs]

    # X axis
    self.ax.tick_params(axis='x', labelsize=self.ip['afsc_tick_size'])
    self.ax.set_xticks(np.arange(M))
    self.ax.set_xticklabels(afscs, rotation=self.ip['afsc_rotation'])
    self.ax.set(xlim=(-0.8, M))

    # Unique AFSC colors potentially based on accessions group
    for index, xtick in enumerate(self.ax.get_xticklabels()):
        xtick.set_color(afsc_colors[index])

    # Y axis
    self.ax.tick_params(axis='y', labelsize=self.ip['yaxis_tick_size'])
    self.ax.set_yticks([0, 0.2, 0.4, 0.6, 0.8, 1])
    self.ax.set_yticklabels(['0%', '20%', '40%', '60%', '80%', '100%'])

    # Legend
    if self.ip["add_legend_afsc_chart"]:
        self.ax.legend(handles=legend_elements, edgecolor='black', loc=self.ip['legend_loc'],
                       fontsize=self.ip['legend_size'], ncol=self.ip['ncol'], labelspacing=1, handlelength=0.8,
                       handletextpad=0.2, borderpad=0.2, handleheight=2)

    # Save the chart
    self.ip['filename'] = self.ip['title']
    if self.ip['save']:
        self.fig.savefig(self.path + self.ip["filename"])
        print("Saved", self.ip["filename"], "Chart to " + self.path + ".")

AccessionsGroupChart(instance)

This is a class dedicated to creating "Accessions Group Charts" which are all charts that include the "accessions groups" on the x-axis alongside the basline. This is meant to condense the amount of code and increase read-ability of the various kinds of charts.

Source code in afccp/visualizations/charts.py
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
def __init__(self, instance):
    """
    This is a class dedicated to creating "Accessions Group Charts" which are all charts
    that include the "accessions groups" on the x-axis alongside the basline. This is meant to condense the amount
    of code and increase read-ability of the various kinds of charts.
    """

    # Load attributes
    self.parameters = instance.parameters
    self.value_parameters, self.vp_name = instance.value_parameters, instance.vp_name
    self.ip = instance.mdl_p  # "instance plot parameters"
    self.solution, self.solution_name = instance.solution, instance.solution_name
    self.data_name, self.data_version = instance.data_name, instance.data_version

    # Dictionaries of instance components (sets of value parameters, solutions)
    self.vp_dict, self.solutions = instance.vp_dict, instance.solutions

    # Initialize the matplotlib figure/axes
    self.fig, self.ax = plt.subplots(figsize=self.ip['figsize'], facecolor=self.ip['facecolor'], tight_layout=True,
                                     dpi=self.ip['dpi'])

    # Label dictionary for AFSC objectives
    self.label_dict = copy.deepcopy(afccp.globals.obj_label_dict)

    # Where to save the chart
    self.paths = {"Data": instance.export_paths["Analysis & Results"] + "Data Charts/",
                  "Solution": instance.export_paths["Analysis & Results"] + self.solution_name + "/",
                  "Comparison": instance.export_paths["Analysis & Results"] + "Comparison Charts/"}

    # Initialize "c" dictionary (specific chart parameters)
    self.c = {"x_labels": ["All Cadets"]}
    for acc_grp in self.parameters['afscs_acc_grp']:
        self.c['x_labels'].append(acc_grp)
    self.c['g'] = len(self.c['x_labels'])

build(chart_type='Data', printing=True)

Builds the specific chart based on what the user passes within the "instance plot parameters" (ip)

Source code in afccp/visualizations/charts.py
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
def build(self, chart_type="Data", printing=True):
    """
    Builds the specific chart based on what the user passes within the "instance plot parameters" (ip)
    """

    # Determine what kind of chart we're showing
    if chart_type == "Data":  # "Before Solution" chart
        pass

    elif chart_type == "Solution":  # Solution chart

        if 'race_categories' not in self.parameters:
            return None  # We're not doing this

        self.results_demographic_chart()

    # Put the solution name in the title if specified
    if self.ip["solution_in_title"]:
        self.ip['title'] = self.solution['name'] + ": " + self.ip['title']

    # Display title
    if self.ip['display_title']:
        self.fig.suptitle(self.ip['title'], fontsize=self.ip['title_size'])

    # Labels
    self.ax.set_ylabel(self.c["y_label"])
    self.ax.yaxis.label.set_size(self.ip['label_size_acc'])
    self.ax.set_xlabel('Accessions Group')
    self.ax.xaxis.label.set_size(self.ip['label_size_acc'])

    # Color the x-axis labels
    if self.ip["color_afsc_text_by_grp"]:
        label_colors = [self.ip['bar_colors'][grp] for grp in self.c['x_labels']]
    else:
        label_colors = ["black" for _ in self.c['x_labels']]

    # X axis
    self.ax.tick_params(axis='x', labelsize=self.ip['xaxis_tick_size'])
    self.ax.set_xticklabels(self.c['x_labels'])

    # Unique label colors potentially based on accessions group
    for index, xtick in enumerate(self.ax.get_xticklabels()):
        xtick.set_color(label_colors[index])

    # Y axis
    self.ax.tick_params(axis='y', labelsize=self.ip['yaxis_tick_size'])
    self.ax.set(ylim=(0, self.ip["y_max"] * 1.03))

    # Legend
    if self.c['legend_elements'] is not None:
        self.ax.legend(handles=self.c["legend_elements"], edgecolor='black', loc=self.ip['legend_loc'],
                       fontsize=self.ip['acc_legend_size'], ncol=self.ip['ncol'], labelspacing=1, handlelength=0.8,
                       handletextpad=0.2, borderpad=0.2, handleheight=2)

    # Get the filename
    if self.ip["filename"] is None:
        self.ip["filename"] = self.data_name + " (" + self.data_version + ") " + self.solution['name'] + \
                              " Accessions Group [" + self.ip['version'] + "] (Results).png"

    # Save the chart
    if self.ip['save']:
        self.fig.savefig(self.paths[chart_type] + self.ip["filename"])

        if printing:
            print("Saved", self.ip["filename"], "Chart to " + self.paths[chart_type] + ".")
    else:
        if printing:
            print("Created", self.ip["filename"], "Chart.")

    # Return the chart
    return self.fig

results_demographic_chart()

Displays a demographic breakdown across accessions groups

Source code in afccp/visualizations/charts.py
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
def results_demographic_chart(self):
    """
    Displays a demographic breakdown across accessions groups
    """

    # Shorthand
    p, vp, solution = self.parameters, self.value_parameters, self.solution

    # Update certain things that apply to all versions of this kind of chart
    self.c['y_label'] = 'Proportion of Cadets'

    # Category Dictionary
    category_dict = {"Race Chart": p['race_categories'], 'Ethnicity Chart': p['ethnicity_categories'],
                     'Gender Chart': ['Male', 'Female'], 'SOC Chart': ['USAFA', 'ROTC']}
    title_dict = {"Race Chart": 'Racial Demographics Across Each Accessions Group',
                  'Ethnicity Chart': 'Ethnicity Demographics Across Each Accessions Group',
                  'Gender Chart': 'Gender Breakdown Across Each Accessions Group',
                  'SOC Chart': 'Source of Commissioning Breakdown Across Each Accessions Group'}
    baseline_num_dict = {"Race Chart": "baseline_simpson_index", "Ethnicity Chart": "baseline_simpson_index_eth",
                         "Gender Chart": "male_proportion", "SOC Chart": "usafa_proportion"}
    acc_grp_num_dict = {"Race Chart": "simpson_index_", "Ethnicity Chart": "simpson_index_eth_",
                        "Gender Chart": "male_proportion_", "SOC Chart": "usafa_proportion_"}

    # Extract the specific information for this chart from the dictionaries above
    self.ip['title'] = title_dict[self.ip['version']]
    categories = category_dict[self.ip['version']]
    baseline_p = baseline_num_dict[self.ip['version']]
    acc_grp_num_dict_s = acc_grp_num_dict[self.ip['version']]

    # Legend elements
    self.c['legend_elements'] = []
    for cat in categories[::-1]:  # Flip the legend
        color = self.ip['bar_colors'][cat]
        self.c['legend_elements'].append(Patch(facecolor=color, label=cat, edgecolor='black'))

    # Baseline
    if len(categories) == 2:
        self.c['legend_elements'].append(mlines.Line2D([], [], color="black", linestyle='--', label="Baseline"))
        self.ax.axhline(y=p[baseline_p], color='black', linestyle='--', zorder=4)
        self.c['y_ticks'] = [0, round(p[baseline_p], 2), 1]

    self.ip['ncol'] = len(self.c['legend_elements'])  # Adjust number of columns for legend

    # Loop through each category and accessions group pair
    quantities, proportions = {}, {}
    for cat in categories:
        quantities[cat], proportions[cat] = np.zeros(self.c['g']), np.zeros(self.c['g'])
        for idx, grp in enumerate(self.c['x_labels']):

            # Get metrics from this category group in this accessions group
            if grp == "All Cadets":
                cadets = p['I^' + cat]

                # Load metrics
                quantities[cat][idx] = int(len(cadets))
                proportions[cat][idx] = len(cadets) / p['N']
            else:
                cadets = np.intersect1d(p['I^' + cat], solution['I^' + grp])

                # Load metrics
                quantities[cat][idx] = int(len(cadets))
                proportions[cat][idx] = len(cadets) / len(solution['I^' + grp])

    # Loop through each accession group to add the text above the bars
    for idx, grp in enumerate(self.c['x_labels']):
        if grp == "All Cadets":
            txt = str(round(p[baseline_p], 2))
        else:
            txt = str(solution[acc_grp_num_dict_s + grp])
        self.ax.text(idx, 1.005, txt, verticalalignment='bottom', fontsize=self.ip["acc_text_size"],
                     horizontalalignment='center')

    # Plot the data
    totals = np.zeros(self.c['g'])
    for cat in quantities:
        color = self.ip['bar_colors'][cat]
        self.ax.bar(self.c['x_labels'], proportions[cat], bottom=totals, color=color, zorder=2, edgecolor='black')
        totals += proportions[cat]

        # Put a number on the bar
        for idx in range(self.c['g']):
            if proportions[cat][idx] >= self.ip['acc_text_bar_threshold'] / max(solution['count']):

                # If it's a dark color, change text color to white
                if 'Black' in cat or "Male" in cat:
                    text_color = 'white'
                else:
                    text_color = 'black'

                # Place the text
                self.ax.text(idx, (totals[idx] - proportions[cat][idx] / 2), int(quantities[cat][idx]),
                             color=text_color, zorder=2, fontsize=self.ip["acc_bar_text_size"],
                             horizontalalignment='center', verticalalignment='center')

individual_weight_graph(instance)

This function creates the chart for either the individual weight function for cadets or the actual individual weights on the AFSCs

Returns:

Type Description

chart

Source code in afccp/visualizations/charts.py
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
def individual_weight_graph(instance):
    """
    This function creates the chart for either the individual weight function for cadets or the actual
    individual weights on the AFSCs
    :return: chart
    """

    # Shorthand
    p, vp, ip = instance.parameters, instance.value_parameters, instance.mdl_p

    # Initialize figure and title
    if ip["title"] is None:
        if ip["cadets_graph"]:
            title = 'Individual Weight on Cadets'
        else:
            title = 'Individual Weight on AFSCs'
    else:
        title = ip["title"]

    # Build figure
    if ip["cadets_graph"]:

        # Cadets Graph
        fig, ax = plt.subplots(figsize=ip["square_figsize"], facecolor=ip["facecolor"], dpi=ip["dpi"],
                               tight_layout=True)
        # ax.set_aspect('equal', adjustable='box')

        # Get x and y coordinates
        if 'merit_all' in p:
            x = p['merit_all']
        else:
            x = p['merit']
        y = vp['cadet_weight'] / np.max(vp['cadet_weight'])

        # Plot
        ax.scatter(x, y, color=ip["bar_color"], alpha=ip["alpha"], linewidth=3)

        # Labels
        ax.set_ylabel('Cadet Weight', fontname='Times New Roman')
        ax.yaxis.label.set_size(ip["label_size"])
        ax.set_xlabel('Percentile', fontname='Times New Roman')
        ax.xaxis.label.set_size(ip["label_size"])

        # Ticks
        # x_ticks = [0, 0.2, 0.4, 0.6, 0.8, 1]
        # ax.set_xticklabels(x_ticks, fontname='Times New Roman')
        ax.tick_params(axis='x', labelsize=ip["xaxis_tick_size"])
        ax.tick_params(axis='y', labelsize=ip["yaxis_tick_size"])

        # Margins
        ax.set(xlim=(-0.02, 1.02))
        # ax.margins(x=0)
        # ax.margins(y=0)

    else:  # AFSC Chart

        # AFSCs Graph
        fig, ax = plt.subplots(figsize=ip["figsize"], facecolor=ip["facecolor"], dpi=ip["dpi"], tight_layout=True)

        # Labels
        ax.set_ylabel('AFSC Weight')
        ax.yaxis.label.set_size(ip["label_size"])
        ax.set_xlabel('AFSCs')
        ax.xaxis.label.set_size(ip["label_size"])

        # We can skip AFSCs
        if ip["skip_afscs"]:
            tick_indices = np.arange(1, p["M"], 2).astype(int)
        else:
            tick_indices = np.arange(p["M"])

        # Plot
        afscs = p['afscs'][:p["M"]]
        ax.bar(afscs, vp['afsc_weight'], color=ip["bar_color"], alpha=ip["alpha"])

        # Ticks
        ax.set(xlim=(-0.8, p["M"]))
        ax.tick_params(axis='x', labelsize=ip["afsc_tick_size"])
        ax.set_yticks([])
        ax.set_xticklabels(afscs[tick_indices], rotation=ip["afsc_rotation"])
        ax.set_xticks(tick_indices)

    if ip["display_title"]:
        ax.set_title(title, fontsize=ip["label_size"])

    if ip["save"]:
        fig.savefig(instance.export_paths['Analysis & Results'] + 'Value Parameters/' + title + '.png',
                    bbox_inches='tight')

    return fig

afsc_multi_criteria_graph(instance, max_num=None)

This chart compares certain AFSCs in a solution according to multiple criteria

Source code in afccp/visualizations/charts.py
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
def afsc_multi_criteria_graph(instance, max_num=None):
    """
    This chart compares certain AFSCs in a solution according to multiple criteria
    """

    # Shorthand
    ip = instance.plt_p
    p = instance.parameters
    vp = instance.value_parameters

    # Create figure
    fig, ax = plt.subplots(figsize=ip['figsize'], facecolor=ip['facecolor'], tight_layout=True, dpi=ip['dpi'])

    # Get list of AFSCs we're considering
    afscs = np.array(ip["comparison_afscs"])
    used_indices = np.array([np.where(p["afscs"] == afsc)[0][0] for afsc in afscs])
    criteria = ip["comparison_criteria"]
    num_afscs = len(afscs)
    num_criteria = len(criteria)

    # Get quota
    if "pgl" in p:
        quota = p["pgl"][used_indices]
    else:
        quota = p["quota"][used_indices]

    # Need to know number of cadets assigned
    quota_k = np.where(vp["objectives"] == "Combined Quota")[0][0]
    total_count = instance.metrics["objective_measure"][used_indices, quota_k]
    full_count = instance.metrics["objective_measure"][:, quota_k]

    # Sort the AFSCs by the PGL
    if ip["sort_by_pgl"]:
        indices = np.argsort(quota)[::-1]

    # Sort the AFSCs by the number of cadets assigned
    else:
        indices = np.argsort(total_count)[::-1]

    # Re-sort the AFSCs, quota, and total count
    afscs = afscs[indices]
    quota = quota[indices]
    total_count = total_count[indices]
    indices = used_indices[indices]

    # Set the bar chart structure parameters
    label_locations = np.arange(num_afscs)
    bar_width = 0.8 / num_criteria

    # Y max
    if max_num is None:
        y_max = ip["y_max"] * max(instance.metrics["objective_measure"][:, quota_k])
    else:
        y_max = ip["y_max"] * max_num

    # Y tick marks
    if 100 <= y_max < 150:
        y_ticks = [50, 100, 150]
    elif 150 <= y_max < 200:
        y_ticks = [50, 100, 150, 200]
    elif 200 <= y_max < 250:
        y_ticks = [50, 100, 150, 200, 250]
    elif 250 <= y_max < 300:
        y_ticks = [50, 100, 150, 200, 250, 300]
    elif y_max >= 300:
        y_ticks = [50, 100, 150, 200, 250, 300, 350]
    else:
        y_ticks = [50]

    # Convert utility matrix to utility columns
    preferences, utilities_array = afccp.data.preferences.get_utility_preferences(p)

    # AFOCD
    afocd_objectives = ["Mandatory", "Desired", "Permitted"]
    afocd_k = {objective: np.where(vp["objectives"] == objective)[0][0] for objective in afocd_objectives}
    afocd_count = {objective: full_count * instance.metrics["objective_measure"][:, afocd_k[objective]]
                   for objective in afocd_objectives}
    afocd_count = {objective: afocd_count[objective][indices] for objective in afocd_objectives}  # Re-sort

    # Counts
    top_3_count = np.zeros(p["M"])
    next_3_count = np.zeros(p["M"])
    non_vol_count = np.zeros(p["M"])
    for i, j in enumerate(instance.solution):

        # Preference Counts
        afsc = p["afscs"][j]
        if afsc in preferences[i, 0:3]:
            top_3_count[j] += 1
        elif afsc in preferences[i, 3:6]:
            next_3_count[j] += 1
        else:
            non_vol_count[j] += 1

    # Re-sort preferences
    top_3_count, next_3_count = top_3_count[indices], next_3_count[indices]
    non_vol_count = non_vol_count[indices]

    # Percentile
    percentile_dict = {1: (0.75, 1), 2: (0.5, 0.75), 3: (0.25, 0.5), 4: (0, 0.25)}

    # Loop through each solution/AFSC bar
    M = len(indices)
    for index, j in enumerate(indices):
        cadets = np.where(instance.solution == j)[0]
        merit = p["merit"][cadets]
        utility = p["utility"][cadets, j]
        for c, obj in enumerate(criteria):

            if obj == "Preference":

                # Plot preference bars
                ax.bar(label_locations[index] + bar_width * c, non_vol_count[index], bar_width,
                       edgecolor='black', color=ip['bar_colors']["bottom_choices"])
                ax.bar(label_locations[index] + bar_width * c, next_3_count[index], bar_width,
                       bottom=non_vol_count[index], edgecolor='black',
                       color=ip['bar_colors']["mid_choices"])
                ax.bar(label_locations[index] + bar_width * c, top_3_count[index], bar_width,
                       bottom=non_vol_count[index] + next_3_count[index], edgecolor='black',
                       color=ip['bar_colors']["top_choices"])

            elif obj == "Merit":

                # Plot the merit gradient bars
                uq = np.unique(merit)
                count_sum = 0
                for val in uq:
                    count = len(np.where(merit == val)[0])
                    color = str(val)  # Grayscale
                    ax.bar(label_locations[index] + bar_width * c, count, bar_width, bottom=count_sum, color=color,
                           zorder=2)
                    count_sum += count

                # Add the text
                ax.text(label_locations[index] + bar_width * c, total_count[index] + 2, round(np.mean(merit), 2),
                        fontsize=ip["text_size"], horizontalalignment='center')

            elif obj == "Utility":

                # Plot the utility gradient bars
                uq = np.unique(utility)
                count_sum = 0
                for val in uq:
                    count = len(np.where(utility == val)[0])
                    color = (1 - val, 0, val)  # Blue to Red
                    ax.bar(label_locations[index] + bar_width * c, count, bar_width, bottom=count_sum, color=color,
                           zorder=2)
                    count_sum += count

                # Add the text
                ax.text(label_locations[index] + bar_width * c, total_count[index] + 2, round(np.mean(utility), 2),
                        fontsize=ip["text_size"], horizontalalignment='center')

            elif obj == "Quartile":

                # Loop through each quartile
                count_sum = 0
                for q in [4, 3, 2, 1]:
                    lb, ub = percentile_dict[q][0], percentile_dict[q][1]
                    count = len(np.where((merit <= ub) & (merit > lb))[0])
                    ax.bar(label_locations[index] + bar_width * c, count, bar_width, bottom=count_sum,
                           edgecolor="black",
                           color=ip['bar_colors']["quartile_" + str(q)], zorder=2)
                    count_sum += count

                    # Put a number on the bar
                    if count >= 10:
                        if q == 1:
                            color = "white"
                        else:
                            color = "black"
                        ax.text(label_locations[index] + bar_width * c, (count_sum - count / 2 - 2), int(count),
                                color=color, zorder=3, fontsize=ip["bar_text_size"], horizontalalignment='center')

            elif obj == "AFOCD":

                # Plot the AFOCD bars
                count_sum = 0
                for objective in afocd_objectives:

                    # Plot AFOCD bars
                    count = afocd_count[objective][index]
                    ax.bar(label_locations[index] + bar_width * c, count, bar_width,
                           bottom=count_sum, edgecolor='black', color=ip['bar_colors'][objective])
                    count_sum += count

                    # Put a number on the bar
                    if count >= 10:

                        prop = count / total_count[index]
                        if objective == "Permitted":
                            color = "black"
                        else:
                            color = "white"
                        ax.text(label_locations[index] + bar_width * c, (count_sum - count / 2 - 2),
                                round(prop, 2), color=color, zorder=3, fontsize=ip["bar_text_size"],
                                horizontalalignment='center')

                # Add the text
                ax.text(label_locations[index] + bar_width * c, total_count[index] + 2, int(total_count[index]),
                        fontsize=ip["text_size"], horizontalalignment='center')

        # Add Lines to the bar chart
        left = label_locations[index] - bar_width / 2
        right = label_locations[index] + bar_width * (num_criteria - 1) + bar_width / 2
        ax.plot((left, right), (total_count[index], total_count[index]), linestyle="-", linewidth=1, zorder=2,
                color="black")

        # PGL Line
        ax.plot((right - 0.02, right + 0.02), (quota[index], quota[index]), linestyle="-", zorder=2, linewidth=4,
                color="black")  # PGL tick mark

        # Add the text
        ax.text(right + 0.04, quota[index], int(quota[index]), fontsize=ip["bar_text_size"], horizontalalignment='left',
                verticalalignment="center")
    # Labels
    ax.set_ylabel("Number of Cadets")
    ax.yaxis.label.set_size(ip["label_size"])
    ax.set_xlabel("AFSCs")
    ax.xaxis.label.set_size(ip["label_size"])

    # Y ticks
    ax.set_yticks(y_ticks)
    ax.tick_params(axis="y", labelsize=ip["yaxis_tick_size"])
    ax.set_yticklabels(y_ticks)
    ax.margins(y=0)
    ax.set(ylim=(0, y_max))

    # X ticks
    ax.set_xticklabels(afscs, rotation=0)
    ax.set_xticks(label_locations + (bar_width / 2) * (num_criteria - 1))
    ax.tick_params(axis="x", labelsize=ip["afsc_tick_size"])
    # ax.set(xlim=[2 * bar_width - 1, num_criteria])

    # Title
    if ip["display_title"]:
        ax.set_title(ip["title"], fontsize=ip["title_size"])

    # Filename
    if ip["filename"] is None:
        ip["filename"] = ip["title"]

    # Save
    if ip['save']:
        fig.savefig(afccp.globals.paths['figures'] + instance.data_name + "/results/" + ip['filename'] + '.png',
                    bbox_inches='tight')

    return fig

cadet_utility_histogram(instance, filepath=None)

Builds the Cadet Utility histogram

Source code in afccp/visualizations/charts.py
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
def cadet_utility_histogram(instance, filepath=None):
    """
    Builds the Cadet Utility histogram
    """

    # Shorthand
    ip = instance.mdl_p

    # Shared elements
    fig, ax = plt.subplots(figsize=ip["figsize"], facecolor=ip["facecolor"], dpi=ip["dpi"], tight_layout=True)
    bins = np.arange(21) / 20

    if ip["solution_names"] is not None:  # Comparing two or more solutions
        if ip["title"] is None:

            # Create the title!
            if ip["num_solutions"] == 1:
                ip['title'] = ip["solution_names"][0] + " Cadet Utility Results Histogram"
            elif ip["num_solutions"] == 2:
                ip['title'] = ip["solution_names"][0] + " and " + ip["solution_names"][1] + \
                              " Cadet Utility Results Histogram"
            elif ip["num_solutions"] == 3:
                ip['title'] = ip["solution_names"][0] + ", " + ip["solution_names"][1] + \
                              ", and " + ip["solution_names"][2] + " Cadet Utility Results Histogram"
            else:
                ip['title'] = ip["solution_names"][0] + ", " + ip["solution_names"][1] + \
                              ", " + ip["solution_names"][2] + ", and " + ip["solution_names"][3] + \
                              " Cadet Utility Results Histogram"

        # Plot the results
        legend_elements = []
        for solution_name in ip["solution_names"]:
            value = instance.solutions[solution_name]['cadet_utility_achieved']
            ax.hist(value, bins=bins, edgecolor='black', color=ip["colors"][solution_name], alpha=0.5)
            legend_elements.append(Patch(facecolor=ip["colors"][solution_name], label=solution_name,
                                         alpha=0.5, edgecolor='black'))

        ax.legend(handles=legend_elements, edgecolor='black', fontsize=ip["legend_size"], loc='upper left',
                  ncol=ip["num_solutions"], columnspacing=0.8, handletextpad=0.25, borderaxespad=0.5, borderpad=0.4)
    else:

        # Get the title and filename
        ip["title"] = "Cadet Utility Results Histogram"
        ip["filename"] = instance.solution_name + " Cadet_Utility_Histogram"
        if ip["solution_in_title"]:
            ip['title'] = instance.solution_name + ": " + ip['title']

        value = instance.solution["cadet_utility_achieved"]
        ax.hist(value, bins=bins, edgecolor='white', color='black', alpha=1)

    # Labels
    ax.set_ylabel('Number of Cadets')
    ax.yaxis.label.set_size(ip["label_size"])
    ax.set_xlabel('Utility Received')
    ax.xaxis.label.set_size(ip["label_size"])

    # Axis
    x_ticks = np.arange(11) / 10
    ax.set_xticks(x_ticks)
    ax.tick_params(axis='x', labelsize=ip["xaxis_tick_size"])
    ax.tick_params(axis='y', labelsize=ip["yaxis_tick_size"])

    # Title
    if ip["display_title"]:
        ax.set_title(ip["title"], fontsize=ip["title_size"])

    # Filename
    if ip["filename"] is None:
        ip["filename"] = ip["title"] + '.png'

    # Save the figure
    if ip["save"]:
        if filepath is None:
            filepath = instance.export_paths['Analysis & Results'] + "Results Charts/"
        fig.savefig(filepath + ip["filename"], bbox_inches='tight')

    return fig

cadet_utility_merit_scatter(instance)

Scatter plot of cadet utility vs cadet merit

Source code in afccp/visualizations/charts.py
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
def cadet_utility_merit_scatter(instance):
    """
    Scatter plot of cadet utility vs cadet merit
    """

    # Shorthand
    ip = instance.plt_p

    # Shared elements
    fig, ax = plt.subplots(figsize=ip["figsize"], facecolor=ip["facecolor"], dpi=ip["dpi"], tight_layout=True)

    # Get the title and filename
    ip["title"] = "Cadet Preference vs. Merit"
    ip["filename"] = instance.solution_name + " Cadet_Preference_Merit_Scatter"
    if ip["solution_in_title"]:
        ip['title'] = instance.solution_name + ": " + ip['title']

    y = instance.metrics["cadet_value"]

    if "merit_all" in instance.parameters:
        x = instance.parameters["merit_all"]
    else:
        x = instance.parameters["merit"]

    ax.scatter(x, y, s=ip["dot_size"], color='black', alpha=1)

    # Labels
    ax.set_ylabel('Cadet Utility Value')
    ax.yaxis.label.set_size(ip["label_size"])
    ax.set_xlabel('Cadet Merit')
    ax.xaxis.label.set_size(ip["label_size"])

    # Axis
    x_ticks = np.arange(11) / 10
    ax.set_xticks(x_ticks)
    ax.tick_params(axis='x', labelsize=ip["xaxis_tick_size"])
    ax.tick_params(axis='y', labelsize=ip["yaxis_tick_size"])

    # Title
    if ip["display_title"]:
        ax.set_title(ip["title"], fontsize=ip["title_size"])

    # Filename
    if ip["filename"] is None:
        ip["filename"] = ip["title"]

    if ip["save"]:
        fig.savefig(afccp.globals.paths['figures'] + instance.data_name + "/results/" + ip["filename"] + '.png',
                    bbox_inches='tight')

    return fig

holistic_color_graph(parameters, value_parameters, metrics, figsize=(11, 10), save=False, facecolor='white')

Builds the Holistic Color Chart

Parameters:

Name Type Description Default
facecolor

color of the background of the graph

'white'
figsize

size of the figure

(11, 10)
save

Whether we should save the graph

False
parameters

fixed cadet/AFSC data

required
value_parameters

value parameters

required
metrics

solution metrics

required

Returns:

Type Description

figure

Source code in afccp/visualizations/charts.py
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
def holistic_color_graph(parameters, value_parameters, metrics, figsize=(11, 10), save=False, facecolor='white'):
    """
    Builds the Holistic Color Chart
    :param facecolor: color of the background of the graph
    :param figsize: size of the figure
    :param save: Whether we should save the graph
    :param parameters: fixed cadet/AFSC data
    :param value_parameters: value parameters
    :param metrics: solution metrics
    :return: figure
    """
    fig, ax = plt.subplots(figsize=figsize, facecolor=facecolor, tight_layout=True)
    ax.set_aspect('equal', adjustable='box')
    N = parameters['N']
    title = 'Attribute Weights and Values Color Chart. Z = ' + str(round(metrics['z'], 2))
    ax.set_title(title)

    # Cadets
    length = value_parameters['cadets_overall_weight']
    values = metrics['cadet_value']
    weights = value_parameters['cadet_weight']
    sorted_indices = values.argsort()[::-1]
    sorted_values = values[sorted_indices]
    sorted_weights = weights[sorted_indices]
    y = 0
    for i in range(N):
        xy = (0, y)
        height = sorted_weights[i]
        objective_value = sorted_values[i]
        c = (1 - objective_value, 0, objective_value)
        rect = Rectangle(xy, length, height, edgecolor='none', color=c)
        ax.add_patch(rect)
        y += height

    # AFSCs
    full_length = value_parameters['afscs_overall_weight']
    afsc_values = metrics['afsc_value']
    afsc_weights = value_parameters['afsc_weight']
    sorted_afsc_indices = afsc_values.argsort()[::-1]
    sorted_afsc_weights = afsc_weights[sorted_afsc_indices]
    y = 0
    for j in sorted_afsc_indices:
        weights = value_parameters['objective_weight'][j, :]
        values = metrics['objective_value'][j, :]
        zeros = np.where(weights == 0)[0]
        weights = np.delete(weights, zeros)
        values = np.delete(values, zeros)
        sorted_indices = values.argsort()[::-1]
        sorted_values = values[sorted_indices]
        sorted_weights = weights[sorted_indices]
        x = value_parameters['cadets_overall_weight']
        height = sorted_afsc_weights[j]
        for k in range(len(sorted_indices)):
            xy = (x, y)
            objective_value = sorted_values[k]
            c = (1 - objective_value, 0, objective_value)
            rect = Rectangle(xy, sorted_weights[k], height, edgecolor='none', color=c)
            ax.add_patch(rect)
            x += sorted_weights[k] * full_length
        height = sorted_afsc_weights[j]
        y += height

    if save:
        fig.savefig(afccp.globals.paths['figures'] + instance.data_name + "/results/" + title + '.png',
                    bbox_inches='tight')

    return fig

pareto_graph(instance, pareto_df, solution_names=None, dimensions=None, save=True, title=None, figsize=(10, 8), facecolor='white', display_title=False, l_word='Value', filepath=None)

Builds the Pareto Frontier Chart for adjusting the overall weight on cadets

Parameters:

Name Type Description Default
filepath

path to the folder to save this chart in

None
solution_names

other solutions to plot on the chart

None
instance

problem instance

required
l_word

"Label word" for whether we're referring to these as "values" or "utilities"

'Value'
display_title

if we should display a title or not

False
save

If we should save the figure

True
title

If we should include a title or not

None
pareto_df

data frame of pareto analysis

required
dimensions

N and M

None
facecolor

color of the background of the graph

'white'
figsize

size of the figure

(10, 8)

Returns:

Type Description

figure

Source code in afccp/visualizations/charts.py
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
def pareto_graph(instance, pareto_df, solution_names=None, dimensions=None, save=True, title=None, figsize=(10, 8),
                 facecolor='white', display_title=False, l_word='Value', filepath=None):
    """
    Builds the Pareto Frontier Chart for adjusting the overall weight on cadets
    :param filepath: path to the folder to save this chart in
    :param solution_names: other solutions to plot on the chart
    :param instance: problem instance
    :param l_word: "Label word" for whether we're referring to these as "values" or "utilities"
    :param display_title: if we should display a title or not
    :param save: If we should save the figure
    :param title: If we should include a title or not
    :param pareto_df: data frame of pareto analysis
    :param dimensions: N and M
    :param facecolor: color of the background of the graph
    :param figsize: size of the figure
    :return: figure
    """

    # Shorthand
    ip = instance.mdl_p

    # Colors and Axis
    cm = plt.cm.get_cmap('RdYlBu')
    label_size = 20
    xaxis_tick_size = 20
    yaxis_tick_size = 20

    # Chart
    fig, ax = plt.subplots(figsize=figsize, facecolor=facecolor, tight_layout=True)
    ax.set_aspect('equal', adjustable='box')

    sc = ax.scatter(pareto_df[l_word + ' on AFSCs'], pareto_df[l_word + ' on Cadets'], c=pareto_df['Weight on Cadets'],
                    s=100, cmap=cm, edgecolor='black', zorder=1)
    c_bar = plt.colorbar(sc)
    c_bar.set_label('Weight on Cadets', fontsize=label_size)
    c_bar.ax.tick_params(labelsize=xaxis_tick_size)
    if title is None:
        if dimensions is not None:
            N = dimensions[0]
            M = dimensions[1]
            title = 'Pareto Frontier for Weight on Cadets (N=' + str(N) + ', M=' + str(M) + ')'
        else:
            title = 'Pareto Frontier for Weight on Cadets'
    if display_title:
        ax.set_title(title)

    # Plot solution point(s)
    if solution_names is not None:
        for solution_name in solution_names:
            solution = instance.solutions[solution_name]
            ax.scatter(solution['afsc_utility_overall'], solution['cadet_utility_overall'],
                       c=ip["colors"][solution_name],
                       s=100, edgecolor='black', zorder=2, marker=ip["markers"][solution_name])
            plt.text(solution['afsc_utility_overall'],
                     solution['cadet_utility_overall'] + 0.003, solution_name, fontsize=15,
                     horizontalalignment='center')

    # Labels
    ax.set_ylabel(l_word + ' on Cadets')
    ax.yaxis.label.set_size(label_size)
    ax.set_xlabel(l_word + ' on AFSCs')
    ax.xaxis.label.set_size(label_size)

    # Axis
    ax.tick_params(axis='y', labelsize=yaxis_tick_size)
    ax.tick_params(axis='x', labelsize=xaxis_tick_size)

    # Save the figure
    if save:
        if filepath is None:
            filepath = instance.export_paths['Analysis & Results'] + "Results Charts/"
        if solution_names is None:
            filename = instance.data_name + " " + title + '.png'
        else:
            string_names = ', '.join(solution_names)
            filename = instance.data_name + " " + title + '(' + string_names + ').png'
        fig.savefig(filepath + filename, bbox_inches='tight')

    return fig

afsc_objective_weights_graph(parameters, value_parameters_dict, afsc, colors=None, save=False, figsize=(19, 7), facecolor='white', title=None, display_title=True, label_size=25, bar_color=None, xaxis_tick_size=15, yaxis_tick_size=25, legend_size=25, title_size=25)

This chart compares the weights under different value parameters for AFSC objectives for a particular AFSC

Parameters:

Name Type Description Default
bar_color

color of bars for figure (for certain kinds of graphs)

None
title_size

font size of the title

25
legend_size

font size of the legend

25
yaxis_tick_size

y axis tick sizes

25
xaxis_tick_size

x axis tick sizes

15
label_size

size of labels

25
display_title

if we should show the title

True
title

title of chart

None
parameters

fixed cadet/AFSC parameters

required
value_parameters_dict

dictionary of value parameters

required
afsc

which AFSC we should plot

required
colors

colors for the kinds of weights

None
save

Whether we should save the graph

False
facecolor

color of the background of the graph

'white'
figsize

size of the figure

(19, 7)

Returns:

Type Description

figure

Source code in afccp/visualizations/charts.py
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
def afsc_objective_weights_graph(parameters, value_parameters_dict, afsc, colors=None, save=False, figsize=(19, 7),
                                 facecolor="white", title=None, display_title=True, label_size=25, bar_color=None,
                                 xaxis_tick_size=15, yaxis_tick_size=25, legend_size=25, title_size=25):
    """
    This chart compares the weights under different value parameters for AFSC objectives for a particular AFSC
    :param bar_color: color of bars for figure (for certain kinds of graphs)
    :param title_size: font size of the title
    :param legend_size: font size of the legend
    :param yaxis_tick_size: y axis tick sizes
    :param xaxis_tick_size: x axis tick sizes
    :param label_size: size of labels
    :param display_title: if we should show the title
    :param title: title of chart
    :param parameters: fixed cadet/AFSC parameters
    :param value_parameters_dict: dictionary of value parameters
    :param afsc: which AFSC we should plot
    :param colors: colors for the kinds of weights
    :param save: Whether we should save the graph
    :param facecolor: color of the background of the graph
    :param figsize: size of the figure
    :return: figure
    """
    if colors is None:
        colors = ['blue', 'black', 'orange', 'magenta']

    if title is None:
        title = afsc + ' Objective Weights For Different Value Parameters'

    fig, ax = plt.subplots(figsize=figsize, facecolor=facecolor, tight_layout=True)

    # Get chart specs
    num_weights = len(value_parameters_dict)
    j = np.where(parameters['afscs'] == afsc)[0][0]
    first_key = list(value_parameters_dict.keys())[0]
    K_A = value_parameters_dict[first_key]['K^A'][j].astype(int)
    objectives = value_parameters_dict[first_key]['objectives'][K_A]
    for k, objective in enumerate(objectives):
        if objective == 'USAFA Proportion':
            objectives[k] = 'USAFA\nProportion'
        elif objective == 'Combined Quota':
            objectives[k] = 'Combined\nQuota'

    if colors is None:
        colors = ['blue', 'lime', 'orange', 'magenta', 'yellow', 'cyan', 'green', 'deeppink', 'red']
        colors = colors[:num_weights]

    if bar_color is not None:
        colors = [bar_color for _ in range(num_weights)]

    # Set the bar chart structure parameters
    label_locations = np.arange(len(K_A))
    bar_width = 0.8 / num_weights

    # Loop through each set of value parameters
    max_weight = 0
    for w_num, weight_name in enumerate(value_parameters_dict):
        # Plot weights
        weights = value_parameters_dict[weight_name]['objective_weight'][j, K_A]
        max_weight = max(max_weight, max(weights))
        ax.bar(label_locations + bar_width * w_num, weights, bar_width, edgecolor='black',
               label=weight_name, color=colors[w_num], alpha=0.5)

    # Labels
    ax.set_ylabel('Objective Weight')
    ax.yaxis.label.set_size(label_size)
    if bar_color is not None:
        ax.set_xlabel('Objectives')
        ax.xaxis.label.set_size(label_size)

    # X ticks
    ax.set(xticks=label_locations + (bar_width / 2) * (num_weights - 1),
           xticklabels=[value_parameters_dict[first_key]['objectives'][i] for i in K_A])
    ax.tick_params(axis='x', labelsize=xaxis_tick_size)
    ax.set_xticklabels(objectives)

    # Y ticks
    ax.tick_params(axis='y', labelsize=yaxis_tick_size)
    ax.margins(y=0)
    ax.set(ylim=(0, max_weight * 1.2))

    if display_title:
        ax.set_title(title, fontsize=title_size)

    if bar_color is None:
        ax.legend(edgecolor='black', fontsize=legend_size, loc='upper right',
                  ncol=num_weights, columnspacing=0.8, handletextpad=0.25, borderaxespad=0.5, borderpad=0.4)

    if save:
        fig.savefig(afccp.globals.paths['figures'] + instance.data_name + "/value parameters/" + title + '.png',
                    bbox_inches='tight')

    return fig

solution_parameter_comparison_graph(z_dict, colors=None, save=False, figsize=(19, 7), facecolor='white')

This chart compares the solutions' objective values under different value parameters

Parameters:

Name Type Description Default
z_dict

dictionary of solution objective values for each set of value parameters

required
colors

colors for the kinds of weights

None
save

Whether we should save the graph

False
facecolor

color of the background of the graph

'white'
figsize

size of the figure

(19, 7)

Returns:

Type Description

figure

Source code in afccp/visualizations/charts.py
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
def solution_parameter_comparison_graph(z_dict, colors=None, save=False, figsize=(19, 7), facecolor="white"):
    """
    This chart compares the solutions' objective values under different value parameters
    :param z_dict: dictionary of solution objective values for each set of value parameters
    :param colors: colors for the kinds of weights
    :param save: Whether we should save the graph
    :param facecolor: color of the background of the graph
    :param figsize: size of the figure
    :return: figure
    """
    fig, ax = plt.subplots(figsize=figsize, facecolor=facecolor, tight_layout=True)

    # Get chart specs
    solution_names = list(z_dict.keys())
    vp_names = list(z_dict[solution_names[0]].keys())
    num_solutions = len(solution_names)
    num_vps = len(vp_names)

    if colors is None:
        colors = ['blue', 'lime', 'orange', 'magenta', 'yellow', 'cyan', 'green', 'deeppink', 'red']
        colors = colors[:num_solutions]

    # Set the bar chart structure parameters
    label_locations = np.arange(num_vps)
    bar_width = 0.8 / num_solutions

    # Loop through each set of solutions
    legend_elements = []
    for s_num, solution_name in enumerate(solution_names):
        legend_elements.append(Patch(facecolor=colors[s_num], label=solution_name, alpha=0.5, edgecolor='black'))
        for vp_num, vp_name in enumerate(vp_names):
            # Plot solutions
            ax.bar(label_locations[vp_num] + bar_width * s_num, z_dict[solution_name][vp_name], bar_width,
                   edgecolor='black', color=colors[s_num])

    # Text
    ax.set_ylabel('Z')
    ax.set(xticks=label_locations + bar_width / 2, xlim=[2 * bar_width - 1, num_vps],
           xticklabels=vp_names)

    title = 'Objective Values for Different Solutions and Value Parameters'
    ax.set_title(title)
    ax.legend(handles=legend_elements, edgecolor='black', loc='upper right', columnspacing=0.8, handletextpad=0.25,
              borderaxespad=0.5, borderpad=0.4)
    if save:
        fig.savefig(afccp.globals.paths['figures'] + instance.data_name + "/value parameters/" + title + '.png',
                    bbox_inches='tight')

    return fig

solution_results_graph(parameters, value_parameters, solutions, vp_name, k, save=False, colors=None, figsize=(19, 7), facecolor='white')

Builds the Graph to show how well we meet each of the objectives

Parameters:

Name Type Description Default
colors

colors of the solutions

None
vp_name

value parameter name (to access from solutions)

required
k

objective index

required
facecolor

color of the background of the graph

'white'
figsize

size of the figure

(19, 7)
save

Whether we should save the graph

False
parameters

fixed cadet/AFSC data

required
value_parameters

value parameters

required
solutions

solution metrics dictionary

required

Returns:

Type Description

figure

Source code in afccp/visualizations/charts.py
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
def solution_results_graph(parameters, value_parameters, solutions, vp_name, k, save=False, colors=None,
                           figsize=(19, 7), facecolor='white'):
    """
    Builds the Graph to show how well we meet each of the objectives
    :param colors: colors of the solutions
    :param vp_name: value parameter name (to access from solutions)
    :param k: objective index
    :param facecolor: color of the background of the graph
    :param figsize: size of the figure
    :param save: Whether we should save the graph
    :param parameters: fixed cadet/AFSC data
    :param value_parameters: value parameters
    :param solutions: solution metrics dictionary
    :return: figure
    """

    # Load the data
    indices = value_parameters['J^E'][k]
    afscs = parameters['afscs'][indices]
    minimums = np.zeros(len(indices))
    maximums = np.zeros(len(indices))
    num_solutions = len(solutions.keys())
    if colors is None:
        colors = ['blue', 'lime', 'orange', 'magenta', 'yellow', 'cyan', 'green', 'deeppink', 'red']
        colors = colors[:num_solutions]

    fig, ax = plt.subplots(figsize=figsize, facecolor=facecolor, tight_layout=True)
    for j, loc in enumerate(indices):
        if k == 0:
            minimums[j], maximums[j] = 0.35, 0.65
        elif k == 1:
            minimums[j], maximums[j] = 0.20, 0.40
        elif k == 2:
            minimums[j] = parameters['quota_min'][j] / parameters['quota'][j]
            maximums[j] = parameters['quota_max'][j] / parameters['quota'][j]
        elif k == 3:
            if parameters['usafa_quota'][j] / parameters['quota'][j] == 0:
                minimums[j], maximums[j] = 0, 0
            elif parameters['usafa_quota'][j] / parameters['quota'][j] == 1:
                minimums[j], maximums[j] = 1, 1
            else:
                minimums[j] = parameters['usafa_quota'][j] / parameters['quota'][j] - 0.1
                maximums[j] = parameters['usafa_quota'][j] / parameters['quota'][j] + 0.1
        elif k == 4:
            if parameters['usafa_quota'][j] / parameters['quota'][j] == 0:
                minimums[j], maximums[j] = 1, 1
            elif parameters['usafa_quota'][j] / parameters['quota'][j] == 1:
                minimums[j], maximums[j] = 0, 0
            else:
                minimums[j] = (parameters['quota'][j] - parameters['usafa_quota'][j]) / parameters['quota'][j] - 0.1
                maximums[j] = (parameters['quota'][j] - parameters['usafa_quota'][j]) / parameters['quota'][j] + 0.1
        elif k in [5, 6, 7]:
            if k == 5 or (k == 6 and afscs[j] not in ["14F", "15A", "17D"]):
                minimums[j] = value_parameters['objective_target'][loc, k]
                maximums[j] = 1
            else:
                minimums[j] = 0
                maximums[j] = value_parameters['objective_target'][loc, k]
        elif k == 8:
            minimums[j], maximums[j] = 0.8, 1
        elif k == 9:
            male_proportion = np.mean(parameters['male'])
            minimums[j], maximums[j] = male_proportion - 0.1, male_proportion + 0.1
        elif k == 10:
            minority_proportion = np.mean(parameters['minority'])
            minimums[j], maximums[j] = minority_proportion - 0.1, minority_proportion + 0.1

    # ticks = list(np.arange(0, 1.1, 0.1))
    # ax.set_yticks(ticks)
    for s_num, solution_name in enumerate(solutions.keys()):
        if k == 2:
            measures = solutions[solution_name][vp_name]['objective_measure'][indices, k] / \
                       parameters['quota'][indices]
        elif k == 3:
            measures = solutions[solution_name][vp_name]['objective_measure'][indices, k] / \
                       parameters['usafa_quota'][indices]
        elif k == 4:
            measures = solutions[solution_name][vp_name]['objective_measure'][indices, k] / \
                       (parameters['quota'][indices] - parameters['usafa_quota'][indices])
        else:
            measures = solutions[solution_name][vp_name]['objective_measure'][indices, k]

        ax.scatter(afscs, measures, c=colors[s_num], linewidths=4)

    # Ranges
    y = [(minimums[i], maximums[i]) for i in range(len(afscs))]
    x = range(len(afscs))
    for i in x:
        plt.axvline(x=i, color='black', linestyle='--', alpha=0.2)
    ax.plot((x, x), ([i for (i, j) in y], [j for (i, j) in y]), c='black')
    ax.scatter(afscs, minimums, c='black', marker="_", linewidth=2)
    ax.scatter(afscs, maximums, c='black', marker="_", linewidth=2)

    # Titles and Labels
    objective = value_parameters['objectives'][k]
    ax.set_title(objective + ' Solution Comparison')
    ax.set_ylabel(objective + ' Measure')

    if save:
        fig.savefig(afccp.globals.paths['figures'] + instance.data_name + "/results/Solution Results Graph.png",
                    bbox_inches='tight')

    return fig

solution_similarity_graph(instance, coords, solution_names, filepath=None)

This is the chart that compares the approximate and exact models (with genetic algorithm) in solve time and objective value

Source code in afccp/visualizations/charts.py
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
def solution_similarity_graph(instance, coords, solution_names, filepath=None):
    """
    This is the chart that compares the approximate and exact models (with genetic algorithm) in solve time and
    objective value
    """

    # Load in plot parameters
    ip = instance.mdl_p
    ip["figsize"] = (10, 10)

    if ip["title"] is None:
        ip["title"] = instance.data_name + " Solution Similarity"

    # Create figure
    fig, ax = plt.subplots(figsize=ip["figsize"], facecolor=ip["facecolor"], tight_layout=True)
    ax.set_aspect('equal', adjustable='box')

    # Plot the solution dot
    legend_elements = []
    special_solutions = []
    for i, solution_name in enumerate(solution_names):
        x, y = coords[i, 0], coords[i, 1]

        # "Special" Solutions to show
        if solution_name in ip['solution_names']:
            special_solutions.append(solution_name)
            ax.scatter(x, y, c=ip["colors"][solution_name], marker=ip["markers"][solution_name], edgecolor="black",
                       s=ip["sim_dot_size"], zorder=2)

            # Add legend element
            legend_elements.append(mlines.Line2D([], [], color=ip["colors"][solution_name],
                                                 marker=ip["markers"][solution_name], linestyle='None',
                                                 markeredgecolor='black', markersize=20, label=solution_name))

        # "Basic" solutions
        else:

            ax.scatter(x, y, c=ip['default_sim_color'], marker=ip["default_sim_marker"], edgecolor="black",
                       s=ip["sim_dot_size"], zorder=2)

    ax.legend(handles=legend_elements, edgecolor='black', fontsize=ip["legend_size"], loc='upper right',
              ncol=len(legend_elements), columnspacing=0.4, handletextpad=0.1, borderaxespad=0.5, borderpad=0.2)

    # Remove tick marks
    ax.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False)

    # Save the figure
    if ip["save"]:
        if filepath is None:
            filepath = instance.export_paths['Analysis & Results'] + "Results Charts/"
        if len(special_solutions) > 0:
            string_names = ', '.join(special_solutions)
            filename = ip['title'] + '(' + string_names + ').png'
        else:
            filename = ip['title'] + '.png'
        fig.savefig(filepath + filename, bbox_inches='tight')

    return fig