Module: NexosisApi::Client::Sessions

Included in:
NexosisApi::Client
Defined in:
lib/nexosis_api/client/sessions.rb

Overview

Session-based API operations

Instance Method Summary collapse

Instance Method Details

#create_anomalies_model(datasource_name, columns = {}, data_contains_anomalies = true) ⇒ NexosisApi::SessionResponse

Note:

The anomalies model session results will contain the anomalous observations when the session is complete.

Create a new model based on a data source

Parameters:

  • datasource_name (String)

    The datasource from which to build the model

  • columns (Hash) (defaults to: {})

    column metadata to modify roles, imputation, or target.

  • data_contains_anomalies (Boolean) (defaults to: true)

    Whether or not the source dataset contains anomalies (default is true)

Returns:

Raises:

Since:

  • 2.1.0



179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/nexosis_api/client/sessions.rb', line 179

def create_anomalies_model(datasource_name, columns = {}, data_contains_anomalies = true)
  model_url = '/sessions/model'
  body = {
    dataSourceName: datasource_name,
    predictionDomain: 'anomalies',
    extraParameters: {
      'containsAnomalies': data_contains_anomalies
    },
    columns: columns
  }
  response = self.class.post(model_url, headers: @headers, body: body.to_json)
  raise HttpException.new("There was a problem creating the model session: #{response.code}.", 'creating anomaly model session' ,response) unless response.success?
  NexosisApi::SessionResponse.new(response.parsed_response.merge(response.headers))
end

#create_classification_model(datasource_name, target_column, columns = {}, balance = true) ⇒ NexosisApi::SessionResponse

Note:

The anomalies model session results will contain the anomalous observations when the session is complete.

Create a new model based on a data source

Parameters:

  • datasource_name (String)

    The datasource from which to build the model

  • target_column (String)

    The column which will be predicted when using the model

  • columns (Hash) (defaults to: {})

    column metadata to modify roles, imputation, or target.

  • balance (Boolean) (defaults to: true)

    Whether or not to balance classes during model building (default is true)

Returns:

Raises:

Since:

  • 2.1.0



204
205
206
# File 'lib/nexosis_api/client/sessions.rb', line 204

def create_classification_model(datasource_name, target_column, columns = {}, balance = true)
  return create_model(datasource_name, target_column, columns, prediction_domain: 'classification', balance: balance)
end

#create_forecast_session(dataset_name, start_date, end_date, target_column = nil, result_interval = NexosisApi::TimeInterval::DAY, column_metadata = nil) ⇒ NexosisApi::SessionResponse

Note:

The time interval selected must be greater than or equal to the finest granularity of the data provided. For instance if your data includes many recoreds per hour, then you could request hour, day, or any other result interval. However, if your data includes only a few records per day or fewer, then a request for an hourly result interval will produce poor results.

Initiate a new forecast session based on a named dataset.

Parameters:

  • dataset_name (String)

    The name of the saved data set that has the data to forecast on.

  • start_date (DateTime)

    The starting date of the forecast period. Can be ISO 8601 string.

  • end_date (DateTime)

    The ending date of the forecast period. Can be ISO 8601 string.

  • target_column (String) (defaults to: nil)

    The name of the column for which you want predictions. Nil if defined in dataset.

  • result_interval (NexosisApi::TimeInterval) (defaults to: NexosisApi::TimeInterval::DAY)

    (optional) - The date/time interval (e.g. Day, Hour) at which predictions should be generated. So, if Hour is specified for this parameter you will get a Result record for each hour between startDate and endDate. If unspecified, we’ll generate predictions at a Day interval.

  • column_metadata (Array of NexosisApi::Column) (defaults to: nil)

    (optional) - specification for how to handle columns if different from existing metadata on dataset

Returns:



75
76
77
# File 'lib/nexosis_api/client/sessions.rb', line 75

def create_forecast_session(dataset_name, start_date, end_date, target_column = nil, result_interval = NexosisApi::TimeInterval::DAY,  = nil)
  create_session(dataset_name, start_date, end_date, target_column, nil, 'forecast', result_interval, )
end

#create_impact_session(dataset_name, start_date, end_date, event_name, target_column = nil, result_interval = NexosisApi::TimeInterval::DAY, column_metadata = nil) ⇒ NexosisApi::SessionResponse

Analyze impact for an event with data already saved to the API.

Parameters:

  • dataset_name (String)

    The name of the saved data set that has the data to forecast on.

  • start_date (DateTime)

    The starting date of the impactful event. Can be ISO 8601 string.

  • end_date (DateTime)

    The ending date of the impactful event. Can be ISO 8601 string.

  • event_name (String)

    The name of the event.

  • target_column (String) (defaults to: nil)

    The name of the column for which you want predictions. Nil if defined in datatset.

  • result_interval (NexosisApi::TimeInterval) (defaults to: NexosisApi::TimeInterval::DAY)

    (optional) - The date/time interval (e.g. Day, Hour) at which predictions should be generated. So, if Hour is specified for this parameter you will get a Result record for each hour between startDate and endDate. If unspecified, we’ll generate predictions at a Day interval.

  • column_metadata (Array of NexosisApi::Column) (defaults to: nil)

    (optional) - specification for how to handle columns if different from existing metadata on dataset

Returns:



89
90
91
# File 'lib/nexosis_api/client/sessions.rb', line 89

def create_impact_session(dataset_name, start_date, end_date, event_name, target_column = nil, result_interval = NexosisApi::TimeInterval::DAY,  = nil)
  create_session(dataset_name, start_date, end_date, target_column, event_name, 'impact', result_interval, )
end

#create_model(datasource_name, target_column, columns = {}, options = { prediction_domain: 'regression' }) ⇒ NexosisApi::SessionResponse

Note:
  • classifcation assumes balanced classes. The use of a ‘balance=false’ option

Create a new model based on a data source

indicates that no attempt should be made to sample the classes in balanced fashion.

Parameters:

  • datasource_name (String)

    The datasource from which to build the model

  • target_column (String)

    The column which will be predicted when using the model

  • columns (Hash) (defaults to: {})

    column metadata to modify roles, imputation, or target.

  • options (Hash) (defaults to: { prediction_domain: 'regression' })

    prediction_domain and or balance (true or false) indicator for classification

Returns:

Raises:

Since:

  • 1.3.0



152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/nexosis_api/client/sessions.rb', line 152

def create_model(datasource_name, target_column, columns = {}, options = { prediction_domain: 'regression' })
  model_url = '/sessions/model'
  body = {
    dataSourceName: datasource_name,
    targetColumn: target_column,
    predictionDomain: options[:prediction_domain].downcase
  }
  body.store(:extraParameters, { balance: options[:balance] }) if options.include?(:balance) && body[:predictionDomain] == 'classification'
  body.store(columns: columns) unless columns.empty?
  response = self.class.post(model_url, headers: @headers, body: body.to_json)
  if response.success?
    session_hash = { 'session' => response.parsed_response }.merge(response.headers)
    NexosisApi::SessionResponse.new(session_hash)
  else
    raise HttpException.new("There was a problem creating the model session: #{response.code}.", 'creating model session' ,response)
  end
end

#get_anomaly_scores(session_id, page = 0, page_size = 50) ⇒ NexosisApi::ScoreResult

Note:
  • This endpoint returns a 404 for requests of non-anomalies sessions

Get the observation anomaly score for a completed anomalies session

Parameters:

  • session_id (String)

    The unique id of the completed anomalies session

Returns:

  • (NexosisApi::ScoreResult)

    A session result with a list of each observation and score per column.

Raises:

Since:

  • 2.1.0



227
228
229
230
231
232
233
234
235
236
# File 'lib/nexosis_api/client/sessions.rb', line 227

def get_anomaly_scores(session_id, page = 0, page_size = 50)
  score_url = "/sessions/#{session_id}/results/anomalyScores"
  query = {
    page: page,
    pageSize: page_size
  }
  response = self.class.get(score_url, headers: @headers, query: query)
  raise HttpException.new("There was a problem getting the anomaly scores for session #{session_id}", 'getting anomaly scores', response) unless response.success?
  NexosisApi::AnomalyScores.new(response.parsed_response.merge(response.headers))
end

#get_class_scores(session_id, page_number = 0, page_size = 50) ⇒ NexosisApi::ScoreResult

Note:
  • This endpoint returns a 404 for requests of non-classification sessions

Get the observation class score for a completed classification session

Parameters:

  • session_id (String)

    The unique id of the completed classification session

  • page_number (Integer) (defaults to: 0)

    zero-based page number of results to retrieve

  • page_size (Integer) (defaults to: 50)

    Count of results to retrieve in each page (max 1000).

Returns:

  • (NexosisApi::ScoreResult)

    A session result with a list of each observation and score per column.

Raises:

Since:

  • 2.1.0



246
247
248
249
250
251
252
253
254
255
# File 'lib/nexosis_api/client/sessions.rb', line 246

def get_class_scores(session_id, page_number = 0, page_size = 50)
  score_url = "/sessions/#{session_id}/results/classScores"
  query = {
    page: page_number,
    pageSize: page_size
  }
  response = self.class.get(score_url, headers: @headers, query: query)
  raise HttpException.new("There was a problem getting the class scores for session #{session_id}", 'getting class scores', response) unless response.success?
  NexosisApi::ClassifierScores.new(response.parsed_response.merge(response.headers))
end

#get_confusion_matrix(session_id) ⇒ NexosisApi::ClassifierResult

Note:
  • This endpoint returns a 404 for requests of non-classification sessions

Get the confusion matrix for a completed classification session

Parameters:

  • session_id (String)

    The unique id of the completed classification session

Returns:

Raises:

Since:

  • 1.4.1



214
215
216
217
218
219
# File 'lib/nexosis_api/client/sessions.rb', line 214

def get_confusion_matrix(session_id)
  result_url = "/sessions/#{session_id}/results/confusionmatrix"
  response = self.class.get(result_url, headers: @headers)
  raise HttpException.new("There was a problem getting a confusion matrix for session #{session_id}", 'getting confusion matrix', response) unless response.success?
  NexosisApi::ClassifierResult.new(response.parsed_response.merge(response.headers))
end

#get_distance_metrics(session_id, page_number = 0, page_size = 50) ⇒ NexosisApi::AnomalyDistances

Note:

This method will return 404 when the session for the given session id does not have a prediction domain of ‘anomalies’

Get per result distance metric for anomaly detection sessions.

Parameters:

  • session_id (String)

    The unique id of the completed session

  • page_number (Integer) (defaults to: 0)

    zero-based page number of results to retrieve

  • page_size (Integer) (defaults to: 50)

    Count of results to retrieve in each page (max 1000).

Returns:

Raises:

See Also:

Since:

  • 2.4.0



285
286
287
288
289
290
291
292
293
294
# File 'lib/nexosis_api/client/sessions.rb', line 285

def get_distance_metrics(session_id, page_number = 0, page_size = 50)
  distance_url = "/sessions/#{session_id}/results/mahalanobisdistances"
  query = {
    page: page_number,
    pageSize: page_size
  }
  response = self.class.get(distance_url, headers: @headers, query: query)
  raise HttpException.new("There was a problem getting the distance metrics for session #{session_id}", 'getting distance metrics', response) unless response.success?
  NexosisApi::AnomalyDistances.new(response.parsed_response.merge(response.headers))
end

#get_feature_importance(session_id, page_number = 0, page_size = 50) ⇒ NexosisApi::FeatureImportance

Note:

The score returned here is calculated before algorithm selection and so is not algorithm specific. For algorithms

Note:

Those sessions which will provide scores have the supports_feature_importance attribute set True. Others will 404 at this endpoint.

Get a feature importance score for each column in the data source used in a session that can return internal scores you need to use the champion endpoints.

Parameters:

  • session_id (String)

    The unique id of the completed session

  • page_number (Integer) (defaults to: 0)

    zero-based page number of results to retrieve

  • page_size (Integer) (defaults to: 50)

    Count of results to retrieve in each page (max 1000).

Returns:

Raises:

Since:

  • 2.4.0



266
267
268
269
270
271
272
273
274
275
# File 'lib/nexosis_api/client/sessions.rb', line 266

def get_feature_importance(session_id, page_number = 0, page_size = 50)
  importance_url = "/sessions/#{session_id}/results/featureimportance"
  query = {
    page: page_number,
    pageSize: page_size
  }
  response = self.class.get(importance_url, headers: @headers, query: query)
  raise HttpException.new("There was a problem getting the feature importance scores for session #{session_id}", 'getting feature importance', response) unless response.success?
  NexosisApi::FeatureImportance.new(response.parsed_response.merge(response.headers))
end

#get_session(session_id) ⇒ NexosisApi::Session

Get a specific session by id.

Parameters:

  • session_id (String)

    the Guid string returned in a previous session request

Returns:

Raises:



134
135
136
137
138
139
# File 'lib/nexosis_api/client/sessions.rb', line 134

def get_session(session_id)
  session_url = "/sessions/#{session_id}"
  response = self.class.get(session_url, @options)
  return NexosisApi::Session.new(response.parsed_response) if response.success?
  raise HttpException.new("There was a problem getting the session: #{response.code}.", "getting session #{session_id}" ,response)
end

#get_session_result_data(session_id, page = 0, page_size = 50, options = {}) ⇒ NexosisApi::SessionResult

Get the results of the session.

Parameters:

  • session_id (String)

    the Guid string returned in a previous session request

  • page (Integer) (defaults to: 0)

    optionally provide a page number for paging. Defaults to 0 (first page).

  • page_size (Integer) (defaults to: 50)

    optionally provide a page size to limit the total number of results. Defaults to 50, max 1000

  • options (Hash) (defaults to: {})

    as_csv [Boolean] to indicate whether results should be returned in csv format; prediction_interval [Float] one of the available prediction intervals for the session.

Returns:

Raises:

Since:

  • 2.1.0



114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/nexosis_api/client/sessions.rb', line 114

def get_session_result_data(session_id, page = 0, page_size = 50, options = {})
  session_result_url = "/sessions/#{session_id}/results"
  @headers['Accept'] = 'text/csv' if options[:as_csv]
  query = { 'page' => page, 'pageSize' => page_size }
  query.store('predictionInterval', options[:prediction_interval]) unless options[:prediction_interval].nil?
  response = self.class.get(session_result_url, headers: @headers, query: query)
  @headers.delete('Accept')
  if (response.success?)
    return response.body if options[:as_csv]
    NexosisApi::SessionResult.new(response.parsed_response)
  else
    raise HttpException.new("There was a problem getting the session: #{response.code}.", "get results for session #{session_id}" ,response)
  end
end

#get_session_results(session_id, as_csv = false, prediction_interval = nil) ⇒ NexosisApi::SessionResult

Deprecated.

Get the results of the session.

Parameters:

  • session_id (String)

    the Guid string returned in a previous session request

  • as_csv (Boolean) (defaults to: false)

    indicate whether results should be returned in csv format

  • prediction_interval (Float) (defaults to: nil)

    one of the available prediction intervals for the session.

Returns:

Raises:



101
102
103
# File 'lib/nexosis_api/client/sessions.rb', line 101

def get_session_results(session_id, as_csv = false, prediction_interval = nil)
  get_session_result_data(session_id, 0, 50, {as_csv: as_csv, prediction_interval: prediction_interval})
end

#get_timeseries_outliers(session_id, page_number = 0, page_size = 50) ⇒ Object

Raises:



296
297
298
299
300
301
302
303
304
305
# File 'lib/nexosis_api/client/sessions.rb', line 296

def get_timeseries_outliers(session_id, page_number = 0, page_size = 50)
  outlier_url = "/sessions/#{session_id}/results/outliers"
  query = {
    page: page_number,
    pageSize: page_size
  }
  response = self.class.get(outlier_url, headers: @headers, query: query)
  raise HttpException.new("There was a problem getting the outliers for session #{session_id}", 'getting outliers', response) unless response.success?
  NexosisApi::TimeseriesOutliers.new(response.parsed_response.merge(response.headers))
end

#list_sessions(session_list_query = NexosisApi::SessionListQuery.new) ⇒ NexosisApi::PagedArray of NexosisApi::SessionResponse

Note:

query parameters hash members are dataset_name, event_name, model_id, sort_by, sort_order, requested_before_date, and requested_after_date. After and before dates refer to the session requested date.

List sessions previously submitted

Examples:

query for just one dataset

sessions = NexosisApi.client.list_sessions :dataset_name => 'MyDataset'

Parameters:

  • session_list_query (NexosisApi::SessionListQuery) (defaults to: NexosisApi::SessionListQuery.new)

    optionally provide query parameters to limit the search of sessions.

Returns:

Raises:

See Also:



22
23
24
25
26
27
28
29
30
31
32
# File 'lib/nexosis_api/client/sessions.rb', line 22

def list_sessions(session_list_query = NexosisApi::SessionListQuery.new)
  sessions_url = '/sessions'
  response = self.class.get(sessions_url, headers: @headers, query: session_list_query.query_parameters)
  raise HttpException.new('Could not retrieve sessions',
                          "Get all sessions with query #{session_list_query.query_parameters}",
                          response) unless response.success?
  NexosisApi::PagedArray.new(response.parsed_response, response.parsed_response['items'].map do |session_hash|
    response_hash = { 'session' => session_hash }.merge(response.headers)
    NexosisApi::SessionResponse.new(response_hash)
  end)
end

#remove_session(session_id) ⇒ Object

Remove a session

Parameters:

  • session_id (String)

    required session identifier

Raises:



38
39
40
41
42
43
44
45
46
# File 'lib/nexosis_api/client/sessions.rb', line 38

def remove_session(session_id)
  if (session_id.to_s.empty?)
    raise ArgumentError 'session_id cannot be empty or nil'
  end
  session_url = "/sessions/#{session_id}"
  response = self.class.delete(session_url, headers: @headers)
  return if response.success?
  raise HttpException.new('Could not delete session with given id', "remove session with id #{session_id}", response)
end

#remove_sessions(query_options = {}) ⇒ Object

Note:

query parameters hash members are type, dataset_name, event_name, start_date, and end_date. Start and end dates refer to the session requested date. Results are not removed but then can only be accessed by dataset name

Remove sessions that have been run. All query options are optional and will be used to limit the sessions removed.

Examples:

Remove all sessions based on a dataset by name

NexosisApi.client.remove_sessions :dataset_name => 'existing_dataset'

Parameters:

  • query_options (Hash) (defaults to: {})

    optionally provide query parametes to limit the set of sessions removed.

Raises:



56
57
58
59
60
61
# File 'lib/nexosis_api/client/sessions.rb', line 56

def remove_sessions(query_options = {})
  sessions_url = '/sessions'
  response = self.class.delete(sessions_url, :headers => @headers, :query => get_query_from_options(query_options))
  return if response.success?
  raise HttpException.new('Could not remove sessions', "Remove sessions with query #{query_options.to_s}",response)
end