Ejemplo n.º 1
0
def characteristics_dict(person: StatePerson,
                         supervision_time_bucket: SupervisionTimeBucket,
                         metric_class: Type[SupervisionMetric],
                         person_metadata: PersonMetadata) -> Dict[str, Any]:
    """Builds a dictionary that describes the characteristics of the person and supervision_time_bucket.

    Args:
        person: the StatePerson we are picking characteristics from
        supervision_time_bucket: the SupervisionTimeBucket we are picking characteristics from
        metric_class: The SupervisionMetric provided determines which fields should be added to the characteristics
            dictionary
        person_metadata: Contains information about the StatePerson that is necessary for the metrics.

    Returns:
        A dictionary populated with all relevant characteristics.
    """

    event_date = supervision_time_bucket.bucket_date

    if (issubclass(metric_class, SupervisionCaseComplianceMetric)
            and supervision_time_bucket.case_compliance):
        event_date = supervision_time_bucket.case_compliance.date_of_evaluation

    # We don't want demographic or person-level attributes on the SupervisionRevocationViolationTypeAnalysisMetrics
    include_person_attributes = (metric_class != SupervisionRevocationViolationTypeAnalysisMetric)

    characteristics = characteristics_dict_builder(pipeline='supervision',
                                                   event=supervision_time_bucket,
                                                   metric_class=metric_class,
                                                   person=person,
                                                   event_date=event_date,
                                                   include_person_attributes=include_person_attributes,
                                                   person_metadata=person_metadata)
    return characteristics
Ejemplo n.º 2
0
def characteristics_dict(person: StatePerson, event: ReleaseEvent,
                         metric_class: Type[ReincarcerationRecidivismMetric],
                         person_metadata: PersonMetadata) -> Dict[str, Any]:
    """Builds a dictionary that describes the characteristics of the person and the release event.

    Release cohort, follow-up period, and methodology are not included in the output here. They are added into
    augmented versions of these combinations later.

    Args:
        person: the StatePerson we are picking characteristics from
        event: the ReleaseEvent we are picking characteristics from
        metric_class: The ReincarcerationRecidivismMetric provided determines which fields should be added to the
            characteristics dictionary
        person_metadata: Contains information about the StatePerson that is necessary for the metrics.

    Returns:
        A dictionary populated with all relevant characteristics.
    """
    event_date = event.original_admission_date

    characteristics = characteristics_dict_builder(
        pipeline='recidivism',
        event=event,
        metric_class=metric_class,
        person=person,
        event_date=event_date,
        include_person_attributes=True,
        person_metadata=person_metadata)

    return characteristics
Ejemplo n.º 3
0
def characteristics_dict(person: StatePerson,
                         incarceration_event: IncarcerationEvent,
                         metric_class: Type[IncarcerationMetric],
                         person_metadata: PersonMetadata) -> Dict[str, Any]:
    """Builds a dictionary that describes the characteristics of the person and event.

    Args:
        person: the StatePerson we are picking characteristics from
        incarceration_event: the IncarcerationEvent we are picking characteristics from
        metric_class: The IncarcerationMetric provided determines which fields should be added to the characteristics
            dictionary
        person_metadata: Contains information about the StatePerson that is necessary for the metrics.
    Returns:
        A dictionary populated with all relevant characteristics.
    """
    event_date = incarceration_event.event_date

    characteristics = characteristics_dict_builder(
        pipeline='incarceration',
        event=incarceration_event,
        metric_class=metric_class,
        person=person,
        event_date=event_date,
        include_person_attributes=True,
        person_metadata=person_metadata)
    return characteristics
Ejemplo n.º 4
0
def map_supervision_combinations(
    person: StatePerson,
    supervision_time_buckets: List[SupervisionTimeBucket],
    metric_inclusions: Dict[SupervisionMetricType, bool],
    calculation_end_month: Optional[str],
    calculation_month_count: int,
    person_metadata: PersonMetadata,
) -> List[Tuple[Dict[str, Any], Any]]:
    """Transforms SupervisionTimeBuckets and a StatePerson into metric combinations.

    Takes in a StatePerson and all of her SupervisionTimeBuckets and returns an array of "supervision combinations".
    These are key-value pairs where the key represents a specific metric and the value represents whether or not
    the person should be counted as a positive instance of that metric.

    This translates a particular time on supervision into many different supervision population metrics.

    Args:
        person: the StatePerson
        supervision_time_buckets: A list of SupervisionTimeBuckets for the given StatePerson.
        metric_inclusions: A dictionary where the keys are each SupervisionMetricType, and the values are boolean
                flags for whether or not to include that metric type in the calculations
        calculation_end_month: The year and month in YYYY-MM format of the last month for which metrics should be
            calculated. If unset, ends with the current month.
        calculation_month_count: The number of months (including the month of the calculation_end_month) to
            limit the monthly calculation output to. If set to -1, does not limit the calculations.
        person_metadata: Contains information about the StatePerson that is necessary for the metrics.
    Returns:
        A list of key-value tuples representing specific metric combinations and the value corresponding to that metric.
    """
    metrics: List[Tuple[Dict[str, Any], Any]] = []

    supervision_time_buckets.sort(key=attrgetter("year", "month"))

    calculation_month_upper_bound = get_calculation_month_upper_bound_date(
        calculation_end_month)
    calculation_month_lower_bound = get_calculation_month_lower_bound_date(
        calculation_month_upper_bound, calculation_month_count)

    for supervision_time_bucket in supervision_time_buckets:
        event_date = supervision_time_bucket.event_date

        if (isinstance(supervision_time_bucket,
                       NonRevocationReturnSupervisionTimeBucket)
                and supervision_time_bucket.case_compliance):
            event_date = supervision_time_bucket.case_compliance.date_of_evaluation

        event_year = event_date.year
        event_month = event_date.month

        if not include_in_output(
                event_year,
                event_month,
                calculation_month_upper_bound,
                calculation_month_lower_bound,
        ):
            continue

        applicable_metric_types = BUCKET_TO_METRIC_TYPES.get(
            type(supervision_time_bucket))

        if not applicable_metric_types:
            raise ValueError(
                "No metric types mapped to supervision_time_bucket of type {}".
                format(type(supervision_time_bucket)))

        for metric_type in applicable_metric_types:
            if not metric_inclusions[metric_type]:
                continue

            metric_class = METRIC_TYPE_TO_CLASS.get(metric_type)

            if not metric_class:
                raise ValueError(
                    "No metric class for metric type {}".format(metric_type))

            if include_event_in_metric(supervision_time_bucket, metric_type):
                characteristic_combo = characteristics_dict_builder(
                    pipeline="supervision",
                    event=supervision_time_bucket,
                    metric_class=metric_class,
                    person=person,
                    event_date=event_date,
                    person_metadata=person_metadata,
                )

                metric_combo = augmented_combo_for_calculations(
                    characteristic_combo,
                    supervision_time_bucket.state_code,
                    metric_type,
                    event_year,
                    event_month,
                )

                value = value_for_metric_combo(supervision_time_bucket,
                                               metric_type)

                metrics.append((metric_combo, value))

    return metrics
Ejemplo n.º 5
0
def map_recidivism_combinations(
    person: StatePerson,
    release_events: Dict[int, List[ReleaseEvent]],
    metric_inclusions: Dict[ReincarcerationRecidivismMetricType, bool],
    person_metadata: PersonMetadata,
) -> List[Tuple[Dict[str, Any], Any]]:
    """Transforms ReleaseEvents and a StatePerson into metric combinations.

    Takes in a StatePerson and all of her ReleaseEvents and returns an array
    of "recidivism combinations". These are key-value pairs where the key
    represents a specific metric and the value represents whether or not
    recidivism occurred.

    This translates a particular recidivism event into many different recidivism
    metrics. Both count-based and rate-based metrics are generated. Each metric
    represents one of many possible combinations of characteristics being
    tracked for that event. For example, if an asian male is reincarcerated,
    there is a metric that corresponds to asian people, one to males,
    one to asian males, one to all people, and more depending on other
    dimensions in the data.

    If a release does not count towards recidivism, then the value is 0 for
    the rate-based metrics in either methodology.

    For both count and rate-based metrics, the value is 0 if the dimensions
    of the metric do not fully match the attributes of the person and their type
    of return to incarceration. For example, for a RecidivismReleaseEvent where
    the return_type is 'REVOCATION', there will be metrics produced where the
    return_type is 'NEW INCARCERATION_ADMISSION' and the value is 0.

    Args:
        person: the StatePerson
        release_events: A dictionary mapping release cohorts to a list of
            ReleaseEvents for the given StatePerson.
        metric_inclusions: A dictionary where the keys are each ReincarcerationRecidivismMetricType, and the values
            are boolean flags for whether or not to include that metric type in the calculations
        person_metadata: Contains information about the StatePerson that is necessary for the metrics.

    Returns:
        A list of key-value tuples representing specific metric combinations and
        the recidivism value corresponding to that metric.
    """
    metrics = []
    all_reincarcerations = reincarcerations(release_events)

    if metric_inclusions.get(
            ReincarcerationRecidivismMetricType.REINCARCERATION_RATE):
        for events in release_events.values():
            for event in events:
                event_date = event.release_date

                characteristic_combo = characteristics_dict_builder(
                    pipeline="recidivism",
                    event=event,
                    metric_class=ReincarcerationRecidivismRateMetric,
                    person=person,
                    event_date=event_date,
                    person_metadata=person_metadata,
                )

                reincarcerations_by_follow_up_period = reincarcerations_by_period(
                    event_date, all_reincarcerations)

                metrics.extend(
                    combination_rate_metrics(
                        characteristic_combo,
                        event,
                        reincarcerations_by_follow_up_period,
                    ))

    if metric_inclusions.get(
            ReincarcerationRecidivismMetricType.REINCARCERATION_COUNT):
        for reincarceration_event in all_reincarcerations.values():
            event_date = reincarceration_event.reincarceration_date

            characteristic_combo = characteristics_dict_builder(
                pipeline="recidivism",
                event=reincarceration_event,
                metric_class=ReincarcerationRecidivismCountMetric,
                person=person,
                event_date=event_date,
                person_metadata=person_metadata,
            )

            augmented_combo = augmented_combo_for_calculations(
                characteristic_combo,
                state_code=reincarceration_event.state_code,
                year=event_date.year,
                month=event_date.month,
                metric_type=ReincarcerationRecidivismMetricType.
                REINCARCERATION_COUNT,
            )

            metrics.append((augmented_combo, 1))

    return metrics