<commit_before>import sys
import cmath
import math
import numpy as np

from matplotlib import pyplot as plt

import param

from holoviews.core.options import Store, Options
from holoviews import Points, Overlay
from holoviews.element.annotation import Contours
from holoviews.operation import ElementOperation

__author__ = "<NAME>"


class WarningCounter(object):
    """
    A simple class to count 'divide by zero' and 'invalid value'
    exceptions to allow a suitable warning message to be generated.
    """
    def __init__(self):
        self.div_by_zeros = 0
        self.invalid_values = 0


    def __call__(self, errtype, flag):
        if errtype == "divide by zero":
            self.div_by_zeros += 1
        elif errtype == "invalid value":
            self.invalid_values += 1


    def warn(self):
        total_events = self.div_by_zeros + self.invalid_values
        if total_events == 0: return
        info = (total_events, self.div_by_zeros, self.invalid_values)
        self.div_by_zeros = 0;
        self.invalid_values = 0
        message = ("Warning: There were %d invalid intersection events:"
                   "\n\tNumpy 'divide by zero' events: %d"
                   "\n\tNumpy 'invalid value' events: %d\n")
        sys.stderr.write(message % info)



class PinwheelAnalysis(ElementOperation):
    """
    Given a Matrix or HoloMap of a cyclic feature preference, compute
    the position of all pinwheel singularities in the map. Optionally
    includes the contours for the real and imaginary components of the
    preference map used to determine the pinwheel locations.

    Returns the original Matrix input overlayed with a Points object
    containing the computed pinwheel locations and (optionally)
    Contours overlays including the real and imaginary contour lines
    respectively.
    """

    output_type = Overlay

    # TODO: Optional computation of pinwheel polarities.

    include_contours = param.Boolean(default=True, doc="""
      Whether or not to include the computed contours for the real and
      imaginary components of the map.""")

    silence_warnings =param.Boolean(default=True, doc="""
      Whether or not to show warnings about invalid intersection
      events when locating pinwheels.""")

    label = param.String(None, allow_None=True, precedence=-1, constant=True,
     doc="""Label suffixes are fixed as there are too many labels to specify.""")

    def _process(self, view, key=None):

        cyclic_matrix = None
        inputs = view.values() if isinstance(view, Overlay) else [view]
        for input_element in inputs:
            if input_element.value_dimensions[0].cyclic:
                cyclic_matrix = input_element
                bounds = cyclic_matrix.bounds
                cyclic_range = input_element.value_dimensions[0].range
                break
        else:
            raise Exception("Pinwheel analysis requires a Matrix over a cyclic quantity")

        if None in cyclic_range:
            raise Exception("Pinwheel analysis requires a Matrix with defined cyclic range")


        cyclic_data = cyclic_matrix.data / (cyclic_range[1] - cyclic_range[0])
        polar_map = self.polar_preference(cyclic_data)
        try:
            contour_info = self.polarmap_contours(polar_map, bounds)
        except Exception as e:
            self.warning("Contour identification failed:\n%s" % str(e))
            contour_info = None

        if contour_info is not None:
            (re_contours, im_contours, intersections) = contour_info
            pinwheels = self.identify_pinwheels(*(re_contours, im_contours, intersections),
                                                silence_warnings=self.p.silence_warnings)
        else:
            pinwheels, re_contours, im_contours = np.array([[],[]]).T, [], []

        label = cyclic_matrix.label
        pinwheels = Points(np.array(pinwheels), label=label, value='Pinwheels')

        if self.p.include_contours:
            re_lines = Contours(re_contours, label=label, value='Real')
            im_lines = Contours(im_contours, label=label, value='Imaginary')
            return cyclic_matrix * re_lines * im_lines * pinwheels
        else:
            return cyclic_matrix * pinwheels



    def polar_preference(self, pref):
        """
        Turns hue representation to polar representation.
        Hue representation uses values expected in the range 0-1.0
        """
        polarfn = lambda x: cmath.rect(1.0, x * 2 * math.pi)<commit_msg>PinwheelAnalysis now sets appropriate value and label on return overlay<commit_after>import sys
import cmath
import math
import numpy as np

from matplotlib import pyplot as plt

import param

from holoviews.core.options import Store, Options
from holoviews import Points, Overlay
from holoviews.element.annotation import Contours
from holoviews.operation import ElementOperation

__author__ = "<NAME>"


class WarningCounter(object):
    """
    A simple class to count 'divide by zero' and 'invalid value'
    exceptions to allow a suitable warning message to be generated.
    """
    def __init__(self):
        self.div_by_zeros = 0
        self.invalid_values = 0


    def __call__(self, errtype, flag):
        if errtype == "divide by zero":
            self.div_by_zeros += 1
        elif errtype == "invalid value":
            self.invalid_values += 1


    def warn(self):
        total_events = self.div_by_zeros + self.invalid_values
        if total_events == 0: return
        info = (total_events, self.div_by_zeros, self.invalid_values)
        self.div_by_zeros = 0;
        self.invalid_values = 0
        message = ("Warning: There were %d invalid intersection events:"
                   "\n\tNumpy 'divide by zero' events: %d"
                   "\n\tNumpy 'invalid value' events: %d\n")
        sys.stderr.write(message % info)



class PinwheelAnalysis(ElementOperation):
    """
    Given a Matrix or HoloMap of a cyclic feature preference, compute
    the position of all pinwheel singularities in the map. Optionally
    includes the contours for the real and imaginary components of the
    preference map used to determine the pinwheel locations.

    Returns the original Matrix input overlayed with a Points object
    containing the computed pinwheel locations and (optionally)
    Contours overlays including the real and imaginary contour lines
    respectively.
    """

    output_type = Overlay

    # TODO: Optional computation of pinwheel polarities.

    include_contours = param.Boolean(default=True, doc="""
      Whether or not to include the computed contours for the real and
      imaginary components of the map.""")

    silence_warnings =param.Boolean(default=True, doc="""
      Whether or not to show warnings about invalid intersection
      events when locating pinwheels.""")

    label = param.String(None, allow_None=True, precedence=-1, constant=True,
     doc="""Label suffixes are fixed as there are too many labels to specify.""")

    def _process(self, view, key=None):

        cyclic_matrix = None
        inputs = view.values() if isinstance(view, Overlay) else [view]
        for input_element in inputs:
            if input_element.value_dimensions[0].cyclic:
                cyclic_matrix = input_element
                bounds = cyclic_matrix.bounds
                cyclic_range = input_element.value_dimensions[0].range
                break
        else:
            raise Exception("Pinwheel analysis requires a Matrix over a cyclic quantity")

        if None in cyclic_range:
            raise Exception("Pinwheel analysis requires a Matrix with defined cyclic range")


        cyclic_data = cyclic_matrix.data / (cyclic_range[1] - cyclic_range[0])
        polar_map = self.polar_preference(cyclic_data)
        try:
            contour_info = self.polarmap_contours(polar_map, bounds)
        except Exception as e:
            self.warning("Contour identification failed:\n%s" % str(e))
            contour_info = None

        if contour_info is not None:
            (re_contours, im_contours, intersections) = contour_info
            pinwheels = self.identify_pinwheels(*(re_contours, im_contours, intersections),
                                                silence_warnings=self.p.silence_warnings)
        else:
            pinwheels, re_contours, im_contours = np.array([[],[]]).T, [], []

        label = cyclic_matrix.label
        pinwheels = Points(np.array(pinwheels), label=label, value='Pinwheels')

        if self.p.include_contours:
            re_lines = Contours(re_contours, label=label, value='Real')
            im_lines = Contours(im_contours, label=label, value='Imaginary')
            overlay =  cyclic_matrix * re_lines * im_lines * pinwheels
        else:
            overlay = (cyclic_matrix * pinwheels)

        return overlay.relabel(value='PinwheelAnalysis', label=label)



    def polar_preference(self, pref):
        """
        Turns hue representation to polar representation.
        Hue representation uses values expected in the range 0-1.0
        """
        polarfn = lambda x: cmath.rect(1.0, x * 2 * math.pi)
{'fraction_non_alphanumeric': 0.07833698030634573, 'fraction_numerical': 0.003938730853391685, 'mean_word_length': 2.65055910543131, 'pattern_counts': {'":': 4, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1865977', 'n_tokens_mistral': 2560, 'n_tokens_neox': 2419, 'n_words': 795}