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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a101a53
 
 
 
 
 
 
 
 
 
 
 
 
e8aad19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
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
346
347
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
392
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
429
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
import copy
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from typing import List, Dict, Tuple, Optional, Any
from modules.utils import normalize, cosine_similarity, project_params, take_two_sides_extreme_sorted, axes_labels_format

__all__ = ['WordBiasExplorer', 'WEBiasExplorer2Spaces', 'WEBiasExplorer4Spaces']

class WordBiasExplorer:
    def __init__(
        self, 
        embedding,      # Embedding class instance
        errorManager    # ErrorManager class instance
    ) -> None:

        self.embedding = embedding
        self.direction = None
        self.positive_end = None
        self.negative_end = None
        self.DIRECTION_METHODS = ['single', 'sum', 'pca']
        self.errorManager = errorManager

    def __copy__(
        self
    ) -> 'WordBiasExplorer':

        bias_word_embedding = self.__class__(self.embedding)
        bias_word_embedding.direction = copy.deepcopy(self.direction)
        bias_word_embedding.positive_end = copy.deepcopy(self.positive_end)
        bias_word_embedding.negative_end = copy.deepcopy(self.negative_end)
        return bias_word_embedding

    def __deepcopy__(
        self, 
        memo: Optional[Dict[int, Any]]
    )-> 'WordBiasExplorer':

        bias_word_embedding = copy.copy(self)
        bias_word_embedding.model = copy.deepcopy(bias_word_embedding.model)
        return bias_word_embedding

    def __getitem__(
        self, 
        key: str
    ) -> np.ndarray:

        return self.embedding.getEmbedding(key)

    def __contains__(
        self, 
        item: str
    ) -> bool:

        return item in self.embedding

    def _is_direction_identified(
        self
    ):
        if self.direction is None:
            raise RuntimeError('The direction was not identified'
                               ' for this {} instance'
                               .format(self.__class__.__name__))

    def _identify_subspace_by_pca(
        self, 
        definitional_pairs: List[Tuple[str, str]], 
        n_components: int
    ) -> PCA:

        matrix = []

        for word1, word2 in definitional_pairs:
            vector1 = normalize(self[word1])
            vector2 = normalize(self[word2])

            center = (vector1 + vector2) / 2

            matrix.append(vector1 - center)
            matrix.append(vector2 - center)

        pca = PCA(n_components=n_components)
        pca.fit(matrix)
        return pca


    def _identify_direction(
        self, 
        positive_end: str, 
        negative_end: str,
        definitional: Tuple[str, str], 
        method: str='pca',
        first_pca_threshold: float=0.5
    ) -> None:

        if method not in self.DIRECTION_METHODS:
            raise ValueError('method should be one of {}, {} was given'.format(
                self.DIRECTION_METHODS, method))

        if positive_end == negative_end:
            raise ValueError('positive_end and negative_end'
                             'should be different, and not the same "{}"'
                             .format(positive_end))
        direction = None

        if method == 'single':
            direction = normalize(normalize(self[definitional[0]])
                                  - normalize(self[definitional[1]]))

        elif method == 'sum':
            group1_sum_vector = np.sum([self[word]
                                        for word in definitional[0]], axis=0)
            group2_sum_vector = np.sum([self[word]
                                        for word in definitional[1]], axis=0)

            diff_vector = (normalize(group1_sum_vector)
                           - normalize(group2_sum_vector))

            direction = normalize(diff_vector)

        elif method == 'pca':
            pca = self._identify_subspace_by_pca(definitional, 10)
            if pca.explained_variance_ratio_[0] < first_pca_threshold:
                raise RuntimeError('The Explained variance'
                                   'of the first principal component should be'
                                   'at least {}, but it is {}'
                                   .format(first_pca_threshold,
                                           pca.explained_variance_ratio_[0]))
            direction = pca.components_[0]

            # if direction is opposite (e.g. we cannot control
            # what the PCA will return)
            ends_diff_projection = cosine_similarity((self[positive_end]
                                                      - self[negative_end]),
                                                     direction)
            if ends_diff_projection < 0:
                direction = -direction  # pylint: disable=invalid-unary-operand-type

        self.direction = direction
        self.positive_end = positive_end
        self.negative_end = negative_end

    def project_on_direction(
        self, 
        word: str
    ) -> float:

        """Project the normalized vector of the word on the direction.
        :param str word: The word tor project
        :return float: The projection scalar
        """

        self._is_direction_identified()

        vector = self[word]
        projection_score = self.embedding.cosineSimilarities(self.direction,
                                                          [vector])[0]
        return projection_score

    def _calc_projection_scores(
        self, 
        words: List[str]
    ) -> pd.DataFrame:

        self._is_direction_identified()

        df = pd.DataFrame({'word': words})

        # TODO: maybe using cosine_similarities on all the vectors?
        # it might be faster
        df['projection'] = df['word'].apply(self.project_on_direction)
        df = df.sort_values('projection', ascending=False)

        return df

    def calc_projection_data(
        self, 
        words: List[str]
    ) -> pd.DataFrame:

        """
        Calculate projection, projected and rejected vectors of a words list.
        :param list words: List of words
        :return: :class:`pandas.DataFrame` of the projection,
                 projected and rejected vectors of the words list
        """
        projection_data = []
        for word in words:
            vector = self[word]
            normalized_vector = normalize(vector)

            (projection,
             projected_vector,
             rejected_vector) = project_params(normalized_vector,
                                               self.direction)

            projection_data.append({'word': word,
                                    'vector': vector,
                                    'projection': projection,
                                    'projected_vector': projected_vector,
                                    'rejected_vector': rejected_vector})

        return pd.DataFrame(projection_data)

    def plot_dist_projections_on_direction(
        self, 
        word_groups: Dict[str, List[str]], 
        ax: plt.Axes=None
    ) -> plt.Axes:

        """Plot the projection scalars distribution on the direction.
        :param dict word_groups word: The groups to projects
        :return float: The ax object of the plot
        """

        if ax is None:
            _, ax = plt.subplots(1)

        names = sorted(word_groups.keys())

        for name in names:
            words = word_groups[name]
            label = '{} (#{})'.format(name, len(words))
            vectors = [self[word] for word in words]
            projections = self.embedding.cosineSimilarities(self.direction,
                                                         vectors)
            sns.distplot(projections, hist=False, label=label, ax=ax)

        plt.axvline(0, color='k', linestyle='--')

        plt.title('← {} {} {} β†’'.format(self.negative_end,
                                        ' ' * 20,
                                        self.positive_end))
        plt.xlabel('Direction Projection')
        plt.ylabel('Density')
        ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))

        return ax

    def __errorChecking(
        self, 
        word: str
    ) -> str:

        out_msj = ""

        if not word:
            out_msj = ['EMBEDDING_NO_WORD_PROVIDED']
        else:
            if word not in self.embedding:
                out_msj = ['EMBEDDING_WORD_OOV', word]

        return self.errorManager.process(out_msj)

    def check_oov(
        self, 
        wordlists: List[str]
    ) -> str:

        for wordlist in wordlists:
            for word in wordlist:
                msg = self.__errorChecking(word)
                if msg:
                    return msg
        return None
    
class WEBiasExplorer2Spaces(WordBiasExplorer):
    def __init__(
        self, 
        embedding,      # Embedding class instance
        errorManager    # ErrorManager class instance
    ) -> None:

        super().__init__(embedding, errorManager)

    def calculate_bias(
        self,
        wordlist_to_diagnose: List[str],
        wordlist_right: List[str],
        wordlist_left: List[str]
    ) -> plt.Figure:

        wordlists = [wordlist_to_diagnose, wordlist_right, wordlist_left] 
        
        for wordlist in wordlists:
            if not wordlist:
                raise Exception('At least one word should be in the to diagnose list, bias 1 list and bias 2 list')
        
        err = self.check_oov(wordlists)
        if err:
            raise Exception(err)

        return self.get_bias_plot(
                wordlist_to_diagnose,
                definitional=(wordlist_left, wordlist_right),
                method='sum',
                n_extreme=10
            )

    def get_bias_plot(
        self,
        wordlist_to_diagnose: List[str],
        definitional: Tuple[List[str], List[str]],
        method: str='sum',
        n_extreme: int=10,
        figsize: Tuple[int, int]=(10, 10)
    ) -> plt.Figure:

        fig, ax = plt.subplots(1, figsize=figsize)
        self.method = method
        self.plot_projection_scores(
            definitional,
            wordlist_to_diagnose, n_extreme, ax=ax,)

        fig.tight_layout()
        fig.canvas.draw()

        return fig

    def plot_projection_scores(
        self, 
        definitional: Tuple[List[str], List[str]],
        words: List[str], 
        n_extreme: int=10,
        ax: plt.Axes=None, 
        axis_projection_step: float=None
    ) -> plt.Axes:

        """Plot the projection scalar of words on the direction.
        :param list words: The words tor project
        :param int or None n_extreme: The number of extreme words to show
        :return: The ax object of the plot
        """
        name_left = ', '.join(definitional[0])
        name_right = ', '.join(definitional[1])

        self._identify_direction(name_left, name_right,
                                 definitional=definitional,
                                 method='sum')

        self._is_direction_identified()

        projections_df = self._calc_projection_scores(words)
        projections_df['projection'] = projections_df['projection'].round(2)

        if n_extreme is not None:
            projections_df = take_two_sides_extreme_sorted(projections_df,
                                                           n_extreme=n_extreme)

        if ax is None:
            _, ax = plt.subplots(1)

        if axis_projection_step is None:
            axis_projection_step = 0.1

        cmap = plt.get_cmap('RdBu')
        projections_df['color'] = ((projections_df['projection'] + 0.5)
                                   .apply(cmap))

        most_extream_projection = np.round(
            projections_df['projection']
            .abs()
            .max(),
            decimals=1)

        sns.barplot(
            x='projection', 
            y='word', 
            data=projections_df,
            palette=projections_df['color'].tolist()
        )

        plt.xticks(np.arange(-most_extream_projection,
                             most_extream_projection + axis_projection_step,
                             axis_projection_step))


        xlabel = axes_labels_format(
            left=self.negative_end,
            right=self.positive_end,
            sep=' ' * 20,
            word_wrap=3
        )

        plt.xlabel(xlabel)
        plt.ylabel('Words')

        return ax


class WEBiasExplorer4Spaces(WordBiasExplorer):
    def __init__(
        self, 
        embedding,      # Embedding Class instance
        errorManager    # ErrorManager class instance
    ) -> None:

        super().__init__(embedding, errorManager)

    def calculate_bias(
        self,
        wordlist_to_diagnose: List[str],
        wordlist_right: List[str],
        wordlist_left: List[str],
        wordlist_top: List[str],
        wordlist_bottom: List[str],
    ) -> plt.Figure:

        wordlists = [
            wordlist_to_diagnose,
            wordlist_left,
            wordlist_right,
            wordlist_top,
            wordlist_bottom
        ]

        for wordlist in wordlists:
            if not wordlist:
                raise Exception('To plot with 4 spaces, you must enter at least one word in all lists')

        err = self.check_oov(wordlists)
        if err:
            raise Exception(err)

        return self.get_bias_plot(
                wordlist_to_diagnose,
                definitional_1=(wordlist_right, wordlist_left),
                definitional_2=(wordlist_top, wordlist_bottom),
                method='sum',
                n_extreme=10
            )

    def get_bias_plot(
        self,
        wordlist_to_diagnose: List[str],
        definitional_1: Tuple[List[str], List[str]],
        definitional_2: Tuple[List[str], List[str]],
        method: str='sum',
        n_extreme: int=10,
        figsize: Tuple[int, int]=(10, 10)
    ) -> plt.Figure:

        fig, ax = plt.subplots(1, figsize=figsize)
        self.method = method
        self.plot_projection_scores(
            definitional_1,
            definitional_2,
            wordlist_to_diagnose, n_extreme, ax=ax,)
        fig.canvas.draw()

        return fig

    def plot_projection_scores(
        self, 
        definitional_1: Tuple[List[str], List[str]], 
        definitional_2: Tuple[List[str], List[str]],
        words: List[str], 
        n_extreme: int=10,
        ax: plt.Axes=None, 
        axis_projection_step: float=None
    ) -> plt.Axes:

        """Plot the projection scalar of words on the direction.
        :param list words: The words tor project
        :param int or None n_extreme: The number of extreme words to show
        :return: The ax object of the plot
        """

        name_left = ', '.join(definitional_1[1])
        name_right = ', '.join(definitional_1[0])

        self._identify_direction(name_left, name_right,
                                 definitional=definitional_1,
                                 method='sum')

        self._is_direction_identified()

        projections_df = self._calc_projection_scores(words)
        projections_df['projection_x'] = projections_df['projection'].round(2)

        name_top = ', '.join(definitional_2[1])
        name_bottom = ', '.join(definitional_2[0])
        self._identify_direction(name_top, name_bottom,
                                 definitional=definitional_2,
                                 method='sum')

        self._is_direction_identified()

        projections_df['projection_y'] = self._calc_projection_scores(words)[
            'projection'].round(2)

        if n_extreme is not None:
            projections_df = take_two_sides_extreme_sorted(projections_df,
                                                           n_extreme=n_extreme)

        if ax is None:
            _, ax = plt.subplots(1)

        if axis_projection_step is None:
            axis_projection_step = 0.1

        cmap = plt.get_cmap('RdBu')
        projections_df['color'] = ((projections_df['projection'] + 0.5)
                                   .apply(cmap))
        most_extream_projection = np.round(
            projections_df['projection']
            .abs()
            .max(),
            decimals=1
        )
        
        sns.scatterplot(x='projection_x', 
                        y='projection_y', 
                        data=projections_df,
                        # color=list(projections_df['color'].to_list()), # No se distinguen los colores
                        color='blue'
        )

        plt.xticks(np.arange(-most_extream_projection,
                             most_extream_projection + axis_projection_step,
                             axis_projection_step))
        for _, row in (projections_df.iterrows()):
            ax.annotate(
                row['word'], (row['projection_x'], row['projection_y']))


        x_label = axes_labels_format(
            left=name_left,
            right=name_right,
            sep=' ' * 20,
            word_wrap=3
        )
        y_label = axes_labels_format(
            left=name_top,
            right=name_bottom,
            sep=' ' * 20,
            word_wrap=3
        )

        plt.xlabel(x_label)
        ax.xaxis.set_label_position('bottom')
        ax.xaxis.set_label_coords(.5, 0)

        plt.ylabel(y_label)
        ax.yaxis.set_label_position('left')
        ax.yaxis.set_label_coords(0, .5)

        ax.spines['left'].set_position('center')
        ax.spines['bottom'].set_position('center')

        ax.set_xticks([])
        ax.set_yticks([])

        return ax