Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ML] Add option for anomaly charts for metric detector should plot min, mean or max as appropriate #81662

Merged
merged 28 commits into from
Nov 9, 2020
Merged
Show file tree
Hide file tree
Changes from 26 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
7a4e9a0
[ML] Add extra function info to marker tooltip if metric function
qn895 Oct 22, 2020
26aa395
[ML] Add dropdown to pick what function to plot by if metric
qn895 Oct 26, 2020
ffce815
[ML] Plot function associated with highest anomaly score by default
qn895 Oct 26, 2020
3c8972a
[ML] Clean up
qn895 Oct 26, 2020
5fff206
Merge remote-tracking branch 'upstream/master' into ml-metric-plotting
qn895 Oct 28, 2020
eda2c30
[ML] Add filter to table
qn895 Oct 28, 2020
d1071a3
[ML] Metric mini swimlane
qn895 Oct 29, 2020
85f1526
Merge remote upstream/master into ml-metric-plotting
qn895 Nov 2, 2020
21bb6cb
[ML] Refactor
qn895 Nov 2, 2020
a583988
[ML] Delete residual merge code
qn895 Nov 3, 2020
e27e433
Merge remote-tracking branch 'upstream/master' into ml-metric-plotting
qn895 Nov 3, 2020
cb2429e
[ML] Rename actualPlotFunction, fix mean and avg name mismatch
qn895 Nov 3, 2020
9f51223
[ML] Have dropdown use mean instead of avg to match terminology
qn895 Nov 3, 2020
759a3f8
Merge remote-tracking branch 'upstream/master' into ml-metric-plotting
qn895 Nov 3, 2020
19e20ee
[ML] Refactor getFunctionDescription
qn895 Nov 3, 2020
ea8d71f
[ML] Fix anomaly point plotting incorrectly for metric partitioned
qn895 Nov 3, 2020
97e0fc3
Merge remote-tracking branch 'upstream/master' into ml-metric-plotting
qn895 Nov 3, 2020
f694868
[ML] Fix typescript
qn895 Nov 3, 2020
09fe186
[ML] Remove metricActualPlotFunction because we no longer need it
qn895 Nov 3, 2020
12b32ad
Merge remote-tracking branch 'upstream/master' into ml-metric-plotting
qn895 Nov 4, 2020
638ed89
[ML] Fix bounds issue caused by value in form of array
qn895 Nov 4, 2020
3c02f4f
[ML] Fix anomalies not showing up in mini swimlane
qn895 Nov 4, 2020
5350e3d
[ML] Use toastNotificationService from kibana context
qn895 Nov 4, 2020
a7e2482
[ML] Clean up
qn895 Nov 4, 2020
2f028cd
Merge upstream/master into ml-metric-plotting
qn895 Nov 4, 2020
595b8b3
[ML] Minor fixes & clean up
qn895 Nov 4, 2020
64ecedb
[ML] Use constant metric, revert code removal, update function descri…
qn895 Nov 9, 2020
df26340
Merge remote-tracking branch 'upstream/master' into ml-metric-plotting
qn895 Nov 9, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { parseInterval } from '../../../../common/util/parse_interval';
import { getEntityFieldList } from '../../../../common/util/anomaly_utils';
import { buildConfigFromDetector } from '../../util/chart_config_builder';
import { mlJobService } from '../../services/job_service';
import { mlFunctionToESAggregation } from '../../../../common/util/job_utils';

// Builds the chart configuration for the provided anomaly record, returning
// an object with properties used for the display (series function and field, aggregation interval etc),
Expand Down Expand Up @@ -48,6 +49,10 @@ export function buildConfig(record) {
// define the metric series to be plotted.
config.entityFields = getEntityFieldList(record);

if (record.function === 'metric') {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use ML_JOB_AGGREGATION.METRIC from common/constants/aggregation_types

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated here 64ecedb

config.metricFunction = mlFunctionToESAggregation(record.function_description);
}

// Build the tooltip data for the chart info icon, showing further details on what is being plotted.
let functionLabel = config.metricFunction;
if (config.metricFieldName !== undefined) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,6 @@ const ML_TIME_FIELD_NAME = 'timestamp';
const USE_OVERALL_CHART_LIMITS = false;
const MAX_CHARTS_PER_ROW = 4;

// callback(getDefaultChartsData());

export const anomalyDataChange = function (
chartsContainerWidth,
anomalyRecords,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import { useResolver } from '../use_resolver';
import { basicResolvers } from '../resolvers';
import { getBreadcrumbWithUrlForApp } from '../breadcrumbs';
import { useTimefilter } from '../../contexts/kibana';
import { useToastNotificationService } from '../../services/toast_notification_service';

export const timeSeriesExplorerRouteFactory = (
navigateToPath: NavigateToPath,
Expand Down Expand Up @@ -88,6 +89,7 @@ export const TimeSeriesExplorerUrlStateManager: FC<TimeSeriesExplorerUrlStateMan
config,
jobsWithTimeRange,
}) => {
const toastNotificationService = useToastNotificationService();
const [appState, setAppState] = useUrlState('_a');
const [globalState, setGlobalState] = useUrlState('_g');
const [lastRefresh, setLastRefresh] = useState(0);
Expand Down Expand Up @@ -293,6 +295,7 @@ export const TimeSeriesExplorerUrlStateManager: FC<TimeSeriesExplorerUrlStateMan
return (
<TimeSeriesExplorer
{...{
toastNotificationService,
appStateHandler,
autoZoomDuration,
bounds,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,9 @@ export const resultsApiProvider = (httpService: HttpService) => ({
latestMs: number,
dateFormatTz: string,
maxRecords: number,
maxExamples: number,
influencersFilterQuery: any
maxExamples?: number,
influencersFilterQuery?: any,
functionDescription?: string | undefined
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should be able to remove | undefined because of the ?.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated here 64ecedb

) {
const body = JSON.stringify({
jobIds,
Expand All @@ -39,6 +40,7 @@ export const resultsApiProvider = (httpService: HttpService) => ({
maxRecords,
maxExamples,
influencersFilterQuery,
functionDescription,
});

return httpService.http$<any>({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { ML_MEDIAN_PERCENTS } from '../../../../common/util/job_utils';
import { JobId } from '../../../../common/types/anomaly_detection_jobs';
import { MlApiServices } from '../ml_api_service';
import { CriteriaField } from './index';
import { aggregationTypeTransform } from '../../../../common/util/anomaly_utils';

interface ResultResponse {
success: boolean;
Expand Down Expand Up @@ -347,9 +348,10 @@ export function resultsServiceRxProvider(mlApiServices: MlApiServices) {
jobIds: string[],
criteriaFields: CriteriaField[],
threshold: any,
earliestMs: number,
latestMs: number,
maxResults: number | undefined
earliestMs: number | null,
latestMs: number | null,
maxResults: number | undefined,
functionDescription?: string | undefined
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As noted above, you should be able to remove | undefined because of the ?.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated here 64ecedb

): Observable<RecordsForCriteria> {
const obj: RecordsForCriteria = { success: true, records: [] };

Expand Down Expand Up @@ -400,6 +402,19 @@ export function resultsServiceRxProvider(mlApiServices: MlApiServices) {
});
});

if (functionDescription !== undefined) {
const mlFunctionToPlotIfMetric =
functionDescription !== undefined
? aggregationTypeTransform.toML(functionDescription)
: functionDescription;

boolCriteria.push({
term: {
function_description: mlFunctionToPlotIfMetric,
},
});
}

return mlApiServices.results
.anomalySearch$(
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ export function resultsServiceProvider(
criteriaFields: any[],
earliestMs: number,
latestMs: number,
intervalMs: number
intervalMs: number,
actualPlotFunctionIfMetric?: string
): Promise<any>;
};
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
ANOMALY_SWIM_LANE_HARD_LIMIT,
SWIM_LANE_DEFAULT_PAGE_SIZE,
} from '../../explorer/explorer_constants';
import { aggregationTypeTransform } from '../../../../common/util/anomaly_utils';

/**
* Service for carrying out Elasticsearch queries to obtain data for the Ml Results dashboards.
Expand Down Expand Up @@ -1293,7 +1294,14 @@ export function resultsServiceProvider(mlApiServices) {
// criteria, time range, and aggregation interval.
// criteriaFields parameter must be an array, with each object in the array having 'fieldName'
// 'fieldValue' properties.
getRecordMaxScoreByTime(jobId, criteriaFields, earliestMs, latestMs, intervalMs) {
getRecordMaxScoreByTime(
jobId,
criteriaFields,
earliestMs,
latestMs,
intervalMs,
actualPlotFunctionIfMetric
) {
return new Promise((resolve, reject) => {
const obj = {
success: true,
Expand Down Expand Up @@ -1321,7 +1329,18 @@ export function resultsServiceProvider(mlApiServices) {
},
});
});
if (actualPlotFunctionIfMetric !== undefined) {
const mlFunctionToPlotIfMetric =
actualPlotFunctionIfMetric !== undefined
? aggregationTypeTransform.toML(actualPlotFunctionIfMetric)
: actualPlotFunctionIfMetric;

mustCriteria.push({
term: {
function_description: mlFunctionToPlotIfMetric,
},
});
}
mlApiServices.results
.anomalySearch(
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

export { PlotByFunctionControls } from './plot_function_controls';
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import React from 'react';
import { EuiFlexItem, EuiFormRow, EuiSelect } from '@elastic/eui';
import { i18n } from '@kbn/i18n';

const plotByFunctionOptions = [
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it necessary to translate these since they relate to Elasticsearch aggregations?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since these are not strict terms that are excluded in the translation guide, I'll keep these translations here.

{
value: 'mean',
text: i18n.translate('xpack.ml.timeSeriesExplorer.plotByAvgOptionLabel', {
defaultMessage: 'mean',
}),
},
{
value: 'min',
text: i18n.translate('xpack.ml.timeSeriesExplorer.plotByMinOptionLabel', {
defaultMessage: 'min',
}),
},
{
value: 'max',
text: i18n.translate('xpack.ml.timeSeriesExplorer.plotByMaxOptionLabel', {
defaultMessage: 'max',
}),
},
];
export const PlotByFunctionControls = ({
functionDescription,
setFunctionDescription,
}: {
functionDescription: undefined | string;
setFunctionDescription: (func: string) => void;
}) => {
if (functionDescription === undefined) return null;
return (
<EuiFlexItem grow={false}>
<EuiFormRow
label={i18n.translate('xpack.ml.timeSeriesExplorer.metricPlotByOption', {
defaultMessage: 'Function',
})}
>
<EuiSelect
options={plotByFunctionOptions}
value={functionDescription}
onChange={(e) => setFunctionDescription(e.target.value)}
aria-label={i18n.translate('xpack.ml.timeSeriesExplorer.metricPlotByOptionLabel', {
defaultMessage: 'Pick function to plot by (min, max, or average) if metric function',
})}
/>
</EuiFormRow>
</EuiFlexItem>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -1475,6 +1475,22 @@ class TimeseriesChartIntl extends Component {
});
}

if (marker.metricFunction) {
tooltipData.push({
label: i18n.translate(
'xpack.ml.timeSeriesExplorer.timeSeriesChart.metricActualPlotFunctionLabel',
{
defaultMessage: 'function',
}
),
value: marker.metricFunction,
seriesIdentifier: {
key: seriesKey,
},
valueAccessor: 'metric_function',
});
}

if (modelPlotEnabled === false) {
// Show actual/typical when available except for rare detectors.
// Rare detectors always have 1 as actual and the probability as typical.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

/**
* Updates criteria fields for API calls, e.g. getAnomaliesTableData
* @param detectorIndex
* @param entities
*/
export const getCriteriaFields = (detectorIndex: number, entities: Record<string, any>) => {
// Only filter on the entity if the field has a value.
const nonBlankEntities = entities.filter(
(entity: { fieldValue: any }) => entity.fieldValue !== null
);
return [
{
fieldName: 'detector_index',
fieldValue: detectorIndex,
},
...nonBlankEntities,
];
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import { i18n } from '@kbn/i18n';
import { mlResultsService } from '../services/results_service';
import { ToastNotificationService } from '../services/toast_notification_service';
import { getControlsForDetector } from './get_controls_for_detector';
import { getCriteriaFields } from './get_criteria_fields';
import { CombinedJob } from '../../../common/types/anomaly_detection_jobs';

/**
* Get the function description from the record with the highest anomaly score
*/
export const getFunctionDescription = async (
{
selectedDetectorIndex,
selectedEntities,
selectedJobId,
selectedJob,
}: {
selectedDetectorIndex: number;
selectedEntities: Record<string, any>;
selectedJobId: string;
selectedJob: CombinedJob;
},
toastNotificationService: ToastNotificationService
) => {
// if the detector's function is metric, fetch the highest scoring anomaly record
// and set to plot the function_description (avg/min/max) of that record by default
if (selectedJob?.analysis_config?.detectors[selectedDetectorIndex]?.function !== 'metric') return;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use ML_JOB_AGGREGATION.METRIC from common/constants/aggregation_types

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated here 64ecedb


const entityControls = getControlsForDetector(
selectedDetectorIndex,
selectedEntities,
selectedJobId
);
const criteriaFields = getCriteriaFields(selectedDetectorIndex, entityControls);
try {
const resp = await mlResultsService
.getRecordsForCriteria([selectedJob.job_id], criteriaFields, 0, null, null, 1)
.toPromise();
if (Array.isArray(resp?.records) && resp.records.length === 1) {
const highestScoringAnomaly = resp.records[0];
return highestScoringAnomaly?.function_description;
}
} catch (error) {
toastNotificationService.displayErrorToast(
error,
i18n.translate('xpack.ml.timeSeriesExplorer.highestAnomalyScoreErrorToastTitle', {
defaultMessage: 'An error occurred getting record with the highest anomaly score',
})
);
}
};
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ function getMetricData(
entityFields: EntityField[],
earliestMs: number,
latestMs: number,
intervalMs: number
intervalMs: number,
esMetricFunction?: string
): Observable<ModelPlotOutput> {
if (
isModelPlotChartableForDetector(job, detectorIndex) &&
Expand Down Expand Up @@ -88,7 +89,7 @@ function getMetricData(
chartConfig.datafeedConfig.indices,
entityFields,
chartConfig.datafeedConfig.query,
chartConfig.metricFunction,
esMetricFunction ?? chartConfig.metricFunction,
chartConfig.metricFieldName,
chartConfig.timeField,
earliestMs,
Expand Down
Loading