diff --git a/include/HostMonitoringTemplate.h b/include/HostMonitoringTemplate.h index 64a65670cb..4fc03e29ba 100644 --- a/include/HostMonitoringTemplate.h +++ b/include/HostMonitoringTemplate.h @@ -35,10 +35,6 @@ public: {} int from_template(const Template &tmpl); - - // todo if needed add attribute getters and setters: - // uint64_t used_cpu() const - // void set_used_cpu(uint64_t used_cpu) }; /** diff --git a/install.sh b/install.sh index 8901618713..6dc43988c5 100755 --- a/install.sh +++ b/install.sh @@ -362,6 +362,8 @@ VAR_DIRS="$VAR_LOCATION/remotes \ $VAR_LOCATION/remotes/etc/vnm \ $VAR_LOCATION/remotes/im \ $VAR_LOCATION/remotes/im/lib \ + $VAR_LOCATION/remotes/im/lib/python \ + $VAR_LOCATION/remotes/im/lib/python/pyoneai \ $VAR_LOCATION/remotes/im/kvm.d \ $VAR_LOCATION/remotes/im/kvm-probes.d/host/beacon \ $VAR_LOCATION/remotes/im/kvm-probes.d/host/monitor \ @@ -570,6 +572,8 @@ INSTALL_FILES=( MADS_LIB_FILES:$LIB_LOCATION/mads IM_PROBES_FILES:$VAR_LOCATION/remotes/im IM_PROBES_LIB_FILES:$VAR_LOCATION/remotes/im/lib + IM_PROBES_LIB_PYTHON_FILES:$VAR_LOCATION/remotes/im/lib/python + IM_PROBES_LIB_PYONEAI_FILES:$VAR_LOCATION/remotes/im/lib/python/pyoneai IM_PROBES_KVM_FILES:$VAR_LOCATION/remotes/im/kvm.d IM_PROBES_QEMU_FILES:$VAR_LOCATION/remotes/im/qemu.d IM_PROBES_DUMMY_FILES:$VAR_LOCATION/remotes/im/dummy.d @@ -1216,6 +1220,16 @@ IM_PROBES_LIB_FILES="\ src/im_mad/remotes/lib/domain.rb \ src/im_mad/remotes/lib/process_list.rb" +IM_PROBES_LIB_PYTHON_FILES="\ + src/im_mad/remotes/lib/python/models/ \ + src/im_mad/remotes/lib/python/prediction.py \ + src/im_mad/remotes/lib/python/prediction.sh" + +IM_PROBES_LIB_PYONEAI_FILES="\ + src/im_mad/remotes/lib/python/pyoneai/__init__.py \ + src/im_mad/remotes/lib/python/pyoneai/core/ \ + src/im_mad/remotes/lib/python/pyoneai/ml/" + # KVM PROBES IM_PROBES_KVM_FILES="\ src/im_mad/remotes/kvm.d/monitord-client_control.sh \ @@ -1227,6 +1241,7 @@ IM_PROBES_KVM_HOST_BEACON_FILES="\ IM_PROBES_KVM_HOST_MONITOR_FILES="\ src/im_mad/remotes/kvm-probes.d/host/monitor/linux_usage.rb \ + src/im_mad/remotes/kvm-probes.d/host/monitor/prediction.sh \ src/im_mad/remotes/kvm-probes.d/host/monitor/numa_usage.rb" IM_PROBES_KVM_HOST_SYSTEM_FILES="\ @@ -1255,6 +1270,7 @@ IM_PROBES_KVM_VM_SNAPSHOT_FILES="\ IM_PROBES_ETC_KVM_PROBES_FILES="\ src/im_mad/remotes/kvm-probes.d/pci.conf \ src/im_mad/remotes/kvm-probes.d/guestagent.conf \ + src/im_mad/remotes/kvm-probes.d/forecast.conf \ src/im_mad/remotes/lib/probe_db.conf" IM_PROBES_QEMU_FILES="\ diff --git a/src/cli/one_helper/onehost_helper.rb b/src/cli/one_helper/onehost_helper.rb index 489adb19de..6d950317d3 100644 --- a/src/cli/one_helper/onehost_helper.rb +++ b/src/cli/one_helper/onehost_helper.rb @@ -78,12 +78,24 @@ class OneHostHelper < OpenNebulaHelper::OneHelper VERSION_XPATH = "#{TEMPLATE_XPATH}/VERSION" MONITORING = { - 'FREE_CPU' => 'CAPACITY', - 'FREE_MEMORY' => 'CAPACITY', - 'USED_CPU' => 'CAPACITY', - 'USED_MEMORY' => 'CAPACITY', - 'NETRX' => 'SYSTEM', - 'NETTX' => 'SYSTEM' + 'FREE_CPU' => 'CAPACITY', + 'FREE_CPU_FORECAST' => 'CAPACITY', + 'FREE_CPU_FORECAST_FAR' => 'CAPACITY', + 'FREE_MEMORY' => 'CAPACITY', + 'FREE_MEMORY_FORECAST' => 'CAPACITY', + 'FREE_MEMORY_FORECAST_FAR' => 'CAPACITY', + 'USED_CPU' => 'CAPACITY', + 'USED_CPU_FORECAST' => 'CAPACITY', + 'USED_CPU_FORECAST_FAR' => 'CAPACITY', + 'USED_MEMORY' => 'CAPACITY', + 'USED_MEMORY_FORECAST' => 'CAPACITY', + 'USED_MEMORY_FORECAST_FAR' => 'CAPACITY', + 'NETRX' => 'SYSTEM', + 'NETRX_FORECAST' => 'SYSTEM', + 'NETRX_FORECAST_FAR' => 'SYSTEM', + 'NETTX' => 'SYSTEM', + 'NETTX_FORECAST' => 'SYSTEM', + 'NETTX_FORECAST_FARR' => 'SYSTEM' } def self.rname @@ -456,9 +468,6 @@ class OneHostHelper < OpenNebulaHelper::OneHelper # Different available size units units = ['K', 'M', 'G', 'T'] - # Attrs that need units conversion - attrs = ['FREE_MEMORY', 'USED_MEMORY'] - if unit && !units.include?(unit) STDERR.puts "Invalid unit `#{unit}`" exit(-1) @@ -501,7 +510,7 @@ class OneHostHelper < OpenNebulaHelper::OneHelper # Parse dcollected data x = monitoring_data.collect {|v| Time.at(v[0].to_i).strftime('%H:%M') } y = monitoring_data.collect do |v| - if attrs.include?(attr) + if attr.match(/_MEMORY/) # GB is the default unit v = OpenNebulaHelper.bytes_to_unit(v[1].to_i, unit).round(2) "#{v} #{unit}B" @@ -512,7 +521,7 @@ class OneHostHelper < OpenNebulaHelper::OneHelper title = '' title << "Host #{host.id} #{attr} " - title << "in #{unit}B " if unit && attrs.include?(attr) + title << "in #{unit}B " if unit && attr.match(/_MEMORY/) title << "from #{start_d} to #{end_d}" x = x.last(n_elems) diff --git a/src/cli/one_helper/onevm_helper.rb b/src/cli/one_helper/onevm_helper.rb index 2847325e9f..16a3e7b15c 100644 --- a/src/cli/one_helper/onevm_helper.rb +++ b/src/cli/one_helper/onevm_helper.rb @@ -210,14 +210,6 @@ class OneVMHelper < OpenNebulaHelper::OneHelper end end - VirtualMachine::EXTERNAL_IP_ATTRS.each do |attr| - external_ip = vm['MONITORING'][attr] - - if !external_ip.nil? && !ips.include?(external_ip) - ips.push(external_ip) - end - end - return '--' if ips.empty? ips.join(',') @@ -743,47 +735,85 @@ class OneVMHelper < OpenNebulaHelper::OneHelper puts - CLIHelper.print_header(str_h1 % 'VIRTUAL MACHINE MONITORING', false) - vm_monitoring = vm_hash['VM']['MONITORING'] - # Find out if it is a hybrid VM to avoid showing local IPs - is_hybrid = false - vm_monitoring.each do |key, _value| - if VirtualMachine::EXTERNAL_IP_ATTRS.include? key - is_hybrid = true - end - end + unit_lambda = ->(v) { OpenNebulaHelper.unit_to_str(v.to_i, {}) } + unitM_lambda = ->(v) { OpenNebulaHelper.unit_to_str(v.to_i / 1024, {}) } - order_attrs = ['CPU', 'MEMORY', 'NETTX', 'NETRX'] + order_attrs = { + 'CPU' => nil, + 'MEMORY' => unit_lambda, + 'NETTX' => unitM_lambda, + 'NETRX' => unitM_lambda, + 'DISKRDBYTES' => unit_lambda, + 'DISKRDIOPS' => nil, + 'DISKWRBYTES' => unit_lambda, + 'DISKWRIOPS' => nil + } vm_monitoring_sort = [] - order_attrs.each do |key| - if (val = vm_monitoring.delete(key)) - vm_monitoring_sort << [key, val] + order_attrs.each do |key, format| + val = vm_monitoring.delete(key) + + next unless val + + val = format.call(val) if format + render = "#{val}" + + forecast = [] + + ["#{key}_FORECAST", "#{key}_FORECAST_FAR"].each do |fk| + fv = vm_monitoring.delete(fk) + fv = format.call(fv) if format && fv + + fv ||= '-' + + forecast << fv end + + vm_monitoring_sort << { 'NAME' => key, + 'VALUE' => val, + 'FORECAST' => forecast[0], + 'FORECAST_FAR' => forecast[1] } end - vm_monitoring_sort.sort_by {|a| a[0] } + vm_monitoring_sort.sort_by {|a| a['NAME'] } - filter_attrs = ['STATE', 'DISK_SIZE', 'SNAPSHOT_SIZE'] + filter_attrs = ['STATE', 'DISK_SIZE', 'SNAPSHOT_SIZE', 'ID', 'TIMESTAMP'] vm_monitoring.each do |key, val| if !filter_attrs.include?(key) - vm_monitoring_sort << [key, val] + vm_monitoring_sort << { 'NAME' => key, + 'VALUE' => val } end end - vm_monitoring_sort.each do |k, v| - if k == 'MEMORY' - puts format(str, k, OpenNebulaHelper.unit_to_str(v.to_i, {})) - elsif k =~ /NET.X/ - puts format(str, k, - OpenNebulaHelper.unit_to_str(v.to_i / 1024, {})) - else - puts format(str, k, v) - end + tstamp = begin + Time.at(vm_monitoring.delete('TIMESTAMP').to_i).ctime + rescue + '' end + CLIHelper.print_header(str_h1 % "VIRTUAL MACHINE MONITORING [#{tstamp}]", false) + CLIHelper::ShowTable.new(nil, self) do + column :METRIC, '', :left, :size => 15 do |d| + d['NAME'] + end + + column :VALUE, '', :left, :size => 15 do |d| + d['VALUE'] + end + + column :FORECAST, '', :left, :size => 15 do |d| + d['FORECAST'] || '' + end + + column :FORECAST_FAR, '', :left, :size => 15 do |d| + d['FORECAST_FAR'] || '' + end + + default :METRIC, :VALUE, :FORECAST, :FORECAST_FAR + end.show(vm_monitoring_sort, {}) + puts CLIHelper.print_header(str_h1 % 'PERMISSIONS', false) @@ -928,27 +958,9 @@ class OneVMHelper < OpenNebulaHelper::OneHelper sg_nics.compact! end - # This variable holds the extra IP's got from monitoring. Right - # now it adds GUEST_IP and GUEST_IP_ADDRESSES from vcenter - # monitoring. If other variables hold IPs just add them to this - # array. Duplicate IPs are not shown. - extra_ips = [] - - if (val = vm['/VM/MONITORING/GUEST_IP']) && (val && !val.empty?) - extra_ips << val - end - - if (val = vm['/VM/MONITORING/GUEST_IP_ADDRESSES']) && (val && !val.empty?) - extra_ips += val.split(',') - end - - extra_ips.uniq! - ['NIC', 'NIC_ALIAS'].each do |type| next unless vm.has_elements?("/VM/TEMPLATE/#{type}") || vm.has_elements?('/VM/TEMPLATE/PCI[NIC_ID>-1]') || - !extra_ips.empty? - puts CLIHelper.print_header( str_h1 % "VM #{type == 'NIC' ? 'NICS' : 'ALIAS'}", false @@ -959,8 +971,6 @@ class OneVMHelper < OpenNebulaHelper::OneHelper 'MAC' => '-', 'BRIDGE' => '-' } - shown_ips = [] - array_id = 0 vm_nics = [vm_hash['VM']['TEMPLATE'][type]] @@ -983,8 +993,6 @@ class OneVMHelper < OpenNebulaHelper::OneHelper ['EXTERNAL_IP', 'IP6_LINK', 'IP6_ULA', 'IP6_GLOBAL', 'IP6'].each do |attr| next unless nic.key?(attr) - shown_ips << nic[attr] - ipstr = { 'IP' => nic.delete(attr), 'CLI_DONE' => true, 'DOUBLE_ENTRY' => true } @@ -997,8 +1005,6 @@ class OneVMHelper < OpenNebulaHelper::OneHelper 'VROUTER_IP6_GLOBAL'].each do |attr| next unless nic.key?(attr) - shown_ips << nic[attr] - ipstr = { 'IP' => nic.delete(attr) + ' (VRouter)', 'CLI_DONE' => true, 'DOUBLE_ENTRY' => true } @@ -1007,25 +1013,10 @@ class OneVMHelper < OpenNebulaHelper::OneHelper array_id += 1 end - shown_ips << nic['IP'] if nic.key?('IP') - shown_ips << nic['EXTERNAL_IP'] if nic.key?('EXTERNAL_IP') - nic.merge!(nic_default) {|_k, v1, _v2| v1 } array_id += 1 end - extra_ips -= shown_ips - - # Add extra IPs to the VM NICS table - extra_ips.each do |ip| - vm_nics << { - 'NIC_ID' => '-', - 'IP' => ip, - 'NETWORK' => 'Additional IP', - 'BRIDGE' => '-' - } - end - CLIHelper::ShowTable.new(nil, self) do column :ID, '', :size => 3 do |d| if d['DOUBLE_ENTRY'] @@ -1103,7 +1094,7 @@ class OneVMHelper < OpenNebulaHelper::OneHelper vm.delete_element('/VM/TEMPLATE/NIC') while vm.has_elements?('/VM/TEMPLATE/NIC') end - if vm.has_elements?('/VM/TEMPLATE/SECURITY_GROUP_RULE') && !is_hybrid + if vm.has_elements?('/VM/TEMPLATE/SECURITY_GROUP_RULE') puts CLIHelper.print_header(str_h1 % 'SECURITY', false) puts diff --git a/src/host/HostMonitoringTemplate.cc b/src/host/HostMonitoringTemplate.cc index 373ee25bd1..2cd8c83dc1 100644 --- a/src/host/HostMonitoringTemplate.cc +++ b/src/host/HostMonitoringTemplate.cc @@ -28,25 +28,45 @@ using namespace std; /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ +template +static void get_set(const Template &tmpl, Template *dst, + const std::map& key_map) +{ + T value; + + for (const auto& [probe_k, monitor_k] : key_map) + { + if (tmpl.get(probe_k, value)) + { + dst->add(monitor_k, value); + } + } +} + int CapacityMonitoring::from_template(const Template &tmpl) { - unsigned long value; - if (tmpl.get("FREECPU", value)) - { - add("FREE_CPU", value); - } - if (tmpl.get("USEDCPU", value)) - { - add("USED_CPU", value); - } - if (tmpl.get("FREEMEMORY", value)) - { - add("FREE_MEMORY", value); - } - if (tmpl.get("USEDMEMORY", value)) - { - add("USED_MEMORY", value); - } + static std::map capacity_map = { + {"FREECPU", "FREE_CPU"}, + {"USEDCPU", "USED_CPU"}, + {"FREEMEMORY", "FREE_MEMORY"}, + {"USEDMEMORY", "USED_MEMORY"}, + }; + + static std::map forecast_map = { + {"FREECPU_FORECAST", "FREE_CPU_FORECAST"}, + {"FREECPU_FORECAST_FAR", "FREE_CPU_FORECAST_FAR"}, + {"USEDCPU_FORECAST", "USED_CPU_FORECAST"}, + {"USEDCPU_FORECAST_FAR", "USED_CPU_FORECAST_FAR"}, + {"FREEMEMORY_FORECAST", "FREE_MEMORY_FORECAST"}, + {"FREEMEMORY_FORECAST_FAR", "FREE_MEMORY_FORECAST_FAR"}, + {"USEDMEMORY_FORECAST", "USED_MEMORY_FORECAST"}, + {"USEDMEMORY_FORECAST_FAR", "USED_MEMORY_FORECAST_FAR"} + }; + + get_set(tmpl, this, capacity_map); + + get_set(tmpl, this, forecast_map); + return 0; } @@ -55,19 +75,23 @@ int CapacityMonitoring::from_template(const Template &tmpl) int SystemMonitoring::from_template(const Template &tmpl) { - unsigned long value; - if (tmpl.get("CPUSPEED", value)) - { - add("CPU_SPEED", value); - } - if (tmpl.get("NETTX", value)) - { - add("NETTX", value); - } - if (tmpl.get("NETRX", value)) - { - add("NETRX", value); - } + static std::map system_map = { + {"CPUSPEED", "CPU_SPEED"}, + {"NETTX", "NETTX"}, + {"NETRX", "NETRX"} + }; + + static std::map forecast_map = { + {"NETTX_FORECAST", "NETTX_FORECAST"}, + {"NETTX_FORECAST_FAR", "NETTX_FORECAST_FAR"}, + {"NETRX_FORECAST", "NETRX_FORECAST"}, + {"NETRX_FORECAST_FAR", "NETRX_FORECAST_FAR"} + }; + + get_set(tmpl, this, system_map); + + get_set(tmpl, this, forecast_map); + return 0; } diff --git a/src/im_mad/remotes/kvm-probes.d/forecast.conf b/src/im_mad/remotes/kvm-probes.d/forecast.conf new file mode 100644 index 0000000000..ff41fdbcfc --- /dev/null +++ b/src/im_mad/remotes/kvm-probes.d/forecast.conf @@ -0,0 +1,13 @@ +# This section is related to the configuration for DB retention and forecast period +# related to the hosts +host: + db_retention: 4 # Number of weeks + forecast_period: 5 # Number of minutes + forecast_far_period: 720 # Number of hours + +# This section is related to the configuration for DB retention and forecast +# related to the virtual machines +virtualmachine: + db_retention: 2 # Number of weeks + forecast_period: 5 # Number of minutes + forecast_far_period: 48 # Number of hours diff --git a/src/im_mad/remotes/kvm-probes.d/host/monitor/linux_usage.rb b/src/im_mad/remotes/kvm-probes.d/host/monitor/linux_usage.rb index ad27ab1aa1..95754fd691 100755 --- a/src/im_mad/remotes/kvm-probes.d/host/monitor/linux_usage.rb +++ b/src/im_mad/remotes/kvm-probes.d/host/monitor/linux_usage.rb @@ -19,3 +19,4 @@ require_relative '../../../lib/linux' LinuxHost.usage('kvm') +LinuxHost.to_sql('kvm') diff --git a/src/im_mad/remotes/kvm-probes.d/host/monitor/prediction.sh b/src/im_mad/remotes/kvm-probes.d/host/monitor/prediction.sh new file mode 100755 index 0000000000..0a7fd735c9 --- /dev/null +++ b/src/im_mad/remotes/kvm-probes.d/host/monitor/prediction.sh @@ -0,0 +1,21 @@ +#!/bin/bash + +# -------------------------------------------------------------------------- # +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems # +# # +# Licensed under the Apache License, Version 2.0 (the "License"); you may # +# not use this file except in compliance with the License. You may obtain # +# a copy of the License at # +# # +# http://www.apache.org/licenses/LICENSE-2.0 # +# # +# Unless required by applicable law or agreed to in writing, software # +# distributed under the License is distributed on an "AS IS" BASIS, # +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # +# See the License for the specific language governing permissions and # +# limitations under the License. # +#--------------------------------------------------------------------------- # + +PYTHON_PATH=/var/tmp/one/im/lib/python + +PYTHONPATH=$PYTHON_PATH python3 $PYTHON_PATH/prediction.py --entity host,0,0,/var/tmp/one --pythonpath $PYTHON_PATH diff --git a/src/im_mad/remotes/lib/domain.rb b/src/im_mad/remotes/lib/domain.rb index 2aae222544..560ac4f08b 100644 --- a/src/im_mad/remotes/lib/domain.rb +++ b/src/im_mad/remotes/lib/domain.rb @@ -16,6 +16,9 @@ # limitations under the License. # #--------------------------------------------------------------------------- # +require 'open3' +require 'yaml' + #------------------------------------------------------------------------------- # This class represents a base domain, information includes: #------------------------------------------------------------------------------- @@ -23,9 +26,34 @@ class BaseDomain attr_reader :vm, :name + MONITOR_KEYS = [ + 'cpu', + 'memory', + 'netrx', + 'nettx', + 'diskrdbytes', + 'diskwrbytes', + 'diskrdiops', + 'diskwriops' + ] + + DB_MONITOR_KEYS = MONITOR_KEYS.clone + DB_MONITOR_KEYS.freeze + + DB_NAME = 'metrics.db' + def initialize(name) @name = name @vm = {} + + begin + path = "#{__dir__}/../../etc/im/kvm-probes.d/forecast.conf" + conf = YAML.load_file(path) + + @db_retention = conf['vm']['db_retention'] + rescue StandardError + @db_retention = 4 # number of weeks + end end # Get domain attribute by name. @@ -64,9 +92,62 @@ class BaseDomain Base64.strict_encode64(mon_s) end - MONITOR_KEYS = ['cpu', 'memory', 'netrx', 'nettx', 'diskrdbytes', 'diskwrbytes', 'diskrdiops', - 'diskwriops'] + def store_metric_db(db, vm_id, metric_name, timestamp, value) + table_name = "virtualmachine_#{vm_id}_#{metric_name}_monitoring" + create_table_query = <<-SQL + CREATE TABLE IF NOT EXISTS #{table_name} ( + TIMESTAMP INTEGER PRIMARY KEY, + VALUE REAL NOT NULL + ); + SQL + db.execute(create_table_query) + + create_trigger_query = <<-SQL + CREATE TRIGGER IF NOT EXISTS delete_old_records_#{table_name} + AFTER INSERT ON #{table_name} + BEGIN + DELETE FROM #{table_name} + WHERE TIMESTAMP < strftime('%s', 'now', '-#{@db_retention} week'); + END; + SQL + db.execute(create_trigger_query) + + insert_query = <<-SQL + INSERT INTO #{table_name} (TIMESTAMP, VALUE) + VALUES (?, ?); + SQL + db.execute(insert_query, [timestamp, value]) + end + + # Write to metric values to the VM SQL DB (named metrics.db) + # The is stored in the VM folder of the system datastore + def to_sql + return unless @vm[:system_datastore] + + db = SQLite3::Database.new(File.join(@vm[:system_datastore], DB_NAME)) + + timestamp = Time.now.to_i + + DB_MONITOR_KEYS.each do |k| + next unless @vm[k.to_sym] + + store_metric_db(db, @vm[:id], k, timestamp, @vm[k.to_sym]) + end + + db.close + rescue StandardError + end + + def predictions + base = '/var/tmp/one/im/lib/python/prediction.sh' + cmd = "#{base} --entity virtualmachine,#{@vm[:id]},#{@vm[:uuid]},#{@vm[:system_datastore]}" + + o, _e, s = Open3.capture3 cmd + + return o if s.success? + rescue StandardError + end end #------------------------------------------------------------------------------- @@ -121,6 +202,24 @@ class BaseDomains mon_s end + # Write VM information into the VM timeseries DB + def to_sql + @vms.each do |_uuid, vm| + vm.to_sql + end + end + + # Return a message string with VM monitor information and predictions + def to_monitor_predictions + mon_s = '' + + @vms.each do |_uuid, vm| + mon_s << vm.predictions + end + + mon_s + end + private # Generic build method for the info list. It filters and builds the diff --git a/src/im_mad/remotes/lib/kvm.rb b/src/im_mad/remotes/lib/kvm.rb index 6c041fdd6d..0705186a00 100644 --- a/src/im_mad/remotes/lib/kvm.rb +++ b/src/im_mad/remotes/lib/kvm.rb @@ -21,6 +21,7 @@ require 'base64' require 'json' require 'yaml' require 'rexml/document' +require 'sqlite3' require_relative 'process_list' require_relative 'domain' @@ -198,6 +199,16 @@ class Domain < BaseDomain @vm[:state] = state @vm[:reason] = reason + # VM system datastore path + xml, _e, s = KVM.virsh(:dumpxml, @name) + + @vm[:system_datastore] = begin + doc = REXML::Document.new(xml) + doc.elements['/domain/metadata/one:vm/one:system_datastore']&.text + rescue 'StandardError' + nil + end if s.success? + ga_stats io_stats end @@ -387,7 +398,8 @@ module DomainList domains = KVMDomains.new domains.info - domains.to_monitor + domains.to_sql + domains.to_monitor_predictions end def self.wilds_info diff --git a/src/im_mad/remotes/lib/linux.rb b/src/im_mad/remotes/lib/linux.rb index 081b61ca7d..4e2ddead9e 100644 --- a/src/im_mad/remotes/lib/linux.rb +++ b/src/im_mad/remotes/lib/linux.rb @@ -17,6 +17,7 @@ #--------------------------------------------------------------------------- # require 'English' +require 'sqlite3' # Gathers compute and network resource information about the host class LinuxHost @@ -27,6 +28,20 @@ class LinuxHost CPUINFO = 'lscpu | grep CPU' MEMINFO = 'cat /proc/meminfo | grep MemTotal' + DB_MONITOR_KEYS = { + 'usedcpu' => ->(m) { m.cpu[:used] }, + 'freecpu' => ->(m) { m.cpu[:free] }, + 'usedmemory' => ->(m) { m.memory[:used] }, + 'freememory' => ->(m) { m.memory[:free] }, + 'netrx' => ->(m) { m.net[:rx] }, + 'nettx' => ->(m) { m.net[:tx] } + } + + DB_PATH = '/var/tmp/one' + DB_NAME = 'metrics.db' + + HOST_ID = 0 + ###### # First, get all the posible info out of virsh # TODO : use virsh freecell when available @@ -35,6 +50,15 @@ class LinuxHost attr_accessor :cpu, :memory, :net, :cgversion def initialize + begin + path = "#{__dir__}/../../etc/im/kvm-probes.d/forecast.conf" + conf = YAML.load_file(path) + + @db_retention = conf['host']['db_retention'] + rescue StandardError + @db_retention = 4 # number of weeks + end + cpuinfo = `#{CPUINFO}` exit(-1) if $CHILD_STATUS.exitstatus != 0 @@ -150,6 +174,47 @@ class LinuxHost print_info('NETTX', linux.net[:tx]) end + def self.store_metric_db(db, host_id, metric_name, timestamp, value) + table_name = "host_#{host_id}_#{metric_name}_monitoring" + + create_table_query = <<-SQL + CREATE TABLE IF NOT EXISTS #{table_name} ( + TIMESTAMP DATETIME PRIMARY KEY, + VALUE REAL NOT NULL + ); + SQL + db.execute(create_table_query) + + create_trigger_query = <<-SQL + CREATE TRIGGER IF NOT EXISTS delete_old_records_#{table_name} + AFTER INSERT ON #{table_name} + BEGIN + DELETE FROM #{table_name} + WHERE TIMESTAMP < strftime('%s', 'now', '-#{@db_retention} week'); + END; + SQL + db.execute(create_trigger_query) + + insert_query = <<-SQL + INSERT INTO #{table_name} (TIMESTAMP, VALUE) + VALUES (?, ?); + SQL + db.execute(insert_query, [timestamp, value]) + end + + def self.to_sql(hypervisor) + linux = new + + db = SQLite3::Database.new(File.join(DB_PATH, DB_NAME)) + timestamp = Time.now.to_i + + DB_MONITOR_KEYS.each do |k,v| + self.store_metric_db(db, HOST_ID, k, timestamp, v.call(linux)) + end + + db.close + end + def self.config(hypervisor) linux = new diff --git a/src/im_mad/remotes/lib/python/models/arima/manifest.yaml b/src/im_mad/remotes/lib/python/models/arima/manifest.yaml new file mode 100644 index 0000000000..99d5c65531 --- /dev/null +++ b/src/im_mad/remotes/lib/python/models/arima/manifest.yaml @@ -0,0 +1,2 @@ +prediction_model_type: pyoneai.ml.ArimaPredictionModel +model_configuration_file: model.yaml \ No newline at end of file diff --git a/src/im_mad/remotes/lib/python/models/arima/model.yaml b/src/im_mad/remotes/lib/python/models/arima/model.yaml new file mode 100644 index 0000000000..1429472cc2 --- /dev/null +++ b/src/im_mad/remotes/lib/python/models/arima/model.yaml @@ -0,0 +1,9 @@ +model_class: statsmodels.tsa.arima.model.ARIMA +sequence_length: 200 +hyper_params: + order: [0, 0, 0] + seasonal_order: [0, 0, 0, 0] + enforce_stationarity: true + enforce_invertibility: true + concentrate_scale: false + trend_offset: 1 \ No newline at end of file diff --git a/src/im_mad/remotes/lib/python/models/fourier/manifest.yaml b/src/im_mad/remotes/lib/python/models/fourier/manifest.yaml new file mode 100644 index 0000000000..901acc663b --- /dev/null +++ b/src/im_mad/remotes/lib/python/models/fourier/manifest.yaml @@ -0,0 +1,2 @@ +prediction_model_type: pyoneai.ml.FourierPredictionModel +model_configuration_file: model.yaml \ No newline at end of file diff --git a/src/im_mad/remotes/lib/python/models/fourier/model.yaml b/src/im_mad/remotes/lib/python/models/fourier/model.yaml new file mode 100644 index 0000000000..e390b583dc --- /dev/null +++ b/src/im_mad/remotes/lib/python/models/fourier/model.yaml @@ -0,0 +1,4 @@ +model_class: pyoneai.ml.FourierPredictionModel +sequence_length: 100 +hyper_params: + nbr_freqs_to_keep: 40 \ No newline at end of file diff --git a/src/im_mad/remotes/lib/python/models/hbgt/manifest.yaml b/src/im_mad/remotes/lib/python/models/hbgt/manifest.yaml new file mode 100644 index 0000000000..4ef097435c --- /dev/null +++ b/src/im_mad/remotes/lib/python/models/hbgt/manifest.yaml @@ -0,0 +1,2 @@ +prediction_model_type: pyoneai.ml.HgbtPredictionModel +model_configuration_file: model.yaml \ No newline at end of file diff --git a/src/im_mad/remotes/lib/python/models/hbgt/model.yaml b/src/im_mad/remotes/lib/python/models/hbgt/model.yaml new file mode 100644 index 0000000000..54f4303ff2 --- /dev/null +++ b/src/im_mad/remotes/lib/python/models/hbgt/model.yaml @@ -0,0 +1,6 @@ +model_class: sklearn.ensemble.HistGradientBoostingRegressor +sequence_length: 30 +training_params: + context_length: 200 + max_iter: 50 + compute_ci: false \ No newline at end of file diff --git a/src/im_mad/remotes/lib/python/prediction.py b/src/im_mad/remotes/lib/python/prediction.py new file mode 100644 index 0000000000..b27d57b7af --- /dev/null +++ b/src/im_mad/remotes/lib/python/prediction.py @@ -0,0 +1,225 @@ +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import sys +import yaml + +import argparse +import base64 +import json +import os +import sqlite3 + +from datetime import timedelta + + +METRICS = { + 'host': + ["usedcpu", "freecpu", "usedmemory", "freememory", "netrx", "nettx"], + 'virtualmachine': + [ + "cpu", + "memory", + "netrx", + "nettx", + "diskrdbytes", + "diskwrbytes", + "diskrdiops", + "diskwriops", + ] +} + +def predictions( + entity, manifest_path, metric_name, metrics_db, forecast_horizon, resolution, + sequence_length +): + """ + Generates predictions for a given Host metric using a trained ML model. + + Parameters + ---------- + entity : dict + Entity information. + manifest_path : str + Path to the ML artifact manifest file. + metric_name : str + Name of the metric to predict. + metrics_db : str + Path to SQLite metrics database. + forecast_horizon : int + Number of prediction steps. + resolution : int + Time resolution in minutes or hours. + sequence_length: int + Number of observations according to the resolution + + Returns + ------- + str + String of predictions in key:value format. + """ + + from pyoneai.core import ( + EntityType, + EntityUID, + Instant, + Metric, + MetricAccessor, + MetricAttributes, + Period, + PredictorAccessor, + SQLiteAccessor, + ) + from pyoneai.ml import ArtifactManager + + if forecast_horizon == 1: + time = Instant(resolution) + else: + time = Period( + slice( + resolution, + resolution * forecast_horizon, + resolution, + ) + ) + + ml_model = ArtifactManager.load(manifest_path) + ml_model.model_config.sequence_length = sequence_length + metric = Metric( + entity_uid=EntityUID(type=EntityType(entity["type"]), id=entity["id"]), + attrs=MetricAttributes(name=metric_name), + accessor=MetricAccessor( + SQLiteAccessor(metrics_db), PredictorAccessor(ml_model) + ), + ) + return round(metric[time].values[-1][0][0], 2) + +def parse_entity(entity_str): + try: + type,id,uuid,db_dir = entity_str.split(",") + return {"type":type,"id": id, "uuid": uuid, "db_dir": db_dir} + except ValueError: + raise argparse.ArgumentTypeError( + f"VM must be in the format 'id,db_dir'. Got: {entity_str}" + ) + +def main(): + parser = argparse.ArgumentParser(description="Prediction probe") + + parser.add_argument( + "--entity", + type=parse_entity, + required=True, + help="Specify an entity in the format 'type,id,uid,db_dir'.", + ) + + parser.add_argument( + "--pythonpath", + type=str, + required=True, + help="Specify the path to python libs and configs", + ) + + args = parser.parse_args() + + entity = args.entity + + # load configuration file + config_file = '/var/tmp/one/etc/im/kvm-probes.d/forecast.conf' + with open(config_file, 'r') as file: + config = yaml.load(file, Loader=yaml.FullLoader) + + # db retention is in weeks + db_retention = timedelta(weeks=int(config[entity["type"]]['db_retention'])) + + # forecast is given in minutes + forecast = timedelta(minutes=int(config[entity["type"]]['forecast_period'])) + + # forecast_far is given in hours + forecast_far = timedelta(hours=int(config[entity["type"]]['forecast_far_period'])) + + resolution = timedelta(minutes=5) + resolution_far = timedelta(hours=1) + + # TODO: since resolution is in minutes the sequence length could be really big + # In this case, we should define a smaller sequence length + sequence_length =int(db_retention/resolution) + sequence_length_far =int(db_retention/resolution_far) + + forecast_horizon = int(forecast/resolution) + forecast_horizon_far = int(forecast_far/resolution_far) + + manifest_path = f"{args.pythonpath}/models/fourier/manifest.yaml" + metrics_db = os.path.join(entity["db_dir"], "metrics.db") + + monitor = {} + connection = sqlite3.connect(metrics_db) + for metric_name in METRICS[entity["type"]]: + if entity["type"] == 'virtualmachine': + # in case of VM we need to add also the monitoring values + table_name = f'virtualmachine_{entity["id"]}_{metric_name}_monitoring' + cursor = connection.cursor() + cursor.execute( + f"SELECT VALUE FROM {table_name} ORDER BY TIMESTAMP DESC LIMIT 1" + ) + latest_value = cursor.fetchone() + if latest_value: + monitor[metric_name.upper()] = latest_value[0] + try: + forecast = predictions( + entity=entity, + manifest_path=manifest_path, + metric_name=metric_name, + metrics_db=metrics_db, + forecast_horizon=forecast_horizon, + resolution=resolution, + sequence_length=sequence_length + ) + except Exception as e: + sys.stderr.write(f"Error: {e} ({type(e).__name__})\n") + forecast = None + + try: + forecast_far = predictions( + entity=entity, + manifest_path=manifest_path, + metric_name=metric_name, + metrics_db=metrics_db, + forecast_horizon=forecast_horizon_far, + resolution=resolution_far, + sequence_length=sequence_length_far + ) + except Exception as e: + sys.stderr.write(f"Error: {e} ({type(e).__name__})\n") + forecast_far = None + + if forecast: + monitor[f"{metric_name.upper()}_FORECAST"] = forecast + if forecast_far: + monitor[f"{metric_name.upper()}_FORECAST_FAR"] = forecast_far + + if monitor: + mon_str = "\n".join(f'{key}="{value}"' for key, value in monitor.items()) + + if entity['type'] == 'host': + print(mon_str) + elif entity['type'] == 'virtualmachine': + mon_base64 = base64.b64encode(mon_str.encode("utf-8")).decode("utf-8") + print( + f'VM = [ ID="{entity["id"]}", DEPLOY_ID="{entity["uuid"]}", MONITOR="{mon_base64}" ]' + ) + + +if __name__ == "__main__": + main() diff --git a/src/im_mad/remotes/lib/python/prediction.sh b/src/im_mad/remotes/lib/python/prediction.sh new file mode 100755 index 0000000000..e5140ac40a --- /dev/null +++ b/src/im_mad/remotes/lib/python/prediction.sh @@ -0,0 +1,21 @@ +#!/bin/bash + +# -------------------------------------------------------------------------- # +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems # +# # +# Licensed under the Apache License, Version 2.0 (the "License"); you may # +# not use this file except in compliance with the License. You may obtain # +# a copy of the License at # +# # +# http://www.apache.org/licenses/LICENSE-2.0 # +# # +# Unless required by applicable law or agreed to in writing, software # +# distributed under the License is distributed on an "AS IS" BASIS, # +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # +# See the License for the specific language governing permissions and # +# limitations under the License. # +#--------------------------------------------------------------------------- # + +SCRIPT_DIR=$(dirname "$0") + +PYTHONPATH=$SCRIPT_DIR python "$SCRIPT_DIR/prediction.py" "$@" --pythonpath $SCRIPT_DIR \ No newline at end of file diff --git a/src/im_mad/remotes/lib/python/pyoneai/__init__.py b/src/im_mad/remotes/lib/python/pyoneai/__init__.py new file mode 100644 index 0000000000..c8de590c3f --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/__init__.py @@ -0,0 +1,5 @@ +__all__ = ( + # sub-packages + "core", + "ml", +) diff --git a/src/im_mad/remotes/lib/python/pyoneai/core/__init__.py b/src/im_mad/remotes/lib/python/pyoneai/core/__init__.py new file mode 100644 index 0000000000..4aea77f91a --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/core/__init__.py @@ -0,0 +1,25 @@ +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .base_accessor import ( + AccessorType, + BaseAccessor, +) +from .entity_uid import EntityType, EntityUID +from .metric import Metric, MetricAttributes, MetricType +from .metric_accessor import MetricAccessor +from .predictor_accessor import PredictorAccessor +from .sqlite_accessor import SQLiteAccessor +from .time import Instant, Period +from .tsnumpy import Timeseries diff --git a/src/im_mad/remotes/lib/python/pyoneai/core/base_accessor.py b/src/im_mad/remotes/lib/python/pyoneai/core/base_accessor.py new file mode 100644 index 0000000000..a47d528bec --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/core/base_accessor.py @@ -0,0 +1,54 @@ +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +__all__ = [ + "AccessorType", + "BaseAccessor", +] + +import abc +from enum import Enum +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from .entity_uid import EntityUID + from .metric import MetricAttributes + from .time import Instant, Period + from .tsnumpy.timeseries import Timeseries + + +class AccessorType(Enum): + OBSERVATION = "Observation" + PREDICTION = "Prediction" + + +class BaseAccessor(abc.ABC): + + @property + @abc.abstractmethod + def type(self) -> AccessorType: + raise NotImplementedError() + + @abc.abstractmethod + def get_timeseries( + self, + entity_uid: EntityUID, + metric_attrs: MetricAttributes, + time: Instant | Period, + *args: Any, + **kwargs: Any, + ) -> Timeseries: + raise NotImplementedError() diff --git a/src/im_mad/remotes/lib/python/pyoneai/core/entity_uid.py b/src/im_mad/remotes/lib/python/pyoneai/core/entity_uid.py new file mode 100644 index 0000000000..b339c4affd --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/core/entity_uid.py @@ -0,0 +1,32 @@ +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from dataclasses import dataclass +from enum import Enum + + +class EntityType(Enum): + HOST = "host" + VIRTUAL_MACHINE = "virtualmachine" + + +@dataclass +class EntityUID: + type: type[EntityType] + id: int + + def __str__(self) -> str: + return f"{self.type.value}_{self.id}" diff --git a/src/im_mad/remotes/lib/python/pyoneai/core/metric.py b/src/im_mad/remotes/lib/python/pyoneai/core/metric.py new file mode 100644 index 0000000000..93d1b23f2c --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/core/metric.py @@ -0,0 +1,96 @@ +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +__all__ = [ + "Metric", + "MetricAttributes", + "MetricType", +] +import enum +from dataclasses import dataclass +from typing import TYPE_CHECKING, Union, overload + +from .entity_uid import EntityUID +from .time import Instant, Period +from .tsnumpy.timeseries import Timeseries + +if TYPE_CHECKING: + from .metric_accessor import MetricAccessor + + +@enum.unique +class MetricType(enum.Enum): + COUNTER = "counter" + GAUGE = "gauge" + RATE = "rate" + + +@dataclass +class MetricAttributes: + name: Union[str, None] = None + type: Union[MetricType, None] = None + instant_resolution: Union[str, None] = None + instant_hist_steps: Union[int, None] = None + + +class Metric: + __slots__ = ("_entity_uid", "_attrs", "_accessor") + + _entity_uid: EntityUID + _attrs: MetricAttributes + _accessor: MetricAccessor + + def __init__( + self, + entity_uid: EntityUID, + attrs: MetricAttributes, + accessor: MetricAccessor, + ) -> None: + self._entity_uid = entity_uid + self._attrs = attrs + self._accessor = accessor + + @property + def entity_uid(self): + return self._entity_uid + + @property + def attributes(self): + return self._attrs + + @property + def accessor(self): + return self._accessor + + def __getitem__( + self, key: Union[str, slice, Instant, Period] + ) -> Timeseries: + time: Instant | Period + + if isinstance(key, str): + time = Instant(key) + elif isinstance(key, slice): + time = Period(key) + elif isinstance(key, (Instant, Period)): + time = key + else: + raise TypeError( + "'key' must be an instance of 'str', 'slice', 'Instant', " + "or 'Period'" + ) + return self.accessor.get_timeseries( + self.entity_uid, self.attributes, time + ) diff --git a/src/im_mad/remotes/lib/python/pyoneai/core/metric_accessor.py b/src/im_mad/remotes/lib/python/pyoneai/core/metric_accessor.py new file mode 100644 index 0000000000..734daf061f --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/core/metric_accessor.py @@ -0,0 +1,80 @@ +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +__all__ = ["MetricAccessor"] +from numbers import Number +from typing import Union + +from .base_accessor import BaseAccessor +from .entity_uid import EntityUID +from .metric import MetricAttributes +from .time import Instant, Period +from .tsnumpy.timeseries import Timeseries + + +class MetricAccessor: + __slots__ = ("_observator_accessor", "_predictor_accessor") + + def __init__( + self, + observator_accessor: BaseAccessor, + predictor_accessor: BaseAccessor, + ) -> None: + self._observator_accessor = observator_accessor + self._predictor_accessor = predictor_accessor + + def get_timeseries( + self, + entity_uid: EntityUID, + metric_attrs: MetricAttributes, + time: Union[Instant, Period], + ) -> Timeseries: + if isinstance(time, Period): + past, future = time.split() + obs, pred = None, None + if past is not None: + obs = self._observator_accessor.get_timeseries( + entity_uid, metric_attrs, past + ) + if future is not None: + pred = self._predictor_accessor.get_timeseries( + entity_uid, + metric_attrs, + future, + observator_accessor=self._observator_accessor, + ) + if pred is None: + # TODO: obs can be None here and we expect to return just Number or TimeSeries + return obs + if obs is None: + return pred + return obs.append(pred) + + if isinstance(time, Instant): + if time.is_past: + return self._observator_accessor.get_timeseries( + entity_uid, metric_attrs, time + ) + elif time.is_future: + return self._predictor_accessor.get_timeseries( + entity_uid, + metric_attrs, + time, + observator_accessor=self._observator_accessor, + ) + raise TypeError( + f"argument {time} should be either Instant or Period" + ) diff --git a/src/im_mad/remotes/lib/python/pyoneai/core/predictor_accessor.py b/src/im_mad/remotes/lib/python/pyoneai/core/predictor_accessor.py new file mode 100644 index 0000000000..68423834e7 --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/core/predictor_accessor.py @@ -0,0 +1,83 @@ +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +__all__ = ["PredictorAccessor"] + +import importlib.util +from typing import TYPE_CHECKING, Any + +from .base_accessor import AccessorType, BaseAccessor +from .entity_uid import EntityUID +from .metric import MetricAttributes +from .time import Instant, Period +from .tsnumpy.timeseries import Timeseries + +if TYPE_CHECKING: + from ..ml.models import BasePredictionModel + + +class PredictorAccessor(BaseAccessor): + __slots__ = () + + def __init__( + self, + prediction_model: BasePredictionModel, + ) -> None: + self._prediction_model = prediction_model + + def get_timeseries( + self, + entity_uid: EntityUID, + metric_attrs: MetricAttributes, + time: Instant | Period, + *args: Any, + **kwargs: Any, + ) -> Timeseries: + observator_accessor = kwargs.get("observator_accessor") + if not observator_accessor: + raise ValueError("Missing 'observator_accessor' in kwargs") + hist_steps = self._prediction_model.model_config.sequence_length + if isinstance(time, Instant): + hist_resolution = time.duration + time_start = time.value + else: + hist_resolution = time.resolution + time_start = time.start + hist_start = ( + time_start - hist_resolution + ) - hist_steps * hist_resolution + hist_end = time_start - hist_resolution + hist_period = Period( + value=slice(hist_start, hist_end, hist_resolution), + origin=time.origin, + ) + obs = observator_accessor.get_timeseries( + entity_uid, metric_attrs, hist_period + ) + if isinstance(time, Instant): + return self._prediction_model.predict(metric=obs, horizon=1) + elif isinstance(time, Period): + return self._prediction_model.predict( + metric=obs, horizon=len(time.values) + ) + else: + raise TypeError( + "'time' must be an instance of 'Instant' or 'Period'" + ) + + @property + def type(self) -> AccessorType: + return AccessorType.PREDICTION diff --git a/src/im_mad/remotes/lib/python/pyoneai/core/sqlite_accessor.py b/src/im_mad/remotes/lib/python/pyoneai/core/sqlite_accessor.py new file mode 100644 index 0000000000..eea2e861ef --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/core/sqlite_accessor.py @@ -0,0 +1,109 @@ +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +__all__ = ["PredictorAccessor"] + +import importlib.util +import sqlite3 +from datetime import timedelta +from typing import TYPE_CHECKING, Any + +import numpy as np + +from .base_accessor import AccessorType, BaseAccessor +from .entity_uid import EntityUID +from .metric import MetricAttributes +from .time import Instant, Period +from .tsnumpy.timeseries import Timeseries + + +class SQLiteAccessor(BaseAccessor): + """ + Metric accessor for SQLite database. + + Parameters + ---------- + db_path : str + Path to the SQLite database. + timestamp_col : str, default=TIMESTAMP + Name of the timestamp column. + value_col : str, default=VALUE + Name of the metric value column. + monitor_interval : int, default=60 + Interval (seconds) at which the data is stored in the database. + """ + + __slots__ = ( + "_connection", + "_timestamp_col", + "_value_col", + "_table_name_template", + "_monitor_interval", + ) + + def __init__( + self, + db_path: str, + timestamp_col: str = "TIMESTAMP", + value_col: str = "VALUE", + monitor_interval: int = 60, + ) -> None: + self._connection = sqlite3.connect(db_path) + self._timestamp_col = timestamp_col + self._value_col = value_col + self._table_name_template = "{entityUID}_{metric_name}_monitoring" + self._monitor_interval = monitor_interval + + @property + def type(self) -> AccessorType: + return AccessorType.OBSERVATION + + def get_timeseries( + self, + entity_uid: EntityUID, + metric_attrs: MetricAttributes, + time: Instant | Period, + ) -> Timeseries: + """ + Retrieve timeseries data from the SQLite database for the given + time period. + + Parameters + ---------- + entity : Entity + Entity to retrieve data for. + metric_attrs : MetricAttributes + Attributes of the metric. + time : Instant or Period + Time period to retrieve data for. + + Returns + ------- + Timeseries + Timeseries data for the given time period. + """ + table_name = self._table_name_template.format( + entityUID=entity_uid, metric_name=metric_attrs.name + ) + return Timeseries.read_from_database( + connection=self._connection, + table_name=table_name, + metric_name=metric_attrs.name, + timestamp_col=self._timestamp_col, + value_col=self._value_col, + time=time, + tolerance=timedelta(seconds=self._monitor_interval), + ) diff --git a/src/im_mad/remotes/lib/python/pyoneai/core/time.py b/src/im_mad/remotes/lib/python/pyoneai/core/time.py new file mode 100644 index 0000000000..bb0fe81aae --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/core/time.py @@ -0,0 +1,338 @@ +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +__all__ = ["Instant", "Period"] + +from datetime import datetime, timedelta, timezone +from typing import Any, Literal, Union + +import numpy as np + +_DatetimeT = Union[str, datetime, np.datetime64] +_TimeDeltaT = Union[str, timedelta, np.timedelta64] + +_DATE_TIME_END = frozenset(map(str, range(10))) | {"Z", "z"} +_TIME_DELTA_END = frozenset({"W", "w", "D", "d", "h", "m", "s"}) + + +class Instant: + __slots__ = ("_origin", "_value", "_tz") + + def __init__( + self, + value: Union[_DatetimeT, _TimeDeltaT, None] = "0", + origin: datetime | None = None, + ) -> None: + self._origin = _set_origin(origin) + self._value = _time_stamp(value, self._origin) + self._tz = timezone.utc + + @property + def value(self) -> datetime: + return self._value + + @property + def origin(self) -> datetime: + return self._origin + + @property + def duration(self) -> timedelta: + return abs(self._value - self._origin) + + @property + def is_past(self) -> bool: + return self._value <= self._origin + + @property + def is_future(self) -> bool: + return self._value > self._origin + + @property + def tz(self) -> timezone: + return self._tz + + @property + def is_monotonic_increasing(self) -> bool: + return True + + @property + def is_unique(self) -> bool: + return True + + @property + def values(self) -> np.ndarray: + return np.array( + [_time_stamp(self.value, self._origin)], dtype="object" + ) + + def __len__(self) -> int: + return 1 + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, Instant): + return False + return self.value == other.value + + +class Period: + __slots__ = ( + "_origin", + "_time_index", + "_start", + "_end", + "_resolution", + "_tz", + ) + + def __init__( + self, value: slice | np.ndarray, origin: datetime | None = None + ) -> None: + self._origin = _set_origin(origin) + self._tz = timezone.utc + if isinstance(value, np.ndarray): + size = len(value) + if size == 0 or size == 1: + raise ValueError( + "'value' must be a Series representing a time period" + ) + elif size == 2: + if value[1] - value[0] == 0: + raise ValueError( + "'value' for Period should represent a time interval, not" + " a single point" + ) + + self._start, self._end = value[0], value[-1] + self._resolution = value[1] - value[0] + self._time_index = value + + elif isinstance(value, slice): + if value.start is None or value.stop is None or value.step is None: + raise ValueError( + "slice 'value' must have a start, stop, and step" + ) + self._start = _time_stamp(value.start, self._origin) + self._end = _time_stamp(value.stop, self._origin) + if self._start > self._end: + raise ValueError( + "'value' specifies an invalid time range (start > end)" + ) + if self._start == self._end: + raise ValueError( + "'value' for Period should represent a time interval, not" + " a single point" + ) + if isinstance(value.step, str): + self._resolution = _parse_timedelta(value.step) + elif isinstance(value.step, timedelta): + self._resolution = value.step + else: + raise TypeError(f"{value.step} should be string or timedelta") + self._time_index = np.arange( + self._start, + self._end + self._resolution, + self._resolution, + dtype="object", + ) + else: + raise TypeError( + "'value' must be a slice or DatetimeIndex representing a time period" + ) + + @classmethod + def from_instant(cls, instant: Instant) -> Period: + return cls( + slice(instant.value, instant.origin, instant.duration), + origin=instant.origin, + ) + + @property + def values(self) -> np.ndarray: + # TODO: Consider renaming this property. + return self._time_index + + @property + def start(self) -> timedelta: + return self._start + + @property + def end(self) -> datetime: + return self._end + + @property + def resolution(self) -> datetime: + return self._resolution + + @property + def duration(self) -> timedelta: + return self._end - self._start + + @property + def span(self) -> tuple[timedelta, timedelta]: + return (self._start - self._origin, self._end - self._origin) + + @property + def origin(self) -> datetime: + return self._origin + + @property + def tz(self) -> timezone: + return self._tz + + @property + def is_monotonic_increasing(self) -> bool: + return np.all(self._time_index[:-1] <= self._time_index[1:]) + + @property + def is_unique(self) -> bool: + return self._time_index.size == np.unique(self._time_index).size + + def __len__(self) -> int: + return len(self.values) + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, Period): + return False + return ( + self._origin == other._origin + and np.array_equal(self._time_index, other._time_index) + and self._start == other._start + and self._end == other._end + and self._resolution == other._resolution + and self._tz == other._tz + ) + + def split( + self, when: _DatetimeT | None = None + ) -> tuple[Instant | Period | None, Instant | Period | None]: + """ + Splits the period into two parts. + + Parameters + ---------- + when : _InstantT or None, optional + A datetime-like object specifying the time to split the + + Returns + ------- + A tuple containing the first and second parts as Instant or + Period instances, or None if the resulting part is empty. + """ + if when is None: + time_stamp = self._origin + else: + time_stamp = _assure_time_zone(when) + time_idx = self._time_index + sep_idx = np.searchsorted(time_idx, time_stamp, side="right") + first_part = time_idx[:sep_idx] + second_part = time_idx[sep_idx:] + + first = ( + None + if first_part.size == 0 + else ( + Instant(first_part[0], origin=self._origin) + if first_part.size == 1 + else Period(first_part, origin=self._origin) + ) + ) + second = ( + None + if second_part.size == 0 + else ( + Instant(second_part[0], origin=self._origin) + if second_part.size == 1 + else Period(second_part, origin=self._origin) + ) + ) + return (first, second) + + +def _assure_time_zone(ts: datetime) -> datetime: + # time zone should be UTC + if ts.tzinfo is not None: + return ts.astimezone(timezone.utc) + else: + return ts.replace(tzinfo=timezone.utc) + + +def _set_origin(origin: _DatetimeT | None) -> datetime: + if origin: + if isinstance(origin, str): + return datetime.fromisoformat(origin).replace(microsecond=0) + elif isinstance(origin, datetime): + return origin.replace(microsecond=0) + elif isinstance(origin, np.datetime64): + return (origin.astype("datetime64[s]")).tolist() + else: + return datetime.now(timezone.utc).replace(microsecond=0) + + +def _parse_timedelta(time_str): + num_part = "".join(filter(lambda c: c.isdigit() or c == "-", time_str)) + unit_part = "".join(filter(str.isalpha, time_str)) + + num = int(num_part) + + unit_mapping = { + "s": timedelta(seconds=num), + "m": timedelta(minutes=num), + "h": timedelta(hours=num), + "d": timedelta(days=num), + } + + if unit_part in unit_mapping: + return unit_mapping[unit_part] + + raise ValueError(f"Unsupported time unit: {unit_part}") + + +def _time_stamp( + value: Union[_DatetimeT, _TimeDeltaT, Literal[0], None], origin: datetime +) -> datetime: + if value in {None, 0, "0"}: + result = _assure_time_zone(origin) + elif isinstance(value, (datetime, np.datetime64)): + if isinstance(value, np.datetime64): + if not np.isnat(value): + value.isvalue = value.astype( + "datetime64[s]" + ).tolist() # Convert to seconds + else: + raise ValueError(f"{value} is not a time") + result = _assure_time_zone( + value.replace(microsecond=0) + ) # Remove microseconds + elif isinstance(value, (timedelta, np.timedelta64)): + result = origin + value + elif isinstance(value, str): + # TODO: Use `dateutil` for better checks. + # (value[-1].isdigit or value.endswith(('Z', 'z'), -1)) + last = value[-1] + if last in _DATE_TIME_END and len(value) >= 14: + result = _assure_time_zone( + datetime.fromisoformat(value).replace(microsecond=0) + ) + elif last in _TIME_DELTA_END: + result = origin + _parse_timedelta(value) + else: + raise ValueError("'value' is an incorrect string") + else: + raise TypeError( + "'value' must be a datetime-like or timedelta-like object" + ) + + return result.replace(microsecond=0) diff --git a/src/im_mad/remotes/lib/python/pyoneai/core/tsnumpy/__init__.py b/src/im_mad/remotes/lib/python/pyoneai/core/tsnumpy/__init__.py new file mode 100644 index 0000000000..efdf3c62c8 --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/core/tsnumpy/__init__.py @@ -0,0 +1,23 @@ +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""OpenNebula timeseries implementation. + +This module provides the Timeseries class for handling time-series data in OpenNebula, +offering a 3-dimensional view of metric data organized by time, metrics, and entities. +""" + +from .timeseries import Timeseries + +__all__ = ["Timeseries"] diff --git a/src/im_mad/remotes/lib/python/pyoneai/core/tsnumpy/index/__init__.py b/src/im_mad/remotes/lib/python/pyoneai/core/tsnumpy/index/__init__.py new file mode 100644 index 0000000000..995969476f --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/core/tsnumpy/index/__init__.py @@ -0,0 +1,28 @@ +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Index classes for timeseries data. + +This module provides the index classes used for organizing and accessing timeseries data +along different dimensions: +- TimeIndex: For time-based indexing +- MetricIndex: For metric name indexing +- EntityIndex: For entity-based indexing +""" + +from .entity import EntityIndex +from .metric import MetricIndex +from .time import TimeIndex + +__all__ = ["time", "metric", "entity"] diff --git a/src/im_mad/remotes/lib/python/pyoneai/core/tsnumpy/index/base.py b/src/im_mad/remotes/lib/python/pyoneai/core/tsnumpy/index/base.py new file mode 100644 index 0000000000..a91ab07c2b --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/core/tsnumpy/index/base.py @@ -0,0 +1,152 @@ +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Base module for timeseries indexing. + +This module provides the base class for all index types used in timeseries data handling. +""" + +from abc import ABC, abstractmethod +from datetime import timedelta +from typing import Any, Generic, List, TypeVar, Union + +import numpy as np + +T = TypeVar("T") + +NO_TIME_SHIFT: timedelta = timedelta(seconds=0) + + +class BaseIndex(ABC, Generic[T]): + """Base class for all index types. + + This abstract base class defines the interface for all index implementations + used in timeseries data handling. + + Parameters + ---------- + values : numpy.ndarray + Array of index values of type T. + + Attributes + ---------- + values : numpy.ndarray + The underlying array of index values. + """ + + __slots__ = ("values",) + + def __init__(self, values: np.ndarray): + self.values = values + self.validate() + + @abstractmethod + def validate(self) -> None: + """Validate index-specific integrity constraints. + + This method should be implemented by subclasses to perform + validation specific to each index type. + + Raises + ------ + ValueError + If the index values do not meet the required constraints. + """ + pass + + @abstractmethod + def get_loc(self, key: Any) -> Union[int, slice, List[int]]: + """Get location(s) for the given key. + + Parameters + ---------- + key : Any + The key to locate in the index. Type depends on the specific index implementation: + - TimeIndex: Period or Instant + - MetricIndex: str or List[str] + - EntityIndex: EntityUID or List[EntityUID] + + Returns + ------- + Union[int, slice, List[int]] + The location(s) where the key was found: + - int: for single element selections + - slice: for range selections (TimeIndex only) + - List[int]: for multiple element selections + + Raises + ------ + KeyError + If the key is not found in the index. + TypeError + If the key type is not supported by the index. + """ + pass + + @abstractmethod + def get_sliced_index( + self, selection: Union[int, slice, List[int]] + ) -> np.ndarray: + """Get a new index array based on the selection. + + This method is used internally by the Timeseries class to maintain proper indexing + when slicing operations are performed. + + Parameters + ---------- + selection : Union[int, slice, List[int]] + The selection to apply: + - int: single element selection + - slice: range selection + - List[int]: multiple element selection + + Returns + ------- + numpy.ndarray + A new numpy array containing the selected index values. The type of the elements + depends on the specific index implementation: + - TimeIndex: np.datetime64 + - MetricIndex: str + - EntityIndex: EntityUID + """ + pass + + def __len__(self) -> int: + """Get the length of the index. + + Returns + ------- + int + Number of elements in the index. + """ + return len(self.values) if self.values is not None else 1 + + @property + def is_monotonic_increasing(self) -> bool: + """Flag showing if index is monotonic increasing.""" + if len(self) > 1: + return bool(np.all(np.diff(self.values) > NO_TIME_SHIFT)) + return True + + @property + def is_monotonic_decreasing(self) -> bool: + """Flag showing if index is monotonic decreasing.""" + if len(self) > 1: + return bool(np.all(np.diff(self.values) < NO_TIME_SHIFT)) + return True + + @property + def is_unique(self) -> bool: + """Flag showing if the index values are unique.""" + return len(np.unique(self.values)) == len(self.values) diff --git a/src/im_mad/remotes/lib/python/pyoneai/core/tsnumpy/index/entity.py b/src/im_mad/remotes/lib/python/pyoneai/core/tsnumpy/index/entity.py new file mode 100644 index 0000000000..0d382342bd --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/core/tsnumpy/index/entity.py @@ -0,0 +1,142 @@ +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Entity index module for timeseries data. + +This module provides entity-specific indexing functionality for timeseries data, +handling EntityUID lookups and selections. +""" + +from typing import List, Union + +import numpy as np + +from pyoneai.core.entity_uid import EntityUID + +from .base import BaseIndex + + +class EntityIndex(BaseIndex[EntityUID]): + """Entity-specific index handling for timeseries data. + + This class handles indexing of entities using EntityUID objects, ensuring + uniqueness and proper type validation. + + Parameters + ---------- + values : numpy.ndarray + Array of EntityUID objects. + + Raises + ------ + ValueError + If invalid entity types are found or if there are duplicate entities. + """ + + def validate(self) -> None: + """Validate entity UIDs are valid and unique. + + This method ensures that: + 1. All values are valid EntityUID objects + 2. No duplicate entities exist (based on type and ID) + + Raises + ------ + ValueError + If invalid entity types are found or if there are duplicate entities. + """ + invalid = [ + i + for i, e in enumerate(self.values) + if not isinstance(e, EntityUID) + ] + if invalid: + types = [type(self.values[i]).__name__ for i in invalid] + raise ValueError( + f"Invalid entity types at indices {invalid}: {types}" + ) + + entity_pairs = [(e.type, e.id) for e in self.values] + if len(set(entity_pairs)) != len(entity_pairs): + raise ValueError("Duplicate entities not allowed") + + def get_loc( + self, key: Union[EntityUID, List[EntityUID]] + ) -> Union[int, List[int]]: + """Get location(s) for the given entity key(s). + + Parameters + ---------- + key : Union[EntityUID, List[EntityUID]] + Single EntityUID or list of EntityUIDs to locate. + + Returns + ------- + Union[int, List[int]] + Index or list of indices where the entity/entities are found. + + Raises + ------ + KeyError + If an entity is not found. + + Examples + -------- + >>> entity_idx = EntityIndex([EntityUID('VM', 1), EntityUID('VM', 2)]) + >>> # Single entity + >>> entity_idx.get_loc(EntityUID('VM', 1)) + 0 + >>> # Multiple entities + >>> entity_idx.get_loc([EntityUID('VM', 1), EntityUID('VM', 2)]) + [0, 1] + """ + if isinstance(key, EntityUID): + loc = [ + i + for i, e in enumerate(self.values) + if e.type == key.type and e.id == key.id + ] + if not loc: + raise KeyError(f"Entity {key} not found") + return loc[0] + return [self.get_loc(k) for k in key] + + def get_sliced_index( + self, selection: Union[int, slice, List[int], np.ndarray] + ) -> np.ndarray: + """Get a new entity index array based on the selection. + + Parameters + ---------- + selection : Union[int, slice, List[int], np.ndarray] + The selection to apply to the entity index. + + Returns + ------- + numpy.ndarray + Array of EntityUIDs for the selected entities. + + Examples + -------- + >>> entity_idx = EntityIndex([EntityUID('VM', 1), EntityUID('VM', 2)]) + >>> # Single entity + >>> entity_idx.get_sliced_index(0) + array([EntityUID('VM', 1)], dtype=object) + >>> # Multiple entities + >>> entity_idx.get_sliced_index([0, 1]) + array([EntityUID('VM', 1), EntityUID('VM', 2)], dtype=object) + """ + if isinstance(selection, int): + return np.array([self.values[selection]]) + return self.values[selection] diff --git a/src/im_mad/remotes/lib/python/pyoneai/core/tsnumpy/index/metric.py b/src/im_mad/remotes/lib/python/pyoneai/core/tsnumpy/index/metric.py new file mode 100644 index 0000000000..96714ca12a --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/core/tsnumpy/index/metric.py @@ -0,0 +1,158 @@ +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Metric index module for timeseries data. + +This module provides metric-specific indexing functionality for timeseries data, +handling case-sensitive metric name lookups and selections. +""" + +from typing import List, Union + +import numpy as np + +from .base import BaseIndex + + +class MetricIndex(BaseIndex[str]): + """Metric-specific index handling for timeseries data. + + This class handles metric name indexing with case-sensitive matching. + Metric names must be unique in a case-sensitive manner (e.g., 'cpu' and 'CPU' + are considered different metrics). + + Parameters + ---------- + values : numpy.ndarray + Array of metric names as strings. + + Raises + ------ + ValueError + If duplicate metric names are found (case-sensitive comparison). + + Examples + -------- + >>> metric_idx = MetricIndex(np.array(['cpu', 'CPU', 'memory'])) + >>> metric_idx.get_loc('cpu') # Returns index for 'cpu' + 0 + >>> metric_idx.get_loc('CPU') # Returns index for 'CPU' + 1 + >>> metric_idx.get_loc('Cpu') # Raises KeyError - case sensitive match + KeyError: "Metric 'Cpu' not found" + """ + + def validate(self) -> None: + """Validate metric names are unique in a case-sensitive manner. + + This method ensures that: + 1. All values are converted to numpy array of strings + 2. No duplicate metric names exist (case-sensitive comparison) + + Raises + ------ + ValueError + If duplicate metric names are found. + """ + # Ensure we have a numpy array + if not isinstance(self.values, np.ndarray): + self.values = np.array(self.values, dtype=str) + elif isinstance(self.values, np.str_): + # Handle single string value + self.values = np.array([str(self.values)], dtype=str) + + # Check for duplicates + if len(self.values.shape) == 0: + # Single value case + self.values = np.array([str(self.values)], dtype=str) + elif not self.is_unique: + raise ValueError( + "Duplicate metric names not allowed (case-sensitive)" + ) + + def get_loc(self, key: Union[str, List[str]]) -> Union[int, List[int]]: + """Get location(s) for the given metric name(s). + + This method performs case-sensitive matching. For example, 'cpu' and 'CPU' + are treated as different metrics. + + Parameters + ---------- + key : Union[str, List[str]] + Single metric name or list of metric names to locate. + + Returns + ------- + Union[int, List[int]] + Index or list of indices where the metric(s) are found. + + Raises + ------ + KeyError + If a metric name is not found (case-sensitive match). + + Examples + -------- + >>> metric_idx = MetricIndex(np.array(['cpu', 'memory', 'disk'])) + >>> # Single metric + >>> metric_idx.get_loc('cpu') + 0 + >>> # Multiple metrics + >>> metric_idx.get_loc(['cpu', 'memory']) + [0, 1] + >>> # Case-sensitive matching + >>> metric_idx.get_loc('Cpu') # Raises KeyError + KeyError: "Metric 'Cpu' not found" + """ + if isinstance(key, str): + # Case-sensitive exact match + loc = np.where(self.values == key)[0] + if len(loc) == 0: + available = "', '".join(self.values) + raise KeyError( + f"Metric '{key}' not found. Available metrics (case-sensitive): '{available}'" + ) + return loc[0] + return [self.get_loc(k) for k in key] + + def get_sliced_index( + self, selection: Union[int, slice, List[int], np.ndarray] + ) -> np.ndarray: + """Get a new metric index array based on the selection. + + Parameters + ---------- + selection : Union[int, slice, List[int], np.ndarray] + The selection to apply to the metric index. + + Returns + ------- + numpy.ndarray + Array of metric names for the selected metrics. + + Examples + -------- + >>> metric_idx = MetricIndex(np.array(['cpu', 'memory', 'disk'])) + >>> # Single metric + >>> metric_idx.get_sliced_index(0) + array(['cpu'], dtype='>> # Multiple metrics + >>> metric_idx.get_sliced_index([0, 1]) + array(['cpu', 'memory'], dtype=' datetime: + """Convert a datetime or string to UTC datetime. + + Parameters + ---------- + dt : Union[str, datetime, np.datetime64] + Input datetime, either as string, datetime object, or numpy.datetime64. + For strings, both ISO format and basic format are supported. + If no timezone is specified, UTC is assumed. + + Returns + ------- + datetime + UTC datetime with timezone information. + + Examples + -------- + >>> _to_utc_datetime("2024-01-01T00:00:00Z") + datetime.datetime(2024, 1, 1, 0, 0, tzinfo=datetime.timezone.utc) + >>> _to_utc_datetime("2024-01-01T00:00:00+01:00") + datetime.datetime(2023, 12, 31, 23, 0, tzinfo=datetime.timezone.utc) + """ + if isinstance(dt, np.datetime64): + # Convert numpy.datetime64 to datetime with UTC timezone + return datetime.fromtimestamp( + dt.astype("datetime64[s]").astype("int"), timezone.utc + ) + + if isinstance(dt, datetime): + if dt.tzinfo is None: + dt = dt.replace(tzinfo=timezone.utc) + return dt.astimezone(timezone.utc) + + if isinstance(dt, str): + # Parse string to datetime, assuming UTC if no timezone + try: + dt = datetime.fromisoformat(dt.replace("Z", "+00:00")) + except ValueError: + # If fromisoformat fails, try basic parsing assuming UTC + dt = datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S").replace( + tzinfo=timezone.utc + ) + + return dt.astimezone(timezone.utc) + + +class TimeIndex(BaseIndex[Union[np.datetime64, Period, Instant]]): + """Time-specific index handling for timeseries data. + + This class provides functionality for indexing timeseries data by time, + supporting both single timestamps and time ranges. + + Parameters + ---------- + values : numpy.ndarray + Array of datetime values representing timestamps. + + Raises + ------ + ValueError + If the time index contains duplicate timestamps or is not strictly monotonic increasing. + """ + + @property + def tz(self) -> str: + """Get the timezone of the time index. + + Returns + ------- + str + The timezone of the time index. + """ + return str(timezone.utc) + + @property + def frequency(self) -> timedelta: + """Get the frequency (time difference) between consecutive timestamps. + + Returns + ------- + timedelta + The time difference between consecutive timestamps. + Returns default frequency if the timeseries has 1 or fewer points. + Returns None if the differences are not constant. + """ + default_freq = timedelta(seconds=_DEFAULT_FREQ_SEC) + if len(self.values) <= 1: + return default_freq + + # Calculate differences between consecutive timestamps + time_diffs = np.array( + [t2 - t1 for t1, t2 in zip(self.values[:-1], self.values[1:])] + ) + + # Check if all differences are equal + first_diff = time_diffs[0] + if not np.all([td == first_diff for td in time_diffs]): + return default_freq + + return first_diff + + def validate(self) -> None: + """Validate time index has no duplicates and is ordered. + + This method ensures that: + 1. All timestamps are converted to UTC datetime objects + 2. There are no duplicate timestamps + 3. Timestamps are strictly monotonic increasing + + Raises + ------ + ValueError + If validation fails due to duplicates or incorrect ordering. + """ + + # The Timeseries time index can be empty + if len(self.values) == 0: + return + + # Convert values to UTC datetime if they aren't already + if not isinstance(self.values[0], datetime): + self.values = np.array([_to_utc_datetime(t) for t in self.values]) + + if not self.is_unique: + raise ValueError("Time index contains duplicate timestamps") + + if not self.is_monotonic_increasing: + raise ValueError( + "Time index must be strictly monotonic increasing" + ) + + def get_loc(self, key: Union[Period, Instant]) -> Union[slice, List[int]]: + """Get location(s) for the given time key. + + Parameters + ---------- + key : Union[Period, Instant] + The time selection: + - Period: A time range with start and end timestamps + - Instant: A single timestamp + + Returns + ------- + Union[slice, List[int]] + - For Period: slice object representing the time range + - For Instant: List[int] with indices where the timestamp is found + + Raises + ------ + ValueError + If the time selection is out of bounds (before first or after last timestamp). + + Examples + -------- + >>> idx = TimeIndex(np.array(['2024-01-01', '2024-01-02', '2024-01-03'])) + >>> # Select single timestamp + >>> idx.get_loc(Instant('2024-01-01')) + [0] + >>> # Select time range + >>> idx.get_loc(Period('2024-01-01', '2024-01-02')) + [0, 1] + """ + if isinstance(key, Instant): + key_val = _to_utc_datetime(key.value) + # Check if instant is within bounds + if key_val < self.values[0] or key_val > self.values[-1]: + raise ValueError("Time selection out of bounds") + return np.where(self.values == key_val)[0] + else: + start_val = _to_utc_datetime(key.start) + end_val = _to_utc_datetime(key.end) + + # Check if period is within bounds + if start_val < self.values[0] or end_val > self.values[-1]: + raise ValueError("Time selection out of bounds") + + mask = (self.values >= start_val) & (self.values <= end_val) + return np.where(mask)[0] # Return indices where mask is True + + def get_sliced_index( + self, selection: Union[int, slice, List[int], np.ndarray] + ) -> np.ndarray: + """Get a new time index array based on the selection. + + Parameters + ---------- + selection : Union[int, slice, List[int], np.ndarray] + The selection to apply to the time index. + + Returns + ------- + numpy.ndarray + Array of datetime64 values for the selected timestamps. + + Examples + -------- + >>> idx = TimeIndex(np.array(['2024-01-01', '2024-01-02', '2024-01-03'])) + >>> idx.get_sliced_index([0, 1]) + array(['2024-01-01', '2024-01-02'], dtype='datetime64[ns]') + """ + return self.values[selection] diff --git a/src/im_mad/remotes/lib/python/pyoneai/core/tsnumpy/timeseries.py b/src/im_mad/remotes/lib/python/pyoneai/core/tsnumpy/timeseries.py new file mode 100644 index 0000000000..6b2ff2a328 --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/core/tsnumpy/timeseries.py @@ -0,0 +1,730 @@ +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Timeseries implementation for OpenNebula metrics. + +This module provides the main Timeseries class for handling time-series data in OpenNebula. +""" + +from __future__ import annotations + +import json +from datetime import timedelta +from typing import Any, Mapping, Tuple, Union + +import numpy as np + +from pyoneai.core.entity_uid import EntityType, EntityUID +from pyoneai.core.time import Instant, Period + +from .index import EntityIndex, MetricIndex, TimeIndex + + +class Timeseries: + """A class representing time-series data for OpenNebula entities. + + This class provides a 3-dimensional view of metric data organized by time, + metrics, and entities. The data is stored in a numpy array with shape + (time_points, metrics, entities). + + Parameters + ---------- + time_idx : Union[Period, Instant, TimeIndex] + Time points of the series. Can be a Period, Instant, or TimeIndex object. + metric_idx : numpy.ndarray + Array of metric names as strings. + entity_uid_idx : numpy.ndarray + Array of EntityUID objects identifying the entities. + data : numpy.ndarray + 3D array of metric values with shape (time_points, metrics, entities). + + Attributes + ---------- + metric_names : numpy.ndarray + Available metric names. + entity_uids : numpy.ndarray + Entity identifiers. + shape : tuple + Data shape as (timestamps, metrics, entities). + values : numpy.ndarray + Raw data array (view). + time_index : Union[Period, Instant] + Time index of the series. + + Examples + -------- + >>> ts = Timeseries( + ... time_idx=Period(...), + ... metric_idx=np.array(["cpu", "memory"]), + ... entity_uid_idx=np.array([ + ... EntityUID(EntityType.VIRTUAL_MACHINE, 1), + ... EntityUID(EntityType.VIRTUAL_MACHINE, 2) + ... ]), + ... data=np.array([...]) # Shape: (time_points, 2, 2) + ... ) + >>> cpu_ts = ts["cpu"] # Select CPU metric + >>> vm1_ts = ts[EntityUID(EntityType.VIRTUAL_MACHINE, 1)] # Select VM + >>> instant_ts = ts[Instant("2024-01-01T00:00:00+00:00")] # Select time + + Raises + ------ + ValueError + If data is empty or dimensions don't match the indices. + """ + + __slots__ = ("_time_idx", "_data", "_metric_idx", "_entity_idx") + + def __init__( + self, + time_idx: Union[Period, Instant, TimeIndex, np.ndarray], + metric_idx: np.ndarray[str], + entity_uid_idx: np.ndarray[EntityUID], + data: np.ndarray, + ) -> None: + # Handle empty data case + if isinstance(data, np.ndarray) and data.size == 0: + # Create minimal shape array (0, 1, 1) for empty timeseries + data = np.array([]).reshape( + (0, len(metric_idx), len(entity_uid_idx)) + ) + + # Create index objects (validation is handled by the index classes) + self._time_idx = ( + time_idx + if isinstance(time_idx, TimeIndex) + else TimeIndex( + time_idx.values + if isinstance(time_idx, Period) + else ( + np.array([time_idx.value]) + if isinstance(time_idx, Instant) + else time_idx + ) + ) + ) + self._metric_idx = MetricIndex(metric_idx) + self._entity_idx = EntityIndex(entity_uid_idx) + + # Validate dimensions match + expected_shape = ( + len(self._time_idx), + len(self._metric_idx), + len(self._entity_idx), + ) + if data.shape != expected_shape or len(data.shape) != 3: + raise ValueError( + f"Dimension mismatch: got {data.shape}, expected {expected_shape} " + f"(time × metrics × entities)" + ) + + self._data = data + + def __len__(self) -> int: + """Length of the timeseries.""" + return len(self.time_index) + + @property + def names(self) -> np.ndarray: + """Available metric names.""" + return self._metric_idx.values + + @property + def entity_uids(self) -> np.ndarray: + """Entity identifiers.""" + return self._entity_idx.values + + @property + def shape(self) -> tuple: + """Data shape as (timestamps, metrics, entities).""" + return self._data.shape + + @property + def ndim(self) -> int: + """Number of metrics in the timeseries. + + Returns + ------- + int + The number of metrics in the timeseries. + """ + return len(self.names) + + @property + def values(self) -> np.ndarray: + """Raw data array (view).""" + return self._data.view() + + @property + def time_index(self) -> Union[Period, Instant, np.ndarray]: + """Time index of the series.""" + len_index = len(self._time_idx) + if len_index > 1: + return Period(self._time_idx.values) + elif len_index == 1: + return Instant(self._time_idx.values[0]) + else: + return np.array([]) + + def rename( + self, names: Mapping[str, str], copy: bool = True + ) -> "Timeseries": + """Rename metrics in the timeseries. + + Parameters + ---------- + names : Mapping[str, str] + Dictionary mapping old metric names to new ones. + Example: {"cpu": "cpu_usage", "memory": "mem_usage"} + copy : bool, optional + If True, return a new timeseries. If False, modify in-place. + Defaults to True. + + Returns + ------- + Timeseries + Timeseries with renamed metrics. + + Examples + -------- + >>> ts = Timeseries(...) + >>> # Create new timeseries with renamed metrics + >>> renamed_ts = ts.rename({"cpu": "cpu_usage"}) + >>> + >>> # Rename metrics in-place + >>> ts.rename({"memory": "mem_usage"}, copy=False) + """ + # Get current metric names + current_names = self.names + renamed_names = current_names.copy() + + # Update metric names that need to be renamed + for old_name, new_name in names.items(): + if old_name in current_names: + renamed_names[current_names == old_name] = new_name + + if copy: + # Create new timeseries with renamed metrics + return Timeseries( + time_idx=TimeIndex(self._time_idx.values), + metric_idx=renamed_names, + entity_uid_idx=self._entity_idx.values, + data=self._data.copy(), + ) + else: + # Modify metric names in-place + self._metric_idx = MetricIndex(renamed_names) + return self + + def to_dict(self) -> dict: + """Convert timeseries data to a dictionary. + Can be then converted to a pandas DataFrame or polars Series if needed. + + Returns + ------- + dict + A dictionary containing the timeseries data. + """ + return { + "time": self.time_index.values, + "metric_name": self.names, + "entity_uid": self.entity_uids, + "data": self.values, + } + + def to_array( + self, dtype: Union[np.dtype, None] = None, copy: bool = False + ) -> np.ndarray: + """Convert timeseries data to numpy array. + + Parameters + ---------- + dtype : numpy.dtype, optional + The dtype to cast the data to. If None, keeps original dtype. + copy : bool, optional + Whether to return a copy of the data. If False, returns a view when possible. + + Returns + ------- + numpy.ndarray + The timeseries data as a numpy array. + """ + data = self._data.copy() if copy else self._data.view() + return data.astype(dtype) if dtype is not None else data + + def __getitem__(self, key: Union[Any, tuple]) -> "Timeseries": + """Get subset of timeseries by metric name(s), entity uid(s), or time selection. + + Parameters + ---------- + key : Union[str, List[str], Period, Instant, EntityUID, List[EntityUID], tuple] + Selection criteria: + - str: Single metric name + - List[str]: Multiple metric names + - Period: Time range selection + - Instant: Single time point + - EntityUID: Single entity + - List[EntityUID]: Multiple entities + - tuple: Combination of above types for multi-dimensional selection + + Returns + ------- + Timeseries + New timeseries with selected data. + + Raises + ------ + KeyError + If metric name or entity not found. + ValueError + If time selection is invalid or selection list is empty. + TypeError + If key type is not supported. + + Examples + -------- + >>> # Select single metric + >>> cpu_ts = ts["cpu"] + >>> # Select multiple metrics + >>> resources_ts = ts[["cpu", "memory"]] + >>> # Select time range + >>> period_ts = ts[Period("2024-01-01", "2024-01-02")] + >>> # Select single entity + >>> vm_ts = ts[EntityUID(EntityType.VIRTUAL_MACHINE, 1)] + """ + # Process key into index arrays and new indices + index_arrays = self._process_key(key) + return self.isel(*index_arrays) + + def isel( + self, + time_idx: Union[int, list[int], slice, np.ndarray] = slice(None), + metric_idx: Union[int, list[int], slice, np.ndarray] = slice(None), + entity_idx: Union[int, list[int], slice, np.ndarray] = slice(None), + ) -> Timeseries: + processed_index: np.ndarray = np.empty(3, dtype=object) + for i, sel in enumerate([time_idx, metric_idx, entity_idx]): + if isinstance(sel, (int, np.integer, list, np.ndarray)): + processed_index[i] = np.array([sel], dtype=np.intp).flatten() + elif isinstance(sel, slice): + # NOTE: to consider direct usage of slice for + # selection. Using collection of IDs makes + # copy of data (of underlying NumPy ndarray) + _slice_values = sel.indices(self._data.shape[i]) + processed_index[i] = np.arange(*_slice_values) + else: + raise TypeError(f"Index type {type(sel)} is not supported.") + new_data = self._data[np.ix_(*processed_index)] + + if len(new_data.shape) != 3: + raise ValueError( + f"Internal error: array must be 3D after processing, " + f"got shape {new_data.shape}" + ) + new_time_index = self._time_idx.get_sliced_index(time_idx) + new_metric_index = self._metric_idx.get_sliced_index(metric_idx) + new_entity_index = self._entity_idx.get_sliced_index(entity_idx) + + return Timeseries( + new_time_index, new_metric_index, new_entity_index, new_data + ) + + def _process_key(self, key: Union[Any, tuple]) -> tuple: + """Process selection key and return selections tuple and new indices. + + Parameters + ---------- + key : Union[Any, tuple] + Selection key which can be a single value or tuple of selections. + + Returns + ------- + tuple + A tuple containing: + - tuple of numpy indexing arrays (ready for array indexing) + - new time index + - new metric index + - new entity index + + Raises + ------ + ValueError + If an empty list is provided for any dimension. + TypeError + If an unsupported key type is provided. + """ + # Initialize selections with default slices + selections = np.array([slice(None)] * 3, dtype=object) + time_key = None + + # Convert single key to tuple and process in one pass + keys = (key,) if not isinstance(key, tuple) else key + + # Check for empty lists before any processing + for k in keys: + if isinstance(k, list) and len(k) == 0: + raise ValueError("Empty selection list") + + # Pre-allocate arrays for type checking to avoid multiple isinstance calls + is_time = np.array([isinstance(k, (Period, Instant)) for k in keys]) + is_metric = np.array( + [ + isinstance(k, (str, list)) + and (isinstance(k, str) or all(isinstance(x, str) for x in k)) + for k in keys + ] + ) + is_entity = np.array( + [ + isinstance(k, (EntityUID, list)) + and ( + isinstance(k, EntityUID) + or all(isinstance(x, EntityUID) for x in k) + ) + for k in keys + ] + ) + + # Get time key if present (needed for return value) + if np.any(is_time): + time_key = keys[np.argmax(is_time)] + selections[0] = self._time_idx.get_loc(time_key) + + # Process metric and entity selections + if np.any(is_metric): + selections[1] = self._metric_idx.get_loc( + keys[np.argmax(is_metric)] + ) + if np.any(is_entity): + selections[2] = self._entity_idx.get_loc( + keys[np.argmax(is_entity)] + ) + + # Validate no unknown types + if not np.all(is_time | is_metric | is_entity): + invalid_idx = np.where(~(is_time | is_metric | is_entity))[0][0] + raise TypeError(f"Unsupported key type: {type(keys[invalid_idx])}") + + # STEP 1: Convert all selection types to numpy arrays + # This ensures consistent handling regardless of input type (slice, list, int, etc.) + return tuple(selections) + + @classmethod + def read_from_database( + cls, + connection: Any, + table_name: str, + metric_name: str, + timestamp_col: str, + value_col: str, + time: Union[Period, Instant], + tolerance: timedelta, + interpolate: bool = True, + ) -> "Timeseries": + """Read timeseries data from a database. + + Parameters + ---------- + connection : Any + Database connection object that supports cursor() and execute() + table_name : str + Name of the table to query + metric_name : str + Name of the metric being queried + timestamp_col : str + Name of the timestamp column + value_col : str + Name of the value column + time : Union[Period, Instant] + Time range or instant to query + tolerance : timedelta + Time tolerance to add/subtract from query bounds + interpolate : bool, optional + Whether to interpolate missing values, by default True + + Returns + ------- + Timeseries + A new timeseries containing the queried data + """ + # Prepare query time bounds + if isinstance(time, Period): + start = (time.start - tolerance).timestamp() + end = (time.end + tolerance).timestamp() + time_index = time.values + elif isinstance(time, Instant): + start = (time.value - tolerance).timestamp() + end = (time.value + tolerance).timestamp() + time_index = np.array([time.value]) + else: + raise TypeError( + "Invalid time parameter. Must be of type Instant or Period." + ) + + # Construct and execute query + query = f""" + SELECT {timestamp_col}, {value_col} + FROM {table_name} + WHERE {timestamp_col} BETWEEN '{start}' AND '{end}' + ORDER BY {timestamp_col} ASC; + """ + + try: + cursor = connection.cursor() + cursor.execute(query) + rows = cursor.fetchall() + finally: + cursor.close() + + if not rows: + # Return empty timeseries with NaN values + return cls( + time_idx=time_index, + metric_idx=np.array([metric_name]), + entity_uid_idx=np.array( + [EntityUID(EntityType.VIRTUAL_MACHINE, -1)] + ), + data=np.full((len(time_index), 1, 1), np.nan), + ) + + # Convert timestamps and check for duplicates + try: + from datetime import datetime, timezone + + db_timestamps = np.array( + [datetime.fromtimestamp(row[0], timezone.utc) for row in rows], + dtype="object", + ) + except ValueError as e: + raise ValueError(f"Invalid timestamp format in database: {e}") + + # Check for duplicate timestamps + _, counts = np.unique(db_timestamps, return_counts=True) + if np.any(counts > 1): + raise ValueError("Duplicate timestamps found in database results") + + # Convert values to numpy array + db_values = [] + for row in rows: + value = row[1] + if value is None: + db_values.append(np.nan) + else: + try: + db_values.append(float(value)) + except (ValueError, TypeError): + raise TypeError(f"Cannot convert value '{value}' to float") + db_values = np.array(db_values, dtype=np.float32) + + # Convert time_index to numpy datetime for comparison + time_idx_np = np.array(time_index, dtype="object") + + # Create unified sorted time index + all_times = np.unique(np.concatenate([time_idx_np, db_timestamps])) + + # Create result array filled with NaN + result_data = np.full((len(all_times), 1, 1), np.nan, dtype=np.float32) + + # Find indices for time alignment + db_indices = np.searchsorted(all_times, db_timestamps) + + # Fill data at correct time positions + result_data[db_indices, 0, 0] = db_values + + if interpolate: + # TODO: Use the TSQuality framework to interpolate missing values and decide what interpolation method to use + valid_mask = ~np.isnan(result_data[:, 0, 0]) + x = np.arange(len(all_times)) + if np.any(valid_mask): + x_valid = x[valid_mask] + y_valid = result_data[valid_mask, 0, 0] + result_data[:, 0, 0] = np.interp(x, x_valid, y_valid) + + # Get final values at requested times + final_indices = np.searchsorted(all_times, time_idx_np) + final_data = result_data[final_indices] + + return cls( + time_idx=time_index, + metric_idx=np.array([metric_name]), + entity_uid_idx=np.array( + [EntityUID(EntityType.VIRTUAL_MACHINE, -1)] + ), + data=final_data, + ) + + # + # Mathematical Operations (TODO) + # + + def __add__(self, other: Union[Timeseries, float, int]) -> Timeseries: + """Add two timeseries or add a scalar to a timeseries. + + Parameters + ---------- + other : Union[Timeseries, float, int] + The timeseries or scalar to add. + + Returns + ------- + Timeseries + A new timeseries containing the sum. + + Notes + ----- + When adding two timeseries: + - Time indices are aligned using their union + - Missing values are filled with NaN + - Metrics must match between the two timeseries + """ + if isinstance(other, (float, int)): + # For scalar addition, simply add to all values + return Timeseries( + time_idx=self._time_idx, + metric_idx=self._metric_idx.values, + entity_uid_idx=self._entity_idx.values, + data=self._data + other, + ) + elif isinstance(other, Timeseries): + # Validate metric names match + if not np.array_equal(self.names, other.names): + raise ValueError( + "Cannot add timeseries with different metric names" + ) + + # Find union of time indices and sort them + all_times = np.unique( + np.concatenate([self._time_idx.values, other._time_idx.values]) + ) + + # Create result array filled with NaN + result_data = np.full( + (len(all_times), len(self.names), len(self._entity_idx)), + np.nan, + dtype=np.float32, + ) + + # Find indices for time alignment + self_time_indices = np.searchsorted( + all_times, self._time_idx.values + ) + other_time_indices = np.searchsorted( + all_times, other._time_idx.values + ) + + # Fill data from both timeseries + result_data[self_time_indices] = self._data + result_data[other_time_indices] += other._data + + return Timeseries( + time_idx=all_times, + metric_idx=self._metric_idx.values, + entity_uid_idx=self._entity_idx.values, + data=result_data, + ) + else: + return NotImplemented + + def __radd__(self, other: Union[float, int]) -> Timeseries: + """Implement reverse addition.""" + return self.__add__(other) + + def append(self, other: "Timeseries") -> "Timeseries": + """Append another timeseries to this one. + + Parameters + ---------- + other : Timeseries + The timeseries to append + + Returns + ------- + Timeseries + A new timeseries containing the concatenated data + + Notes + ----- + - The timeseries must have the same metrics + - The timestamps must not overlap + - The result will be sorted by time + """ + # Handle empty cases + if len(other._time_idx) == 0: + return Timeseries( + time_idx=self._time_idx, + metric_idx=self._metric_idx.values, + entity_uid_idx=self._entity_idx.values, + data=self._data.copy(), + ) + if len(self._time_idx) == 0: + return Timeseries( + time_idx=other._time_idx, + metric_idx=other._metric_idx.values, + entity_uid_idx=other._entity_idx.values, + data=other._data.copy(), + ) + + # Verify metrics match + if not np.array_equal(self.names, other.names): + raise ValueError("Cannot append timeseries with different metrics") + + # Get time indices and check for overlaps + all_times = np.concatenate( + [self._time_idx.values, other._time_idx.values] + ) + unique_times = np.unique(all_times) + if len(unique_times) != len(all_times): + raise ValueError( + "Cannot append timeseries with overlapping timestamps." + ) + + # Sort by time + sort_idx = np.argsort(all_times) + all_times = all_times[sort_idx] + + # Create new data array by concatenating and sorting + new_data = np.concatenate([self._data, other._data], axis=0)[sort_idx] + + return Timeseries( + time_idx=all_times, + metric_idx=self._metric_idx.values, + entity_uid_idx=self._entity_idx.values, + data=new_data, + ) + + def to_json(self) -> str: + """Convert timeseries data to JSON string. + + Returns + ------- + str + JSON string representation of the timeseries data. + Format: {"metric_name": {timestamp_ms: value, ...}, ...} + where timestamp_ms is Unix timestamp in milliseconds. + """ + # Convert timestamps to epoch in seconds + time_ms = np.array( + [int(t.timestamp()) for t in self._time_idx.values] + ) + + # Create dictionary for each metric + result = {} + for i, metric_name in enumerate(self.names): + # Get values for this metric (assuming single entity for now) + values = self._data[:, i, 0] + # Create timestamp:value mapping + result[metric_name] = { + int(t): round(float(v), 2) for t, v in zip(time_ms, values) + } + + return json.dumps(result, separators=(",", ":")) diff --git a/src/im_mad/remotes/lib/python/pyoneai/ml/__init__.py b/src/im_mad/remotes/lib/python/pyoneai/ml/__init__.py new file mode 100644 index 0000000000..fedfb4f89e --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/ml/__init__.py @@ -0,0 +1,35 @@ +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +try: + import statsmodels +except ImportError: + pass +else: + from .arima_prediction_model import ArimaPredictionModel + +from .artifact_manager import ArtifactManager +from .base_prediction_model import BasePredictionModel +from .fourier_prediction_model import FourierPredictionModel +from .persistence_prediction_model import PersistencePredictionModel + +try: + import sklearn +except ImportError: + pass +else: + from .hgbt_prediction_model import HgbtPredictionModel + +from .manifest import Manifest +from .model_config import ModelConfig diff --git a/src/im_mad/remotes/lib/python/pyoneai/ml/arima_prediction_model.py b/src/im_mad/remotes/lib/python/pyoneai/ml/arima_prediction_model.py new file mode 100644 index 0000000000..4f432373ca --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/ml/arima_prediction_model.py @@ -0,0 +1,159 @@ +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import warnings +from typing import ClassVar + +import numpy as np + +from ..core.time import Instant, Period +from ..core.tsnumpy.timeseries import Timeseries +from .base_prediction_model import BasePredictionModel +from .model_config import ModelConfig +from .utils import get_class + + +class ArimaPredictionModel(BasePredictionModel): + """ + Implement an ARIMA prediction model for time series data. + + The ARIMA model is fit on-the-fly during each call to the + `predict` method. + + Attributes + ---------- + model_config : ModelConfig + The configuration of the model. + model : ArimaModel + The ARIMA model used, initialized to None until predict. + __SUPPORTS_CI__ : bool + Whether the model supports confidence intervals. + """ + __SUPPORTS_CI__: ClassVar[bool] = False + + def fit( + self, + metric: Timeseries, + ) -> ArimaPredictionModel: + """ + Do not train the ARIMA model as it will be fitted in the + `predict` method. + + Parameters + ---------- + metric : Timeseries + The metric used to train the model (univariate or + multivariate). + + Returns + ------- + ArimaPredictionModel + The instance of the ArimaPredictionModel, without + performing any fitting as it's done on-the-fly in + `predict`. + """ + return self + + def predict(self, metric: Timeseries, horizon: int = 1) -> Timeseries: + """ + Generate predictions using the ARIMA model. + + The ARIMA model is fit on-the-fly to the provided metric. + + Parameters + ---------- + metric : Timeseries + The metric data (univariate or multivariate) used for + fitting the ARIMA model and making predictions. + horizon : int + The number of steps into the future to predict (default + is 1). + + Returns + ------- + Timeseries + A Timeseries object containing the predictions generated by the + ARIMA model. + """ + model_class = get_class(self.model_config.model_class) + predictions = [] + + last_ts = metric.time_index.values[-1] + + for name in metric.names: + act_metric = metric[name] + metric_data = act_metric.to_array() + + if len(metric_data) == 1: + warnings.warn( + "Only one historical step is used. Returning the " + " latest value for the prediction." + ) + last_value = metric_data[-1] + forecast = np.repeat(last_value, horizon) + else: + model = model_class( + metric_data, **self.model_config.hyper_params + ) + fitted_model = model.fit() + + forecast = fitted_model.forecast(steps=horizon) + + if horizon == 1: + prediction_time_index = [ + Instant(last_ts + metric.frequency).value + ] + else: + prediction_time_index = Period( + slice( + last_ts + metric.frequency, + last_ts + horizon * metric.frequency, + metric.frequency, + ) + ).values + + predicted_metric = Timeseries( + prediction_time_index, {name: forecast} + ) + list_metric_predictions.append(predicted_metric) + + return Timeseries.multivariate(list_metric_predictions) + + @classmethod + def load( + cls, model_config: ModelConfig, checkpoint: io.BytesIO | None = None + ) -> ArimaPredictionModel: + """ + Load an ARIMA model with the specified model configuration. + + This method does not utilize checkpoints as ARIMA is fit + on-the-fly during prediction. + + Parameters + ---------- + model_config : ModelConfig + The model configuration used to load the ARIMA model. + checkpoint : str or os.PathLike or None + Ignored, as ARIMA does not require checkpoint-based loading + (default is None). + + Returns + ------- + ArimaPredictionModel + An instance of the ArimaPredictionModel with the loaded + configuration. + """ + return cls(model_config) diff --git a/src/im_mad/remotes/lib/python/pyoneai/ml/artifact_manager.py b/src/im_mad/remotes/lib/python/pyoneai/ml/artifact_manager.py new file mode 100644 index 0000000000..1dc9b3d675 --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/ml/artifact_manager.py @@ -0,0 +1,160 @@ +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +__all__ = ("ArtifactManager",) + +import os +import warnings +from dataclasses import asdict +from pathlib import Path +from typing import Union + +import yaml + +from .base_prediction_model import BasePredictionModel +from .manifest import Manifest +from .model_config import ModelConfig +from .utils import get_class + + +def _read_manifest(manifest_path: Path) -> Manifest: + if not manifest_path.exists(): + raise FileNotFoundError( + f"Manifest file '{manifest_path}' doesn't exist." + ) + + with open(manifest_path, "r") as manifest_file_stream: + manifest_data = yaml.safe_load(manifest_file_stream) + manifest = Manifest(**manifest_data) + + return manifest + + +def _get_model_config(manifest_path: Path, manifest: Manifest) -> ModelConfig: + config_path: Path = Path(manifest.model_configuration_file) + if not config_path.is_absolute(): + config_path = manifest_path.parent / config_path + + if not config_path.exists(): + raise FileNotFoundError( + f"Model configuration file '{config_path}' " "doesn't exist." + ) + + with open(config_path, "r") as config_file: + config_data = yaml.safe_load(config_file) + config = ModelConfig(**config_data) + return config + + +def _maybe_get_checkpoint_path( + manifest_path: Path, manifest: Manifest +) -> Union[Path, None]: + checkpoint_path: Union[Path, None] = None + if manifest.checkpoint_file: + checkpoint_path = Path(manifest.checkpoint_file) + + if not checkpoint_path.is_absolute(): + checkpoint_path = manifest_path.parent / checkpoint_path + + if not checkpoint_path.exists(): + warnings.warn( + "Checkpoint path was passed but the file could " + "not be found. It will be ignored." + ) + return checkpoint_path + + +class ArtifactManager: + """ + Manage saving and loading of predictor models using a manifest file. + """ + + @classmethod + def save( + cls, + model: BasePredictionModel, + config_path: Union[str, os.PathLike], + manifest_path: Union[str, os.PathLike], + checkpoint_path: Union[str, os.PathLike, None] = None, + ) -> None: + """ + Save the model configuration, checkpoint, and manifest. + + Parameters + ---------- + model : BasePredictionModel + The ML model to save. + config_path : str or os.PathLike + Path where the ML model configuration will be saved. + manifest_path : str or os.PathLike + Path where the manifest will be saved. + checkpoint_path : str or os.PathLike or None + Path where the ML model checkpoint will be saved (default is + None). + """ + model.save(config_path, checkpoint_path) + + manifest = Manifest( + prediction_model_type=f"{model.__class__.__module__}.{model.__class__.__name__}", + model_configuration_file=Path(config_path), + checkpoint_file=( + Path(checkpoint_path) + if checkpoint_path and os.path.exists(checkpoint_path) + else None + ), + ) + + with open(manifest_path, "w") as manifest_file: + yaml.safe_dump(asdict(manifest), manifest_file) + + @classmethod + def load( + cls, manifest_path: Union[str, os.PathLike] + ) -> BasePredictionModel: + """ + Load a prediction model using a manifest YAML file. + + Parameters + ---------- + manifest_path : str or os.PathLike + Path to the manifest YAML file with model configuration and + checkpoint information. + + Returns + ------- + The loaded prediction model. + + Raises + ------ + FileNotFoundError + If the manifest or model configuration file doesn't exist + TypeError + If the model class is not a subclass of BasePredictionModel + """ + _manifest_path: Path = Path(manifest_path) + manifest: Manifest = _read_manifest(_manifest_path) + config: ModelConfig = _get_model_config(_manifest_path, manifest) + checkpoint: Union[Path, None] = _maybe_get_checkpoint_path( + _manifest_path, manifest + ) + + model_cls = get_class(manifest.prediction_model_type) + if not issubclass(model_cls, BasePredictionModel): + raise TypeError( + f"Model class '{manifest.prediction_model_type}' " + "is not a subclass of BasePredictionModel." + ) + model_obj = model_cls.load(config, checkpoint) + + return model_obj diff --git a/src/im_mad/remotes/lib/python/pyoneai/ml/base_prediction_model.py b/src/im_mad/remotes/lib/python/pyoneai/ml/base_prediction_model.py new file mode 100644 index 0000000000..9d6a1a94da --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/ml/base_prediction_model.py @@ -0,0 +1,208 @@ +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import os +import warnings +from abc import ABCMeta, abstractmethod +from dataclasses import asdict +import numpy as np +from pathlib import Path +from typing import Any, ClassVar + +import yaml + +from ..core.time import Period, Instant +from ..core.tsnumpy.timeseries import Timeseries, TimeIndex +from .model_config import ModelConfig +from .utils import get_class + + +class BasePredictionModel(metaclass=ABCMeta): + """ + Abstract base class for prediction models. + + It provides an interface to facilitate integration with + different artificial intelligence frameworks. The base class + provides a basic implementation for saving a model - + it saves the configuration YAML file. + + Parameters + ---------- + model_config : ModelConfig + The configuration of the model. + + Attributes + ---------- + model_config : ModelConfig + The configuration of the model. + model + The model used for predictions. + __SUPPORTS_CI__ : bool + Whether the model supports confidence intervals, default + is True + """ + + __SUPPORTS_CI__: ClassVar[bool] = True + + def __init__(self, model_config: ModelConfig): + self.model_config = model_config + self.model = None + if self.model_config.compute_ci and not self.__SUPPORTS_CI__: + warnings.warn( + f"Model of type {type(self).__name__} does not " + "support computation of confidence intervals. " + "That option will be ignored." + ) + + def init_model(self) -> Any: + """ + Initialize the model based on the model configuration. + + Returns + ------- + Any + An instance of the artificial intelligence method class. + """ + model_class = get_class(self.model_config.model_class) + return model_class(**self.model_config.hyper_params) + + def _forecast_time_index( + self, metric: Timeseries, horizon: int + ) -> TimeIndex: + time_index = metric.time_index + if isinstance(time_index, Instant): + last_time = time_index.value + elif isinstance(time_index, Period): + last_time = time_index.values[-1] + else: + raise ValueError("Unknown time index type") + + freq = metric._time_idx.frequency + + return TimeIndex(np.array( + [last_time + (i + 1) * freq for i in range(horizon)]) + ) + + + @abstractmethod + def fit( + self, + metric: Timeseries, + ) -> BasePredictionModel: + """ + Train the model using the given metric. + + Parameters + ---------- + metric : Timeseries + The metric used to train the model (univariate or + multivariate). + + Returns + ------- + BasePredictionModel + The BasePredictionModel with the model trained. + + Raises + ------ + NotImplementedError + This method must be implemented by subclasses. + """ + raise NotImplementedError + + @abstractmethod + def predict(self, metric: Timeseries, horizon: int = 1) -> Timeseries: + """ + Predict future values for the given metric. + + Parameters + ---------- + metric : Timeseries + The metric data for generating predictions (univariate or + multivariate). + horizon : int + The number of steps ahead to predict (default is 1). + + Returns + ------- + Timeseries + The prediction results of the model. + + Raises + ------ + NotImplementedError + This method must be implemented by subclasses. + """ + raise NotImplementedError + + @classmethod + @abstractmethod + def load( + cls, + model_config: ModelConfig, + checkpoint: str | os.PathLike | None = None, + ) -> BasePredictionModel: + """ + Load a model based on provided configuration and checkpoint. + + It initializes the model and loads the state from the + checkpoint if provided. + + Parameters + ---------- + model_config : ModelConfig + The model configuration used to load the model. + checkpoint : str or os.PathLike or None + A file path to the model's checkpoint from which the model + state is loaded (default is None). + + Returns + ------- + BasePredictionModel + An instance of the BasePredictionModel with the loaded + model. + + Raises + ------ + NotImplementedError + This method must be implemented by subclasses. + """ + raise NotImplementedError + + def save( + self, + model_config_path: os.PathLike | str, + checkpoint_path: os.PathLike | str | None = None, + ) -> None: + """ + Save the model configuration and state. + + The default implementation saves just the model configuration + YAML file. + + Parameters + ---------- + model_config_path : os.PathLike or str + The file path where the model configuration (ModelConfig) + will be saved. + checkpoint_path : os.PathLike or str or None + The file path where the model checkpoint will be saved. + If None, the model checkpoint will not be saved. + """ + model_config_file = Path(model_config_path) + model_config_file.parent.mkdir(parents=True, exist_ok=True) + with open(model_config_path, "w") as model_config_file: + yaml.safe_dump(asdict(self.model_config), model_config_file) diff --git a/src/im_mad/remotes/lib/python/pyoneai/ml/fourier_prediction_model.py b/src/im_mad/remotes/lib/python/pyoneai/ml/fourier_prediction_model.py new file mode 100644 index 0000000000..0719ff948f --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/ml/fourier_prediction_model.py @@ -0,0 +1,222 @@ +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import os +from typing import Callable, ClassVar + +import numpy as np + +from ..core.tsnumpy import Timeseries +from .base_prediction_model import BasePredictionModel +from .model_config import ModelConfig +from pyoneai.core.entity_uid import EntityType, EntityUID + + +class FourierPredictionModel(BasePredictionModel): + __SUPPORTS_CI__: ClassVar[bool] = False + + def __init__(self, model_config: ModelConfig): + super().__init__(model_config) + self.nbr_freqs_to_keep = model_config.hyper_params.get( + "nbr_freqs_to_keep", 40 + ) + + def _get_freqs_to_keep(self, metric: Timeseries): + """ + Compute number of FFT strongest frequencies to keep. + + It returns the value of the provided hyper-parameter named + `nbr_freqs_to_keep` or the number of frequencies in the + input metric, if it is shorter than `nbr_freqs_to_keep`. + """ + if self.nbr_freqs_to_keep < 1 or self.nbr_freqs_to_keep > len(metric): + return len(metric) + return self.nbr_freqs_to_keep + + def _find_trend_func(self, metric: Timeseries) -> Callable[[int], float]: + """ + Find trend function for the timeseries. + + Fits the line in the log-transformed timeseries. + """ + assert metric.ndim == 1 + values = metric.to_array().squeeze() + trend_coeff = np.polyfit( + range(len(metric)), np.log(values + 1), 1 + ) + return lambda x: np.exp(np.poly1d(trend_coeff)(x)) - 1 + + def _detrend( + self, metric: Timeseries, trend_func: Callable[[int], float] + ) -> Timeseries: + """Remove trend from the timeseries. + + Parameters + ---------- + metric : Timeseries + The metric to detrend. + trend_func : Callable[[int], float] + The trend function to remove. + + Returns + ------- + Timeseries + The detrended timeseries. + """ + assert metric.ndim == 1 + trend_values = np.array([trend_func(i) for i in range(len(metric))]) + detrended_values = metric.to_array().squeeze() - trend_values + + return Timeseries( + time_idx=metric.time_index, + metric_idx=np.array([metric.names[0]]), + entity_uid_idx=np.array([EntityUID(EntityType.VIRTUAL_MACHINE, -1)]), + data=detrended_values.reshape(-1, 1, 1), + ) + + def _find_seasonality_func( + self, detrend_metric: Timeseries + ) -> Callable[[int], float]: + """Find FFT seasonality pattern in the detrended timeseries. + + Computes FFT features and leaves just the strongest ones. + Number of the FFT features to keep are computed based on the + provided hyper-parameter `nbr_freqs_to_keep` or the length of + the input metric, if it is shorter than `nbr_freqs_to_keep`. + + Parameters + ---------- + detrend_metric : Timeseries + The detrended timeseries. + + Returns + ------- + Callable[[int], float] + The seasonality function. + """ + assert detrend_metric.ndim == 1 + freqs_to_keep = self._get_freqs_to_keep(detrend_metric) + # Extract data values directly from the data array + values = detrend_metric.to_array().squeeze() + fft = np.fft.fft(values) + strongest_freqs_idx = np.argpartition(abs(fft), -freqs_to_keep)[ + -freqs_to_keep: + ] + fft_filtered = np.zeros(len(fft), dtype=np.complex128) + fft_filtered[strongest_freqs_idx] = fft[strongest_freqs_idx] + _predicted_vals = np.fft.ifft(fft_filtered).real + return lambda x: _predicted_vals[x % len(_predicted_vals)] + + def _generate_trend_forecasts( + self, + metric: Timeseries, + trend_func: Callable[[int], float], + horizon: int, + ) -> np.ndarray: + return np.array( + [trend_func(len(metric) + i + 1) for i in range(horizon)] + ) + + def _generate_seasonal_forecasts( + self, + metric: Timeseries, + seasonal_func: Callable[[int], float], + horizon: int, + ) -> np.ndarray: + return np.array( + [seasonal_func(len(metric) + i + 1) for i in range(horizon)] + ) + + def _predict_univariate( + self, metric: Timeseries, horizon: int + ) -> Timeseries: + """Predict univariate time series based on FFT features.""" + assert metric.ndim == 1, "Function expects univariate timeseries" + trend_func = self._find_trend_func(metric) + detrend_metric = self._detrend(metric, trend_func) + seasonal_func = self._find_seasonality_func(detrend_metric) + + trend_forecast = self._generate_trend_forecasts( + metric, trend_func, horizon + ) + seasonal_forecast = self._generate_seasonal_forecasts( + detrend_metric, seasonal_func, horizon + ) + forecast_vals = trend_forecast + seasonal_forecast + + time_index = self._forecast_time_index(metric, horizon) + return Timeseries( + time_idx=time_index, + metric_idx=np.array([metric.names[0]]), + entity_uid_idx=np.array([EntityUID(EntityType.VIRTUAL_MACHINE, -1)]), + data=forecast_vals.reshape(-1, 1, 1) + ) + + def fit(self, metric: Timeseries): + return self + + def predict(self, metric: Timeseries, horizon: int = 1) -> Timeseries: + """ + Predict future time series values based on FFT features. + + Parameters + ---------- + metric : Timeseries + The historical metric values to use to predict. + horizon : int, optional + The number of future time steps to predict, by default 1 + + Returns + ------- + Timeseries + The predicted future time series with `horizon` values + """ + if metric.ndim == 1: + return self._predict_univariate(metric, horizon) + elif metric.ndim > 1: + # Get predictions for each metric + predictions = [] + for i, metric_name in enumerate(metric.names): + # Extract the single metric using string indexing + single_metric = metric[metric_name] + predictions.append(self._predict_univariate(single_metric, horizon)) + + # Combine predictions into a single multivariate timeseries + # All predictions should have the same time index since they use the same horizon + time_idx = predictions[0]._time_idx + metric_names = np.array([p.names[0] for p in predictions]) + entity_uid_idx = predictions[0]._entity_idx.values + + # Combine data arrays along the metric dimension (axis=1) + data_arrays = [p._data for p in predictions] + combined_data = np.concatenate(data_arrays, axis=1) + + return Timeseries( + time_idx=time_idx, + metric_idx=metric_names, + entity_uid_idx=entity_uid_idx, + data=combined_data + ) + else: + raise ValueError("Timeseries does not contain data") + + @classmethod + def load( + cls, + model_config: ModelConfig, + checkpoint: str | os.PathLike | None = None, + ) -> FourierPredictionModel: + return cls(model_config) diff --git a/src/im_mad/remotes/lib/python/pyoneai/ml/hgbt_prediction_model.py b/src/im_mad/remotes/lib/python/pyoneai/ml/hgbt_prediction_model.py new file mode 100644 index 0000000000..c7371f5f58 --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/ml/hgbt_prediction_model.py @@ -0,0 +1,371 @@ +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import importlib +import os +import pickle +from pathlib import Path +from typing import Any, ClassVar + +import numpy as np +from sklearn.model_selection import TimeSeriesSplit + +from ..core.time import Period +from ..core.tsnumpy.timeseries import Timeseries +from .base_prediction_model import BasePredictionModel +from .model_config import ModelConfig +from .utils import get_class + +__HAS_PANDAS__ = False +__HAS_POLARS__ = False + +if importlib.util.find_spec("pandas"): + import pandas as pd + from pandas import Series + + __HAS_PANDAS__ = True +elif importlib.util.find_spec("polars"): + import polars as pl + from polars import Series + + __HAS_POLARS__ = True +else: + raise ImportError( + "Neither 'polars' nor 'pandas' is installed. Please install at least one of them." + ) + + +class HgbtPredictionModel(BasePredictionModel): + """ + Implement a Histogram Gradient Boosing tree (HGBT) regressor model. + + The HGBT model is fit on-the-fly during each call of the + `predict` method. + """ + __SUPPORTS_CI__: ClassVar[bool] = True + MIN_N_SPLITS: ClassVar[int] = 200 + + is_fit: bool + _context_length: int + _max_iter: int + _compute_ci: bool + gbrt_mean: Any + gbrt_q5: Any + gbrt_q95: Any + + def __init__(self, model_config: ModelConfig): + super().__init__(model_config) + self._is_fit = False + self._max_iter = self.model_config.training_params.get("max_iter", 100) + self._context_length = self.model_config.training_params.get( + "context_length", 200 + ) + self._compute_ci = self.model_config.compute_ci + self.gbrt_mean, self.gbrt_q5, self.gbrt_q95 = ( + self._configure_regressors() + ) + + def _configure_regressors(self) -> tuple[Any, Any, Any]: + gbrt_mean = gbrt_q5 = gbrt_q95 = None + model_class = get_class(self.model_config.model_class) + gbrt_mean = model_class(loss="poisson", max_iter=self._max_iter) + if self._compute_ci: + gbrt_q5 = model_class( + loss="quantile", quantile=0.05, max_iter=self._max_iter + ) + gbrt_q95 = model_class( + loss="quantile", quantile=0.95, max_iter=self._max_iter + ) + return (gbrt_mean, gbrt_q5, gbrt_q95) + + def _validate_fit_metric(self, metric: Timeseries): + index = metric.time_index + if not index.is_monotonic_increasing: + raise ValueError("Time series must be monotonic " "increasing.") + if not index.is_unique: + raise ValueError("Time series must have unique index.") + + if len(metric) < self.MIN_N_SPLITS + self._context_length: + raise ValueError( + f"The passed context length {self._context_length} " + f"is too long or the time series is too short ({len(metric)}) " + "to train a model with the specified number of splits. " + "Number of observations must be at least " + f"{self.MIN_N_SPLITS}+, in your case:" + f"({self.MIN_N_SPLITS + self._context_length})." + ) + if metric.ndim > 1: + raise ValueError( + "Histogram-based Gradient Boosting Tree can be " + "trained for univariate time series only." + ) + if any(np.isnan(metric)): + raise ValueError("Time series cannot contain NaN values.") + + def _validate_forecast_metric(self, metric: Timeseries): + if len(metric) < self._context_length: + raise ValueError( + "The passed historical context (time series) on length " + f"{len(metric)} is too short. It needs to be of the length " + "not less than predefined conext length " + f"({self._context_length})." + ) + + def _prepare_splits( + self, metric: Timeseries + ) -> list[tuple[np.ndarray, np.ndarray]]: + return list( + TimeSeriesSplit( + n_splits=len(metric) - self._context_length, + max_train_size=self._context_length, + test_size=1, + ).split(metric) + ) + + def _get_forecast_index( + self, metric: Timeseries, horizon: int = 1 + ) -> np.ndarray: + + last_ts = metric.time_index.values[-1] + + return Period( + slice( + last_ts, last_ts + horizon * metric.frequency, metric.frequency + ) + ).values[1:] + + def _fit(self, metric: Timeseries) -> None: + self._validate_fit_metric(metric) + splits = self._prepare_splits(metric) + data = metric.to_dataframe() + if __HAS_PANDAS__: + x = np.array( + [data.iloc[idx[0]].values for idx in splits] + ).squeeze() + y = np.array( + [data.iloc[idx[1]].values for idx in splits] + ).squeeze() + elif __HAS_POLARS__: + x = np.array( + [ + data[idx[0]].select(data.columns[1]).to_numpy() + for idx in splits + ] + ).squeeze() + y = np.array( + [ + data[idx[1]].select(data.columns[1]).to_numpy() + for idx in splits + ] + ).squeeze() + self.gbrt_mean.fit(x, y) + if self._compute_ci: + self.gbrt_q5.fit(x, y) + self.gbrt_q95.fit(x, y) + + def fit( + self, + metric: Timeseries, + ) -> HgbtPredictionModel: + """ + Train the HGBT model with the passed time series. + + Parameters + ---------- + metric : Timeseries + The metric used to train the model (univariate or + multivariate). + + Returns + ------- + HgbtPredictionModel + The instance of the fitted HgbtPredictionModel. + """ + self._fit(metric) + self._is_fit = True + return self + + def _forecast_with_ci( + self, + name: str, + x: Series, + forecast_index: np.ndarray, + horizon: int, + ) -> Timeseries: + preds_mean = [] + preds_q5 = [] + preds_q95 = [] + + if __HAS_PANDAS__: + x_feed = x.values.reshape(1, -1) + elif __HAS_POLARS__: + x_feed = x.to_numpy().reshape(1, -1) + for _ in range(horizon): + preds_mean.append(self.gbrt_mean.predict(x_feed)) + preds_q5.append(self.gbrt_q5.predict(x_feed)) + preds_q95.append(self.gbrt_q95.predict(x_feed)) + x_feed = np.roll(x_feed, -1) + # NOTE: simple assigning + # x_feed[-1] = preds_mean[-1] + # replaces all values to preds_mean[-1] + np.put(x_feed, -1, preds_mean[-1]) + + return Timeseries( + time_index=forecast_index, + data={ + name: np.array(preds_mean).squeeze(), + f"{name}_lower": np.array(preds_q5).squeeze(), + f"{name}_upper": np.array(preds_q95).squeeze(), + }, + ) + + def _forecast_without_ci( + self, + name: str, + x: Series, + forecast_index: np.ndarray, + horizon: int, + ) -> Timeseries: + preds_mean = [] + + if __HAS_PANDAS__: + x_feed = x.values.reshape(1, -1) + elif __HAS_POLARS__: + x_feed = x.to_numpy().reshape(1, -1) + for _ in range(horizon): + preds_mean.append(self.gbrt_mean.predict(x_feed)) + x_feed = np.roll(x_feed, -1) + # NOTE: simple assigning + # x_feed[-1] = preds_mean[-1] + # replaces all values to preds_mean[-1] + np.put(x_feed, -1, preds_mean[-1]) + + return Timeseries( + time_index=forecast_index, + data={ + name: np.array(preds_mean).squeeze(), + }, + ) + + def predict(self, metric: Timeseries, horizon: int = 1) -> Timeseries: + """ + Generate predictions using the HGBT model. + + The HGBT model is fit on-the-fly to the provided metric. + + Parameters + ---------- + metric : Timeseries + The metric data (univariate or multivariate) used for + fitting the HGBT model and making predictions. + horizon : int + The number of steps into the future to predict (default + is 1). + + Returns + ------- + Timeseries + A Timeseries object containing the predictions generated by the + HGBT model. + """ + self._validate_forecast_metric(metric) + if __HAS_PANDAS__: + all_x = metric.to_dataframe(copy=True).iloc[ + -self._context_length : + ] + elif __HAS_POLARS__: + all_x = metric.to_dataframe(copy=True)[-self._context_length :] + multivariate = [] + for name in metric.names: + x = all_x[name] + if not self._is_fit: + # NOTE: fit on the fly + self._fit(metric[name]) + + forecast_index = self._get_forecast_index(metric, horizon) + + if self._compute_ci: + forecast_ts = self._forecast_with_ci( + name, x, forecast_index, horizon + ) + else: + forecast_ts = self._forecast_without_ci( + name, x, forecast_index, horizon + ) + multivariate.append(forecast_ts) + return Timeseries.multivariate(multivariate) + + @classmethod + def load( + cls, + model_config: ModelConfig, + checkpoint: str | os.PathLike | None = None, + ) -> HgbtPredictionModel: + """ + Load an HGBT model with the specified model configuration. + + This method does not utilize checkpoints as HGBT is fit + on-the-fly during prediction. + + Parameters + ---------- + model_config : ModelConfig + The model configuration used to load the HGBT model. + checkpoint : str or os.PathLike or None + Path with HGBT checkpoint to load, default is None + + Returns + ------- + HgbtPredictionModel + An instance of the HgbtPredictionModel with the loaded + configuration. + """ + model = cls(model_config) + if checkpoint is None: + return model + try: + with open(checkpoint, "rb") as file: + model.gbrt_mean, model.gbrt_q5, model.gbrt_q95 = pickle.load( + file + ) + return model + except ValueError: + raise ValueError( + f"Failed to load HGBT model from checkpoint {checkpoint}." + ) + + def save( + self, + model_config_path: os.PathLike | str, + checkpoint_path: os.PathLike | str | None = None, + ) -> None: + """ + Save the model configuration and state. + + Parameters + ---------- + model_config_path : os.PathLike or str + The file path where the model configuration (ModelConfig) + will be saved. + checkpoint_path : os.PathLike or str or None + The file path where the model checkpoint will be saved. + """ + super().save(model_config_path, checkpoint_path) + if checkpoint_path: + checkpoint_path = Path(checkpoint_path) + checkpoint_path.parent.mkdir(parents=True, exist_ok=True) + with open(checkpoint_path, "wb") as f: + pickle.dump((self.gbrt_mean, self.gbrt_q5, self.gbrt_q95), f) diff --git a/src/im_mad/remotes/lib/python/pyoneai/ml/manifest.py b/src/im_mad/remotes/lib/python/pyoneai/ml/manifest.py new file mode 100644 index 0000000000..a0ff8292f1 --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/ml/manifest.py @@ -0,0 +1,24 @@ +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from pathlib import Path +from typing import Union + + +@dataclass +class Manifest: + prediction_model_type: str + model_configuration_file: Path + checkpoint_file: Union[Path, None] = None diff --git a/src/im_mad/remotes/lib/python/pyoneai/ml/model_config.py b/src/im_mad/remotes/lib/python/pyoneai/ml/model_config.py new file mode 100644 index 0000000000..5c70ca0688 --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/ml/model_config.py @@ -0,0 +1,42 @@ +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from typing import Any, Dict + + +@dataclass +class ModelConfig: + """ + The class with prediction model configuration. + + Attibutes + --------- + model_class : str + The fully qualified name of the model class. + sequence_length : int + The length of the input sequence needed by the model. + compute_ci : bool + If confidence intervals should be computed (if supported by + the model_class, default is True). + hyper_params : dict + The hyper parameters of the model. + training_params : dict + The training parameters of the model. + """ + model_class: str + sequence_length: int + compute_ci: bool = True + hyper_params: Dict[str, Any] = field(default_factory=dict) + training_params: Dict[str, Any] = field(default_factory=dict) diff --git a/src/im_mad/remotes/lib/python/pyoneai/ml/persistence_prediction_model.py b/src/im_mad/remotes/lib/python/pyoneai/ml/persistence_prediction_model.py new file mode 100644 index 0000000000..c9ec327d4d --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/ml/persistence_prediction_model.py @@ -0,0 +1,73 @@ +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import os +from typing import ClassVar + +import numpy as np + +from ..core import EntityUID, EntityType +from ..core.tsnumpy.timeseries import Timeseries +from .base_prediction_model import BasePredictionModel +from .model_config import ModelConfig + + +class PersistencePredictionModel(BasePredictionModel): + __SUPPORTS_CI__: ClassVar[bool] = False + + def fit(self, metric: Timeseries): + return self + + def predict(self, metric: Timeseries, horizon: int = 1) -> Timeseries: + + predictions = [] + time_index = self._forecast_time_index(metric, horizon) + + for name in metric.names: + last_value = metric[name].to_array()[-1] + + predicted_metric = Timeseries( + time_idx=time_index, + metric_idx=np.array([name]), + entity_uid_idx=np.array([EntityUID(EntityType.VIRTUAL_MACHINE, -1)]), + data=np.repeat(last_value, horizon).reshape(-1, 1, 1) + ) + + predictions.append(predicted_metric) + + # Combine predictions into a single multivariate timeseries + # All predictions should have the same time index since they use the same horizon + time_idx = predictions[0]._time_idx + metric_names = np.array([p.names[0] for p in predictions]) + entity_uid_idx = predictions[0]._entity_idx.values + + # Combine data arrays along the metric dimension (axis=1) + data_arrays = [p._data for p in predictions] + combined_data = np.concatenate(data_arrays, axis=1) + return Timeseries( + time_idx=time_idx, + metric_idx=metric_names, + entity_uid_idx=entity_uid_idx, + data=combined_data + ) + + @classmethod + def load( + cls, + model_config: ModelConfig, + checkpoint: str | os.PathLike | None = None, + ) -> PersistencePredictionModel: + return cls(model_config) diff --git a/src/im_mad/remotes/lib/python/pyoneai/ml/utils.py b/src/im_mad/remotes/lib/python/pyoneai/ml/utils.py new file mode 100644 index 0000000000..a042e31902 --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/ml/utils.py @@ -0,0 +1,25 @@ +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from importlib import import_module +from typing import Type + + +def get_class(path: str) -> Type: + """Get class from path.""" + if "." not in path: + raise ValueError(f"Invalid path {path}") + module_name, _, class_name = path.rpartition(".") + module = import_module(module_name) + return getattr(module, class_name) diff --git a/src/im_mad/remotes/lib/python/pyoneai/tests/integration/test_metric.py b/src/im_mad/remotes/lib/python/pyoneai/tests/integration/test_metric.py new file mode 100644 index 0000000000..8e828d33d4 --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/tests/integration/test_metric.py @@ -0,0 +1,248 @@ +import os +import sqlite3 +from datetime import datetime, timedelta, timezone +from unittest.mock import ANY + +import numpy as np +import pytest + +from pyoneai.core import ( + EntityType, + EntityUID, + Instant, + Metric, + MetricAccessor, + MetricAttributes, + Period, + PredictorAccessor, + SQLiteAccessor, + Timeseries, +) +from pyoneai.ml import ( + FourierPredictionModel, + ModelConfig, + PersistencePredictionModel, +) + + +class TestMetric: + + def sample_db(self): + conn = sqlite3.connect(self.db_path) + + entity_uid = "virtualmachine_1" + metric_name = "cpu" + table_name = f"{entity_uid}_{metric_name}_monitoring" + + conn.execute( + f""" + CREATE TABLE IF NOT EXISTS {table_name} ( + TIMESTAMP INTEGER PRIMARY KEY, + VALUE REAL NOT NULL + ) + """ + ) + + start = datetime(2024, 1, 1, 0, 0, 0, tzinfo=timezone.utc) + end = datetime(2024, 12, 31, 23, 59, 59, tzinfo=timezone.utc) + frequency = timedelta(minutes=60) + + times = [] + current = start + while current <= end: + times.append(current) + current += frequency + + data = [] + period = 24 * 3600 + min_value = 0 + max_value = 100 + amplitude = (max_value - min_value) / 2 + offset = (max_value + min_value) / 2 + time_seconds = np.array([(t - start).total_seconds() for t in times]) + data = amplitude * np.sin(2 * np.pi * time_seconds / period) + offset + + conn.executemany( + f"INSERT INTO {table_name} (TIMESTAMP, VALUE) VALUES (?, ?)", + zip([t.timestamp() for t in times], data), + ) + conn.commit() + conn.close() + + @pytest.fixture + def fourier_config_and_model(self): + yield ModelConfig( + model_class="pyoneai.ml.FourierPredictionModel", + sequence_length=100, + hyper_params={"nbr_freqs_to_keep": 40}, + ), FourierPredictionModel + + # @pytest.fixture + # def hgbt_config_and_model(self): + # HgbtPredictionModel.MIN_N_SPLITS = 1 + # yield ModelConfig( + # model_class="sklearn.ensemble.HistGradientBoostingRegressor", + # sequence_length=100, + # training_params={ + # "max_iter": 100, + # "context_length": 10, + # "compute_ci": False, + # }, + # ), HgbtPredictionModel + + # @pytest.fixture + # def arima_config_and_model(self): + # yield ModelConfig( + # model_class="statsmodels.tsa.arima.model.ARIMA", + # sequence_length=100, + # hyper_params={ + # "order": [0, 0, 0], + # "seasonal_order": [0, 0, 0, 0], + # "enforce_stationarity": True, + # "enforce_invertibility": True, + # "concentrate_scale": False, + # "trend_offset": 1, + # }, + # ), ArimaPredictionModel + + @pytest.fixture + def persistence_config_and_model(self): + yield ModelConfig( + model_class="pyoneai.ml.PersistencePredictionModel", + sequence_length=2, + ), PersistencePredictionModel + + # NOTE: this fixture parametrizes the prediction models + @pytest.fixture( + params=[ + "fourier_config_and_model", + # "hgbt_config_and_model", + # "arima_config_and_model", + "persistence_config_and_model", + ] + ) + def config_and_model(self, request): + yield request.getfixturevalue(request.param) + + @pytest.fixture(autouse=True) + def setup(self, config_and_model, tmp_path, mocker): + model_config, prediction_model_class = config_and_model + self.db_path = os.path.join(tmp_path, "test_metrics.db") + self.sample_db() + self.observator = SQLiteAccessor( + db_path=self.db_path, + timestamp_col="TIMESTAMP", + value_col="VALUE", + monitor_interval=3600, + ) + + self.predictor = PredictorAccessor( + prediction_model=prediction_model_class(model_config) + ) + + metric_accessor = MetricAccessor( + observator_accessor=self.observator, + predictor_accessor=self.predictor, + ) + + self.mock_observator_get_ts = mocker.patch.object( + SQLiteAccessor, + "get_timeseries", + wraps=metric_accessor._observator_accessor.get_timeseries, + ) + + self.mock_predictor_get_ts = mocker.patch.object( + PredictorAccessor, + "get_timeseries", + wraps=metric_accessor._predictor_accessor.get_timeseries, + ) + + self.entity_uid = EntityUID(type=EntityType.VIRTUAL_MACHINE, id=1) + self.attrs = MetricAttributes(name="cpu") + + self.metric = Metric( + entity_uid=self.entity_uid, + attrs=self.attrs, + accessor=metric_accessor, + ) + + self.period_past_future = Period( + slice("-1d", "+1d", "1h"), + origin="2024-10-31T10:00+00:00", + ) + + self.period_past = Period( + slice("-1d", "-5h", "1h"), + origin="2024-10-31T23:00+00:00", + ) + + self.period_future = Period( + slice("+1h", "+5h", "1h"), + origin="2024-12-30T23:00+00:00", + ) + + self.instant_past = Instant( + timedelta(days=-1), + origin=datetime(2024, 12, 30, tzinfo=timezone.utc), + ) + self.instant_future = Instant( + timedelta(days=+1), + origin=datetime(2024, 12, 30, tzinfo=timezone.utc), + ) + + def test_metric_past(self): + timeseries = self.metric[self.period_past] + + assert isinstance(timeseries, Timeseries) + assert len(timeseries) == len(self.period_past) + self.mock_observator_get_ts.assert_called_once_with( + self.entity_uid, self.attrs, self.period_past + ) + self.mock_predictor_get_ts.assert_not_called() + # NOTE: Both pandas and polars has to_numpy method to test values + assert np.all(~np.isnan(timeseries.to_array())) + + def test_metric_future(self): + timeseries = self.metric[self.period_future] + + assert isinstance(timeseries, Timeseries) + assert len(timeseries) == len(self.period_future) + self.mock_observator_get_ts.assert_called_once() + self.mock_predictor_get_ts.assert_called_once() + assert np.all(~np.isnan(timeseries.to_array())) + + def test_metric_past_and_future(self): + timeseries = self.metric[self.period_past_future] + + assert isinstance(timeseries, Timeseries) + assert len(timeseries) == len(self.period_past_future) + assert self.mock_observator_get_ts.call_count == 2 + self.mock_predictor_get_ts.assert_called_once() + assert np.all(~np.isnan(timeseries.to_array())) + + def test_metric_instant_past(self): + timeseries = self.metric[self.instant_past] + + assert isinstance(timeseries, Timeseries) + assert len(timeseries) == 1 + self.mock_observator_get_ts.assert_called_once_with( + self.entity_uid, self.attrs, self.instant_past + ) + self.mock_predictor_get_ts.assert_not_called() + assert np.all(~np.isnan(timeseries.to_array())) + + def test_metric_instant_future(self): + timeseries = self.metric[self.instant_future] + + assert isinstance(timeseries, Timeseries) + assert len(timeseries) == 1 + self.mock_observator_get_ts.assert_called_once_with( + self.entity_uid, self.attrs, ANY + ) + self.mock_predictor_get_ts.assert_called_once_with( + self.entity_uid, + self.attrs, + self.instant_future, + observator_accessor=self.observator, + ) + assert np.all(~np.isnan(timeseries.to_array())) diff --git a/src/im_mad/remotes/lib/python/pyoneai/tests/unit/__init__.py b/src/im_mad/remotes/lib/python/pyoneai/tests/unit/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/im_mad/remotes/lib/python/pyoneai/tests/unit/test_core/test_metric.py b/src/im_mad/remotes/lib/python/pyoneai/tests/unit/test_core/test_metric.py new file mode 100644 index 0000000000..f78816712b --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/tests/unit/test_core/test_metric.py @@ -0,0 +1,130 @@ +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from datetime import datetime, timedelta, timezone +from numbers import Number +from unittest.mock import MagicMock + +import pytest + +from pyoneai.core import ( + EntityUID, + Instant, + Metric, + MetricAccessor, + MetricAttributes, + Period, +) +from pyoneai.core.tsnumpy import Timeseries + + +class TestMetric: + @pytest.fixture(autouse=True) + def setup(self, mocker): + self.mock_entity_uid = mocker.MagicMock(spec=EntityUID) + self.mock_attrs = mocker.MagicMock(spec=MetricAttributes) + self.mock_accessor = mocker.MagicMock(spec=MetricAccessor) + self.metric = Metric( + entity_uid=self.mock_entity_uid, + attrs=self.mock_attrs, + accessor=self.mock_accessor, + ) + + def test_init(self): + assert hasattr(self.metric, "entity_uid") + assert self.metric._entity_uid is self.mock_entity_uid + assert hasattr(self.metric, "attributes") + assert self.metric._attrs is self.mock_attrs + assert hasattr(self.metric, "accessor") + assert self.metric._accessor is self.mock_accessor + + @pytest.mark.parametrize( + "key, mock_return_type, expected_type, expected_attrs", + [ + ( + "2024-01-01T00:00:00+00:00", + Number, + Instant, + {"value": datetime(2024, 1, 1, 0, 0, tzinfo=timezone.utc)}, + ), + ( + slice( + "2024-07-04T15:08:45+00:00", + "2024-07-04T15:10:00+00:00", + "15s", + ), + Timeseries, + Period, + { + "start": datetime( + 2024, 7, 4, 15, 8, 45, tzinfo=timezone.utc + ), + "end": datetime(2024, 7, 4, 15, 10, tzinfo=timezone.utc), + "resolution": timedelta(seconds=15), + }, + ), + ( + Instant("2024-07-04T15:08:45+00:00"), + Number, + Instant, + { + "value": datetime( + 2024, 7, 4, 15, 8, 45, tzinfo=timezone.utc + ) + }, + ), + ( + Period( + slice( + "2024-07-04T15:08:45+00:00", + "2024-07-04T15:10:00+00:00", + "15s", + ) + ), + Timeseries, + Period, + { + "start": datetime( + 2024, 7, 4, 15, 8, 45, tzinfo=timezone.utc + ), + "end": datetime( + 2024, 7, 4, 15, 10, 00, tzinfo=timezone.utc + ), + "resolution": timedelta(seconds=15), + }, + ), + ], + ) + def test_getitem( + self, key, mock_return_type, expected_type, expected_attrs, mocker + ): + self.mock_accessor.get_timeseries.return_value = MagicMock( + spec=mock_return_type + ) + + result = self.metric[key] + self.mock_accessor.get_timeseries.assert_called_once_with( + self.mock_entity_uid, self.mock_attrs, mocker.ANY + ) + actual_key = self.mock_accessor.get_timeseries.call_args[0][2] + + assert isinstance(actual_key, expected_type) + for attr, value in expected_attrs.items(): + assert getattr(actual_key, attr) == value + + assert isinstance(result, mock_return_type) + + def test_getitem_with_invalid_key(self): + with pytest.raises(TypeError): + _ = self.metric[123] diff --git a/src/im_mad/remotes/lib/python/pyoneai/tests/unit/test_core/test_predictor_accessor.py b/src/im_mad/remotes/lib/python/pyoneai/tests/unit/test_core/test_predictor_accessor.py new file mode 100644 index 0000000000..30b207be1b --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/tests/unit/test_core/test_predictor_accessor.py @@ -0,0 +1,119 @@ +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pytest +from pytest_mock import MockerFixture + +from pyoneai.core import ( + AccessorType, + EntityUID, + Instant, + MetricAttributes, + Period, + PredictorAccessor, +) + + +class TestPredictorAccessor: + @pytest.fixture(autouse=True) + def setup(self, mocker: MockerFixture): + self.mock_model = mocker.MagicMock() + self.mock_model.model_config = mocker.MagicMock() + self.mock_model.model_config.sequence_length = 4 + self.mock_entity_uid = mocker.MagicMock(spec=EntityUID) + self.mock_metric_attrs = mocker.MagicMock(spec=MetricAttributes) + self.mock_observator_accessor = mocker.MagicMock() + self.instant = Instant( + "2024-07-04T12+00:00", origin="2024-07-04T11:59:45+00:00" + ) + self.period = Period( + slice("2024-07-04T12+00:00", "2024-07-04T14+00:00", "15s"), + origin="2024-07-04T12+00:00", + ) + self.accessor = PredictorAccessor(prediction_model=self.mock_model) + + def test_type(self): + assert self.accessor.type == AccessorType.PREDICTION + + def test_get_timeseries_instant(self, mocker: MockerFixture): + result = self.accessor.get_timeseries( + self.mock_entity_uid, + self.mock_metric_attrs, + self.instant, + observator_accessor=self.mock_observator_accessor, + ) + self.mock_observator_accessor.get_timeseries.assert_called_once_with( + self.mock_entity_uid, + self.mock_metric_attrs, + mocker.ANY, + ) + hist_start_ = ( + self.instant.origin + - self.mock_model.model_config.sequence_length + * self.instant.duration + ) + hist_end = self.instant.origin + duration = ( + self.mock_model.model_config.sequence_length + * self.instant.duration + ) + called_period = self.mock_observator_accessor.get_timeseries.call_args[ + 0 + ][2] + assert called_period.start == hist_start_ + assert called_period.end == hist_end + assert called_period.duration == duration + assert called_period.resolution == self.instant.duration + + self.mock_model.predict.assert_called_once_with( + metric=self.mock_observator_accessor.get_timeseries.return_value, + horizon=1, + ) + assert result is self.mock_model.predict.return_value + + def test_get_timeseries_period(self, mocker: MockerFixture): + result = self.accessor.get_timeseries( + self.mock_entity_uid, + self.mock_metric_attrs, + self.period, + observator_accessor=self.mock_observator_accessor, + ) + self.mock_observator_accessor.get_timeseries.assert_called_once_with( + self.mock_entity_uid, + self.mock_metric_attrs, + mocker.ANY, + ) + called_period = self.mock_observator_accessor.get_timeseries.call_args[ + 0 + ][2] + hist_start = ( + (self.period.start - self.period.resolution) + - self.mock_model.model_config.sequence_length + * self.period.resolution + ) + hist_end = self.period.start - self.period.resolution + duration = ( + self.mock_model.model_config.sequence_length + * self.period.resolution + ) + assert called_period.start == hist_start + assert called_period.end == hist_end + assert called_period.duration == duration + assert called_period.resolution == self.period.resolution + + self.mock_model.predict.assert_called_once_with( + metric=self.mock_observator_accessor.get_timeseries.return_value, + horizon=len(self.period.values), + ) + assert result is self.mock_model.predict.return_value diff --git a/src/im_mad/remotes/lib/python/pyoneai/tests/unit/test_core/test_sqlite_accessor.py b/src/im_mad/remotes/lib/python/pyoneai/tests/unit/test_core/test_sqlite_accessor.py new file mode 100644 index 0000000000..89d7c5905b --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/tests/unit/test_core/test_sqlite_accessor.py @@ -0,0 +1,76 @@ +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from datetime import timedelta + +import pytest +from pytest_mock import MockerFixture + +from pyoneai.core import ( + AccessorType, + EntityType, + EntityUID, + MetricAttributes, + Period, + SQLiteAccessor, +) +from pyoneai.core.tsnumpy import Timeseries + + +class TestSQLiteAccessor: + @pytest.fixture(autouse=True) + def setup(self, mocker: MockerFixture): + self.mock_connection = mocker.MagicMock() + mocker.patch("sqlite3.connect", return_value=self.mock_connection) + self.entity_uid = EntityUID(EntityType.VIRTUAL_MACHINE, 0) + self.metric_attrs = MetricAttributes(name="cpu") + self.monitor_interval = 60 + self.accessor = SQLiteAccessor( + db_path="dummy_db_path", monitor_interval=self.monitor_interval + ) + + def test_init(self): + assert self.accessor._connection is self.mock_connection + assert self.accessor._timestamp_col == "TIMESTAMP" + assert self.accessor._value_col == "VALUE" + assert ( + self.accessor._table_name_template + == "{entityUID}_{metric_name}_monitoring" + ) + + def test_type(self): + assert self.accessor.type == AccessorType.OBSERVATION + + def test_get_timeseries(self, mocker): + expected_ts = mocker.MagicMock() + mocker.patch( + "pyoneai.core.tsnumpy.Timeseries.read_from_database", + return_value=expected_ts, + ) + mock_period = mocker.MagicMock(spec=Period) + expected_table_name = "virtualmachine_0_cpu_monitoring" + result = self.accessor.get_timeseries( + self.entity_uid, self.metric_attrs, mock_period + ) + + assert result == expected_ts + Timeseries.read_from_database.assert_called_once_with( + connection=self.accessor._connection, + table_name=expected_table_name, + metric_name="cpu", + timestamp_col="TIMESTAMP", + value_col="VALUE", + time=mock_period, + tolerance=timedelta(seconds=self.monitor_interval), + ) diff --git a/src/im_mad/remotes/lib/python/pyoneai/tests/unit/test_core/test_time.py b/src/im_mad/remotes/lib/python/pyoneai/tests/unit/test_core/test_time.py new file mode 100644 index 0000000000..daeb13e456 --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/tests/unit/test_core/test_time.py @@ -0,0 +1,190 @@ +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from datetime import datetime, timedelta, timezone + +import numpy as np +import pytest + +from pyoneai.core import Instant, Period + +_INSTANT = { + "datetime_str": ["2024-07-04T10+00:00", "2024-07-04T12:00:00+02:00"], + "datetime": [ + datetime(2024, 7, 4, 10, 0, tzinfo=timezone.utc), + datetime(2024, 7, 4, 12, 0, tzinfo=timezone(timedelta(hours=2))), + ], + "timedelta_str": ["-15m", "15m", "-2h", "1h"], + "timedelta": [ + timedelta(minutes=15), + timedelta(minutes=-15), + timedelta(hours=2), + timedelta(hours=-1), + ], +} + +_PERIOD = { + "string": [ + slice("2024-07-04T10+00:00", "2024-07-04T15+00:00", "1h"), + slice("-150m", "150m", "30m"), + ], + "datetime": [ + np.arange( + start=datetime(2024, 7, 4, 10, 0, tzinfo=timezone.utc), + stop=datetime(2024, 7, 4, 12, 0, tzinfo=timezone.utc), + step=timedelta(minutes=30), + dtype=object, + ) + ], +} + + +class TestInstant: + @pytest.fixture(autouse=True) + def setup(self, mocker): + self.now = datetime(2024, 7, 4, 12, 30, tzinfo=timezone.utc) + + @pytest.mark.parametrize("value", _INSTANT["datetime_str"]) + def test_init_from_datetime_string(self, value): + instant = Instant(value=value, origin=self.now) + assert isinstance(instant.value, datetime) + assert datetime.fromisoformat(value) == instant.value + assert isinstance(instant.origin, datetime) + assert instant.origin == self.now + assert isinstance(instant.duration, timedelta) + assert instant.tz == timezone.utc + + @pytest.mark.parametrize("value", _INSTANT["datetime"]) + def test_init_from_datetime(self, value): + instant = Instant(value=value, origin=self.now) + assert isinstance(instant.value, datetime) + assert value == instant.value + assert isinstance(instant.origin, datetime) + assert instant.origin == self.now + assert isinstance(instant.duration, timedelta) + + @pytest.mark.parametrize("value", _INSTANT["timedelta_str"]) + def test_init_from_timedelta_string(self, value): + instant = Instant(value=value, origin=self.now) + assert isinstance(instant.value, datetime) + assert isinstance(instant.origin, datetime) + assert instant.origin == self.now + assert isinstance(instant.duration, timedelta) + + @pytest.mark.parametrize("value", _INSTANT["timedelta"]) + def test_init_from_timedelta(self, value): + timestamp = self.now + value + instant = Instant(value=value, origin=self.now) + assert isinstance(instant.value, datetime) + assert instant.value == timestamp + assert isinstance(instant.origin, datetime) + assert instant.origin == self.now + assert isinstance(instant.duration, timedelta) + + def test_init_from_none(self): + instant = Instant() + assert isinstance(instant.value, datetime) + assert instant.value == instant.origin + instant = Instant(value=self.now, origin=None) + assert isinstance(instant.origin, datetime) + instant = Instant(origin=self.now) + assert isinstance(instant.value, datetime) + instant = Instant(datetime.now()) + assert isinstance(instant.value, datetime) + + def test_incorrect_init(self): + period = slice(None) + with pytest.raises(TypeError): + Instant(value=period, origin=self.now) + incorrect_str = "fake date" + with pytest.raises(ValueError): + Instant(value=incorrect_str, origin=self.now) + nat_datetime = np.datetime64("NaT") + with pytest.raises(ValueError): + Instant(value=nat_datetime, origin=self.now) + + +class TestPeriod: + @pytest.fixture(autouse=True) + def setup(self, mocker): + self.now = datetime(2024, 7, 4, 12, 30, tzinfo=timezone.utc) + + @pytest.mark.parametrize("value", _PERIOD["string"] + _PERIOD["datetime"]) + def test_init_from_string(self, value): + period = Period(value=value, origin=self.now) + assert isinstance(period.origin, datetime) + assert period.origin == self.now + assert isinstance(period.start, datetime) + assert isinstance(period.end, datetime) + assert isinstance(period.resolution, timedelta) + assert isinstance(period.values, np.ndarray) + assert isinstance(period.duration, timedelta) + duration = period.end - period.start + assert period.duration == duration + assert isinstance(period.span, tuple) + assert all(isinstance(t, timedelta) for t in period.span) + + def test_incorrect_init(self): + value = slice(None) + with pytest.raises(ValueError): + Period(value=value, origin=self.now) + timestamp = self.now + with pytest.raises(TypeError): + Period(value=timestamp, origin=self.now) + td = timedelta(minutes=-150) + with pytest.raises(TypeError): + Period(value=td, origin=self.now) + dt = datetime.fromisoformat("2024-07-04T12:00:00+02:00") + with pytest.raises(TypeError): + Period(value=dt, origin=self.now) + str_instant = "0" + with pytest.raises(TypeError): + Period(value=str_instant, origin=self.now) + + def test_init_from_start_greater_than_stop(self): + value = slice("2024-07-04T15+00:00", "2024-07-04T10+00:00", "30m") + with pytest.raises(ValueError): + time_idx = Period(value) # noqa: F841 + + def test_split(self): + period = Period( + value=slice("2024-07-04T10+00:00", "2024-07-04T15+00:00", "30m"), + origin="2024-07-04T12+00:00", + ) + past, future = period.split( + when=datetime(2024, 7, 4, 13, 0, tzinfo=timezone.utc) + ) + assert past.start == datetime(2024, 7, 4, 10, 0, tzinfo=timezone.utc) + assert past.end == datetime(2024, 7, 4, 13, 0, tzinfo=timezone.utc) + assert past.resolution == timedelta(minutes=30) + assert future.start == datetime( + 2024, 7, 4, 13, 30, 0, tzinfo=timezone.utc + ) + assert future.end == datetime(2024, 7, 4, 15, 0, tzinfo=timezone.utc) + assert future.resolution == timedelta(minutes=30) + + def test_split_default(self): + period = Period( + value=slice("2024-07-04T10+00:00", "2024-07-04T15+00:00", "30m"), + origin="2024-07-04T12+00:00", + ) + past, future = period.split() + assert past.start == datetime(2024, 7, 4, 10, 0, tzinfo=timezone.utc) + assert past.end == datetime(2024, 7, 4, 12, 0, tzinfo=timezone.utc) + assert past.resolution == timedelta(minutes=30) + assert future.start == datetime( + 2024, 7, 4, 12, 30, tzinfo=timezone.utc + ) + assert future.end == datetime(2024, 7, 4, 15, tzinfo=timezone.utc) + assert future.resolution == timedelta(minutes=30) diff --git a/src/im_mad/remotes/lib/python/pyoneai/tests/unit/test_core/test_tsnumpy.py b/src/im_mad/remotes/lib/python/pyoneai/tests/unit/test_core/test_tsnumpy.py new file mode 100644 index 0000000000..a7f514b542 --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/tests/unit/test_core/test_tsnumpy.py @@ -0,0 +1,639 @@ +from datetime import datetime, timedelta, timezone +from typing import Union + +import numpy as np +import pytest + +from pyoneai.core.entity_uid import EntityType, EntityUID +from pyoneai.core.time import Instant, Period +from pyoneai.core.tsnumpy.index import TimeIndex +from pyoneai.core.tsnumpy.timeseries import Timeseries + + +# TODO: Remove once we define the __eq__ method for EntityUID +def assert_entities_equal( + expected: Union[EntityUID, list], actual: np.ndarray +) -> None: + """Assert that the actual entities match the expected ones. + + Parameters + ---------- + expected : Union[EntityUID, list] + Expected entity or list of entities + actual : np.ndarray + Array of actual entities from the timeseries + """ + if isinstance(expected, EntityUID): + expected = [expected] + + assert len(expected) == len( + actual + ), f"Number of entities mismatch: expected {len(expected)}, got {len(actual)}" + + for exp, act in zip(expected, actual): + assert ( + exp.type == act.type + ), f"Entity type mismatch: expected {exp.type}, got {act.type}" + assert ( + exp.id == act.id + ), f"Entity ID mismatch: expected {exp.id}, got {act.id}" + + +def assert_metrics_equal( + expected: Union[str, list], actual: np.ndarray +) -> None: + """Assert that the actual metrics match the expected ones. + + Parameters + ---------- + expected : Union[str, list] + Expected metric name or list of metric names + actual : np.ndarray + Array of actual metric names from the timeseries + """ + if isinstance(expected, str): + expected = [expected] + + assert len(expected) == len( + actual + ), f"Number of metrics mismatch: expected {len(expected)}, got {len(actual)}" + + assert all( + exp == act for exp, act in zip(expected, actual) + ), f"Metric names mismatch: expected {expected}, got {actual.tolist()}" + + +@pytest.fixture(scope="module") +def sample_timeseries(): + """Create a sample timeseries with test data. + + Returns + ------- + Timeseries + Sample timeseries with shape (2 hours, 3 metrics, 2 entities): + + Time t=0: + Metrics VM1 VM2 + cpu 1 2 + memory 3 4 + network 5 6 + + Time t=1: + Metrics VM1 VM2 + cpu 7 8 + memory 9 10 + network 11 12 + """ + # Create time period (2 hours with hourly intervals) + period = Period( + slice("2024-01-01T00:00:00+00:00", "2024-01-01T01:00:00+00:00", "1h") + ) + + entities = np.array( + [ + EntityUID(EntityType.VIRTUAL_MACHINE, 1), + EntityUID(EntityType.VIRTUAL_MACHINE, 2), + ] + ) + + metrics = np.array(["cpu", "memory", "network"]) + + data = np.array( + [ + # t=0 + [ + [1, 2], # cpu + [3, 4], # memory + [5, 6], # network + ], + # t=1 + [ + [7, 8], # cpu + [9, 10], # memory + [11, 12], # network + ], + ] + ) + + return Timeseries( + time_idx=period, + metric_idx=metrics, + entity_uid_idx=entities, + data=data, + ) + + +@pytest.fixture(scope="module") +def large_timeseries(): + """Create a larger timeseries for comprehensive slicing tests. + + Returns + ------- + Timeseries + Sample timeseries with shape (24 hours, 8 metrics, 5 entities): + - Time: 24 hours of hourly data + - Metrics: cpu, memory, disk_read, disk_write, net_rx, net_tx, iops, load + - Entities: 5 virtual machines + """ + reference_datetime = datetime(2024, 1, 1, hour=0, tzinfo=timezone.utc) + dates = [ + reference_datetime + timedelta(hours=i) for i in range(24) + ] # 24 hours of data + time_index = Period(np.array(dates)) + + metric_index = np.array( + [ + "cpu", + "memory", + "disk_read", + "disk_write", + "net_rx", + "net_tx", + "iops", + "load", + ] + ) + + entity_index = np.array( + [ + EntityUID(EntityType.VIRTUAL_MACHINE, i) + for i in range(1, 6) # 5 VMs + ] + ) + + # Random data: 24 hours x 8 metrics x 5 VMs + # Using random seed for reproducibility + np.random.seed(42) + data = np.random.rand(24, 8, 5) + return Timeseries(time_index, metric_index, entity_index, data) + + +class TestTimeseries: + """Comprehensive test suite for Timeseries class.""" + + @pytest.fixture(autouse=True) + def setup(self): + """Setup common test variables.""" + self.reference_datetime = datetime( + 2024, 1, 1, hour=0, tzinfo=timezone.utc + ) + self.test_period = Period( + slice( + self.reference_datetime, + self.reference_datetime + timedelta(hours=1), + "1h", + ) + ) + self.test_instant = Instant(self.reference_datetime) + self.test_entity = EntityUID(EntityType.VIRTUAL_MACHINE, 1) + self.test_entities = [ + EntityUID(EntityType.VIRTUAL_MACHINE, 1), + EntityUID(EntityType.VIRTUAL_MACHINE, 2), + ] + + # Basic Operations Tests + def test_properties(self, sample_timeseries): + """Test basic properties of timeseries.""" + assert sample_timeseries.shape == (2, 3, 2) + assert_metrics_equal( + ["cpu", "memory", "network"], sample_timeseries.names + ) + assert_entities_equal( + [ + EntityUID(EntityType.VIRTUAL_MACHINE, 1), + EntityUID(EntityType.VIRTUAL_MACHINE, 2), + ], + sample_timeseries.entity_uids, + ) + + def test_single_metric_selection(self, sample_timeseries): + """Test selecting a single metric from timeseries.""" + cpu_ts = sample_timeseries["cpu"] + assert cpu_ts.shape == (2, 1, 2) + assert_metrics_equal("cpu", cpu_ts._metric_idx.values) + expected = np.array([[[1, 2]], [[7, 8]]]) + np.testing.assert_array_equal(cpu_ts.values, expected) + + def test_multiple_metrics_selection(self, sample_timeseries): + """Test selecting multiple metrics from timeseries.""" + resources_ts = sample_timeseries[["cpu", "memory"]] + assert resources_ts.shape == (2, 2, 2) + assert_metrics_equal( + ["cpu", "memory"], resources_ts._metric_idx.values + ) + expected = np.array([[[1, 2], [3, 4]], [[7, 8], [9, 10]]]) + np.testing.assert_array_equal(resources_ts.values, expected) + + # Single Dimension Slicing Tests + def test_time_selection(self, large_timeseries): + """Test time-based selection.""" + result = large_timeseries[self.test_period] + assert result.shape[0] == 2 # Two time points + assert result.shape[1:] == (8, 5) # Same metrics and entities + + def test_metric_selection(self, large_timeseries): + """Test metric-based selection.""" + result = large_timeseries["cpu"] + assert result.shape == (24, 1, 5) # 24 hours, 1 metric, 5 VMs + assert_metrics_equal("cpu", result._metric_idx.values) + + def test_entity_selection(self, large_timeseries): + """Test entity-based selection.""" + result = large_timeseries[self.test_entity] + assert result.shape == (24, 8, 1) # 24 hours, 8 metrics, 1 VM + assert_entities_equal(self.test_entity, result._entity_idx.values) + + # Two Dimension Slicing Tests + def test_time_metric_selection(self, large_timeseries): + """Test combined time and metric selection.""" + result = large_timeseries[self.test_period, ["cpu", "memory"]] + assert result.shape == (2, 2, 5) # 2 hours, 2 metrics, 5 VMs + assert_metrics_equal(["cpu", "memory"], result._metric_idx.values) + + def test_time_entity_selection(self, large_timeseries): + """Test combined time and entity selection.""" + result = large_timeseries[self.test_period, self.test_entity] + assert result.shape == (2, 8, 1) # 2 hours, 8 metrics, 1 VM + assert_entities_equal(self.test_entity, result._entity_idx.values) + + def test_metric_entity_selection(self, large_timeseries): + """Test combined metric and entity selection.""" + result = large_timeseries[["cpu", "memory"], self.test_entity] + assert result.shape == (24, 2, 1) # 24 hours, 2 metrics, 1 VM + assert_metrics_equal(["cpu", "memory"], result._metric_idx.values) + assert_entities_equal(self.test_entity, result._entity_idx.values) + + # Three Dimension Slicing Tests + def test_time_metric_entity_selection(self, large_timeseries): + """Test selection on all three dimensions.""" + result = large_timeseries[ + self.test_period, ["cpu", "memory"], self.test_entity + ] + assert result.shape == (2, 2, 1) # 2 hours, 2 metrics, 1 VM + assert_metrics_equal(["cpu", "memory"], result._metric_idx.values) + assert_entities_equal(self.test_entity, result._entity_idx.values) + + # Mixed Selection Tests + def test_instant_multiple_metrics(self, large_timeseries): + """Test single time point with multiple metrics.""" + result = large_timeseries[self.test_instant, ["cpu", "memory"]] + assert result.shape == (1, 2, 5) # 1 hour, 2 metrics, 5 VMs + assert_metrics_equal(["cpu", "memory"], result._metric_idx.values) + + def test_period_single_metric(self, large_timeseries): + """Test time period with single metric.""" + result = large_timeseries[self.test_period, "cpu"] + assert result.shape == (2, 1, 5) # 2 hours, 1 metric, 5 VMs + assert_metrics_equal("cpu", result._metric_idx.values) + + def test_multiple_entities(self, large_timeseries): + """Test selection of multiple entities.""" + result = large_timeseries[self.test_entities] + assert result.shape == (24, 8, 2) # 24 hours, 8 metrics, 2 VMs + assert_entities_equal(self.test_entities, result._entity_idx.values) + + def test_different_dimension_order(self, large_timeseries): + """Test different ordering of dimension selections.""" + result = large_timeseries[ + self.test_entity, ["cpu", "memory"], self.test_period + ] + assert result.shape == (2, 2, 1) # 2 hours, 2 metrics, 1 VM + assert_metrics_equal(["cpu", "memory"], result._metric_idx.values) + assert_entities_equal(self.test_entity, result._entity_idx.values) + + # Validation Tests + def test_invalid_metric_selection(self, sample_timeseries): + """Test selecting a non-existent metric raises KeyError.""" + with pytest.raises(KeyError, match="Metric 'nonexistent' not found"): + _ = sample_timeseries["nonexistent"] + + def test_invalid_entity_selection(self, sample_timeseries): + """Test selecting a non-existent entity raises KeyError.""" + invalid_entity = EntityUID(EntityType.VIRTUAL_MACHINE, 999) + with pytest.raises( + KeyError, match="Entity virtualmachine_999 not found" + ): + _ = sample_timeseries[invalid_entity] + + def test_non_monotonic_time_index(self): + """Test that non-monotonic time values in Period are caught.""" + time_values = np.array( + [ + "2024-01-01T02:00:00", + "2024-01-01T00:00:00", + "2024-01-01T01:00:00", + ], + dtype="datetime64[ns]", + ) + + period = Period(time_values) + entities = np.array([self.test_entity]) + metrics = np.array(["cpu"]) + data = np.zeros((3, 1, 1)) + + with pytest.raises( + ValueError, + match="Time index must be strictly monotonic increasing", + ): + Timeseries(period, metrics, entities, data) + + def test_invalid_entity_type(self): + """Test that non-EntityUID objects in entity index are caught.""" + period = Period( + slice( + "2024-01-01T00:00:00+00:00", "2024-01-01T01:00:00+00:00", "1h" + ) + ) + + entities = np.array( + [ + EntityUID(EntityType.VIRTUAL_MACHINE, 1), + "invalid_entity", # Wrong type + ] + ) + metrics = np.array(["cpu"]) + data = np.zeros((2, 1, 2)) + + with pytest.raises( + ValueError, match="Invalid entity types at indices" + ): + Timeseries(period, metrics, entities, data) + + def test_data_shape_mismatch(self): + """Test that data shape mismatches are caught.""" + period = Period( + slice( + "2024-01-01T00:00:00+00:00", "2024-01-01T01:00:00+00:00", "1h" + ) + ) + + entities = np.array([EntityUID(EntityType.VIRTUAL_MACHINE, 1)]) + metrics = np.array(["cpu"]) + data = np.zeros((3, 1, 1)) + + with pytest.raises( + ValueError, match="Dimension mismatch: got .* expected" + ): + Timeseries(period, metrics, entities, data) + + # Edge Cases Tests + def test_single_element_lists(self, large_timeseries): + """Test selections with single-element lists.""" + result = large_timeseries[ + self.test_period, ["cpu"], [self.test_entity] + ] + assert result.shape == (2, 1, 1) # 2 hours, 1 metric, 1 VM + assert_metrics_equal("cpu", result._metric_idx.values) + assert_entities_equal(self.test_entity, result._entity_idx.values) + + def test_mixed_single_multiple_different_order(self, large_timeseries): + """Test mixed single/multiple selections with different dimension order.""" + result = large_timeseries[self.test_entities, "cpu", self.test_instant] + assert result.shape == (1, 1, 2) # 1 hour, 1 metric, 2 VMs + assert_metrics_equal("cpu", result._metric_idx.values) + assert_entities_equal(self.test_entities, result._entity_idx.values) + + def test_multiple_selections_all_dimensions(self, large_timeseries): + """Test multiple selections in all dimensions simultaneously.""" + result = large_timeseries[ + self.test_period, + ["cpu", "memory"], + self.test_entities, + ] + assert result.shape == (2, 2, 2) # 2 hours, 2 metrics, 2 VMs + assert_metrics_equal(["cpu", "memory"], result._metric_idx.values) + assert_entities_equal(self.test_entities, result._entity_idx.values) + + def test_invalid_dimension_order(self, large_timeseries): + """Test that invalid dimension combinations raise appropriate errors.""" + with pytest.raises(TypeError, match="Unsupported key type"): + _ = large_timeseries[ + "cpu", 123, self.test_entity + ] # Invalid time type + + with pytest.raises(TypeError, match="Unsupported key type"): + _ = large_timeseries[ + {"invalid": "type"} + ] # Completely invalid type + + def test_out_of_bounds_time_selection(self, large_timeseries): + """Test that out-of-bounds time selections raise appropriate errors.""" + # Future time selection + future_instant = Instant(self.reference_datetime + timedelta(days=1)) + with pytest.raises(ValueError, match="Time selection out of bounds"): + _ = large_timeseries[future_instant] + + # Future period + future_period = Period( + slice( + self.reference_datetime + timedelta(days=1), + self.reference_datetime + timedelta(days=2), + "1h", + ) + ) + with pytest.raises(ValueError, match="Time selection out of bounds"): + _ = large_timeseries[future_period] + + # Past period + past_period = Period( + slice( + self.reference_datetime - timedelta(days=1), + self.reference_datetime - timedelta(hours=1), + "1h", + ) + ) + with pytest.raises(ValueError, match="Time selection out of bounds"): + _ = large_timeseries[past_period] + + # Period partially out of bounds (future) + partially_future_period = Period( + slice( + self.reference_datetime, + self.reference_datetime + timedelta(days=2), + "1h", + ) + ) + with pytest.raises(ValueError, match="Time selection out of bounds"): + _ = large_timeseries[partially_future_period] + + # Period partially out of bounds (past) + partially_past_period = Period( + slice( + self.reference_datetime - timedelta(days=1), + self.reference_datetime + timedelta(hours=1), + "1h", + ) + ) + with pytest.raises(ValueError, match="Time selection out of bounds"): + _ = large_timeseries[partially_past_period] + + # Duplicate Handling Tests + def test_duplicate_time_values(self): + """Test that duplicate timestamps are caught during initialization.""" + time_values = np.array( + [ + datetime(2024, 1, 1, hour=0, tzinfo=timezone.utc), + datetime(2024, 1, 1, hour=0, tzinfo=timezone.utc), # Duplicate + datetime(2024, 1, 1, hour=1, tzinfo=timezone.utc), + ] + ) + period = Period(time_values) + metrics = np.array(["cpu"]) + data = np.zeros((3, 1, 1)) + entities = np.array([self.test_entity]) + + with pytest.raises( + ValueError, match="Time index contains duplicate timestamps" + ): + Timeseries(period, metrics, entities, data) + + def test_duplicate_entities(self): + """Test that duplicate entities are caught during initialization.""" + entities = np.array( + [ + EntityUID(EntityType.VIRTUAL_MACHINE, 1), + EntityUID(EntityType.VIRTUAL_MACHINE, 1), # Same type and ID + ] + ) + metrics = np.array(["cpu"]) + data = np.zeros((2, 1, 2)) + + with pytest.raises(ValueError, match="Duplicate entities not allowed"): + Timeseries(self.test_period, metrics, entities, data) + + def test_entities_with_same_id_different_types(self): + """Test that entities with same ID but different types are allowed.""" + entities = np.array( + [ + EntityUID(EntityType.VIRTUAL_MACHINE, 1), + EntityUID(EntityType.HOST, 1), # Same ID but different type + ] + ) + metrics = np.array(["cpu"]) + data = np.zeros((2, 1, 2)) + + ts = Timeseries(self.test_period, metrics, entities, data) + assert ts.shape == (2, 1, 2) + + # Metric Handling Tests + def test_metric_case_sensitivity(self): + """Test case-sensitive behavior of metric names.""" + # Test initialization with case-sensitive metrics + metrics = np.array(["CPU", "cpu", "Memory"]) + data = np.zeros((2, 3, 1)) + entities = np.array([self.test_entity]) + + ts = Timeseries(self.test_period, metrics, entities, data) + assert ts.shape == (2, 3, 1) + + # Test individual metric selection + cpu_lower = ts["cpu"] + assert_metrics_equal("cpu", cpu_lower._metric_idx.values) + + cpu_upper = ts["CPU"] + assert_metrics_equal("CPU", cpu_upper._metric_idx.values) + + # Test multiple metric selection + multi_ts = ts[["CPU", "Memory"]] + assert_metrics_equal(["CPU", "Memory"], multi_ts._metric_idx.values) + + def test_metric_validation(self): + """Test comprehensive metric validation including duplicates, empty lists, and invalid names.""" + metrics = np.array(["cpu", "memory"]) + data = np.zeros((2, 2, 1)) + entities = np.array([self.test_entity]) + + ts = Timeseries(self.test_period, metrics, entities, data) + + # Test duplicate metrics in initialization + with pytest.raises( + ValueError, match="Duplicate metric names not allowed" + ): + Timeseries( + self.test_period, + np.array(["cpu", "memory", "cpu"]), + entities, + np.zeros((2, 3, 1)), + ) + + # Test duplicate metrics in selection + with pytest.raises( + ValueError, match="Duplicate metric names not allowed" + ): + _ = ts[["cpu", "memory", "cpu"]] + + # Test empty selection list + with pytest.raises(ValueError, match="Empty selection list"): + _ = ts[[]] + + # Test non-existent metrics + with pytest.raises( + KeyError, match="Available metrics.*: 'cpu', 'memory'" + ): + _ = ts["CPU"] # Wrong case + + with pytest.raises( + KeyError, match="Available metrics.*: 'cpu', 'memory'" + ): + _ = ts["network"] # Non-existent metric + + # Test invalid metric names + with pytest.raises( + KeyError, match="Available metrics.*: 'cpu', 'memory'" + ): + _ = ts["cpu%"] # Special characters + + with pytest.raises( + KeyError, match="Available metrics.*: 'cpu', 'memory'" + ): + _ = ts["cpu usage"] # Whitespace + + # Test mixed valid/invalid selections + with pytest.raises( + KeyError, match="Available metrics.*: 'cpu', 'memory'" + ): + _ = ts[["cpu", "disk"]] # One valid, one invalid + + +class TestTimeIndex: + + def test_monotonic_increasing(self): + index = TimeIndex( + np.array( + [ + "2024-01-01T00:00:00", + "2024-01-01T01:00:00", + "2024-01-01T02:00:00", + ], + dtype="datetime64[ns]", + ) + ) + assert index.is_monotonic_increasing + + def test_is_monotonic_increasing_when_single_element(self): + index = TimeIndex( + np.array(["2024-01-01T00:00:00"], dtype="datetime64[ns]") + ) + assert index.is_monotonic_increasing + + def test_is_monotonic_decreasing_when_single_element(self): + index = TimeIndex( + np.array(["2024-01-01T00:00:00"], dtype="datetime64[ns]") + ) + assert index.is_monotonic_decreasing + + def test_non_monotonic_increasing(self): + with pytest.raises( + ValueError, + match=r"Time index must be strictly monotonic increasing", + ): + _ = TimeIndex( + np.array( + [ + "2024-01-01T00:00:00", + "2024-01-01T02:00:00", + "2024-01-01T01:00:00", + ], + dtype="datetime64[ns]", + ) + ) diff --git a/src/im_mad/remotes/lib/python/pyoneai/tests/unit/test_ml/test_arima_predictor.py b/src/im_mad/remotes/lib/python/pyoneai/tests/unit/test_ml/test_arima_predictor.py new file mode 100644 index 0000000000..79c37bd35e --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/tests/unit/test_ml/test_arima_predictor.py @@ -0,0 +1,99 @@ +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from datetime import datetime, timedelta, timezone + +import numpy as np +import pytest + +from pyoneai.core import Instant, Period + +from pyoneai.tests.unit.test_ml.test_predictors_interface import ( + TestPredictionModelInterface, +) + +try: + import pandas + + __HAS_PANDAS__ = True +except: + __HAS_PANDAS__ = False + + +@pytest.mark.skipif(not __HAS_PANDAS__, reason="pandas not installed") +class TestArimaPredictionModel(TestPredictionModelInterface): + __test__ = True + + @pytest.fixture + def model_config(self): + from pyoneai.ml import ModelConfig + + yield ModelConfig( + model_class="statsmodels.tsa.arima.model.ARIMA", + hyper_params={ + "order": (0, 0, 0), + "seasonal_order": (0, 0, 0, 0), + "enforce_stationarity": True, + "enforce_invertibility": True, + "concentrate_scale": False, + "trend_offset": 1, + }, + training_params={}, + sequence_length=10, + ) + + @pytest.fixture + def prediction_model(self, model_config): + from pyoneai.ml import ArimaPredictionModel + + yield ArimaPredictionModel(model_config) + + @pytest.fixture(autouse=True) + def setup(self): + pass + + @pytest.mark.parametrize( + "create_timeseries", + ["create_univariate_timeseries", "create_multivariate_timeseries"], + ) + def test_warn_if_single_element_time_series( + self, prediction_model, create_timeseries + ): + ts = getattr(self, create_timeseries)(1) + with pytest.warns( + Warning, match=r"Only one historical step is used. Returning the.*" + ): + prediction_model.predict(ts) + + @pytest.mark.parametrize( + "create_timeseries", + ["create_univariate_timeseries", "create_multivariate_timeseries"], + ) + def test_return_lastest_value_for_single_element_time_series( + self, prediction_model, create_timeseries + ): + ts = getattr(self, create_timeseries)(1) + forecast = prediction_model.predict(ts, horizon=1) + assert np.all(forecast._df.to_numpy() == ts._df.to_numpy()) + + @pytest.mark.parametrize( + "create_timeseries", + ["create_univariate_timeseries", "create_multivariate_timeseries"], + ) + def test_return_lastest_value_for_single_element_time_series_multstep( + self, prediction_model, create_timeseries + ): + ts = getattr(self, create_timeseries)(1) + forecast = prediction_model.predict(ts, horizon=100) + assert np.all(forecast._df.to_numpy() == ts._df.to_numpy()) diff --git a/src/im_mad/remotes/lib/python/pyoneai/tests/unit/test_ml/test_fourier_predictor.py b/src/im_mad/remotes/lib/python/pyoneai/tests/unit/test_ml/test_fourier_predictor.py new file mode 100644 index 0000000000..869d1a00a1 --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/tests/unit/test_ml/test_fourier_predictor.py @@ -0,0 +1,91 @@ +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pytest +import numpy as np + +from pyoneai.core.entity_uid import EntityType, EntityUID +from pyoneai.core.tsnumpy import Timeseries +from pyoneai.ml import FourierPredictionModel, ModelConfig +from pyoneai.tests.unit.test_ml.test_predictors_interface import ( + TestPredictionModelInterface, +) + + +class TestFourierPredictionModel(TestPredictionModelInterface): + """Test class for FourierPredictionModel.""" + + __test__ = True + + @pytest.fixture + def model_config(self) -> ModelConfig: + """ + Returns a model configuration for FourierPredictionModel. + """ + return ModelConfig( + model_class="pyoneai.ml.FourierPredictionModel", + compute_ci=False, + hyper_params={"nbr_freqs_to_keep": 40}, + training_params={}, + sequence_length=2, + ) + + @pytest.fixture + def prediction_model( + self, model_config: ModelConfig + ) -> FourierPredictionModel: + """Instantiates and returns a model using the configuration.""" + return FourierPredictionModel(model_config) + + @pytest.mark.parametrize( + "create_timeseries", + ["create_univariate_timeseries", "create_multivariate_timeseries"], + ) + def test_keep_all_freqs_for_too_short_timeseries( + self, create_timeseries, prediction_model + ): + ts = getattr(self, create_timeseries)(10) + # For multivariate timeseries, we need to select a single metric + if ts.ndim > 1: + ts = ts[ts.names[0]] + assert prediction_model._get_freqs_to_keep(ts) == len(ts) + + @pytest.mark.parametrize( + "create_timeseries", + ["create_univariate_timeseries", "create_multivariate_timeseries"], + ) + def test_keep_some_freqs_for_long_timeseries( + self, create_timeseries, prediction_model + ): + ts = getattr(self, create_timeseries)(100) + # For multivariate timeseries, we need to select a single metric + if ts.ndim > 1: + ts = ts[ts.names[0]] + assert prediction_model._get_freqs_to_keep(ts) == 40 + + def test_detrend_produces_timeseries(self, prediction_model): + ts = self.create_univariate_timeseries(10) + detrend_ts = prediction_model._detrend(ts, lambda x: x) + assert isinstance(detrend_ts, Timeseries) + + def test_detrend_produces_ts_of_the_same_length(self, prediction_model): + ts = self.create_univariate_timeseries(10) + detrend_ts = prediction_model._detrend(ts, lambda x: x) + assert len(detrend_ts) == len(ts) + + def test_warn_on_unsupported_compute_ci_option(self, model_config): + model_config.compute_ci = True + return super()._test_warn_on_unsupported_compute_ci_option( + FourierPredictionModel, model_config + ) diff --git a/src/im_mad/remotes/lib/python/pyoneai/tests/unit/test_ml/test_hgbt_prediction.py b/src/im_mad/remotes/lib/python/pyoneai/tests/unit/test_ml/test_hgbt_prediction.py new file mode 100644 index 0000000000..38a076b831 --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/tests/unit/test_ml/test_hgbt_prediction.py @@ -0,0 +1,342 @@ +# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import importlib +import tempfile +from datetime import datetime, timedelta, timezone +from pathlib import Path +from typing import TYPE_CHECKING + +import numpy as np +import pytest + +from pyoneai.core import Instant, Period, Timeseries + +try: + import sklearn +except ImportError: + pass +else: + from pyoneai.ml.hgbt_prediction_model import HgbtPredictionModel + +from pyoneai.ml import ModelConfig +from pyoneai.tests.unit.test_ml.test_predictors_interface import ( + TestPredictionModelInterface, +) + +__HAS_PANDAS__ = False +__HAS_POLARS__ = False + +if importlib.util.find_spec("pandas"): + import pandas as pd + + __HAS_PANDAS__ = True +elif importlib.util.find_spec("polars"): + import polars as pl + + __HAS_POLARS__ = True + +@pytest.mark.skipif(not __HAS_PANDAS__, reason="pandas not installed") +class TestHgbtPredictionModel(TestPredictionModelInterface): + __test__ = True + + @pytest.fixture + def model_config(self) -> ModelConfig: + """Return a model configuration for HgbtPredictionModel.""" + return ModelConfig( + model_class="sklearn.ensemble.HistGradientBoostingRegressor", + hyper_params={}, + training_params={ + "max_iter": 50, + "context_length": self.context_length, + "compute_ci": True, + }, + sequence_length=2, + ) + + @pytest.fixture + def prediction_model( + self, model_config: ModelConfig + ) -> 'HgbtPredictionModel': + """Instantiate and returns a HgbtPredictionModel.""" + return HgbtPredictionModel(model_config) + + @pytest.fixture(autouse=True) + def setup(self): + self.context_length = 4 + self.ts_length = 300 + HgbtPredictionModel.MIN_N_SPLITS = 6 + + @pytest.fixture + def tmp_modelconfig_path(self): + path = Path(tempfile.gettempdir()) / "model_config.yaml" + yield path + path.unlink() + + @pytest.fixture + def tmp_checkpoint_path(self): + path = Path(tempfile.gettempdir()) / "checkpoint.checkpoint" + yield path + path.unlink() + + def test_fail_on_timeseries_too_short(self, prediction_model): + start = datetime(2023, 1, 1, tzinfo=timezone.utc) + freq = timedelta(hours=1) + ts = Timeseries( + time_index=np.array( + [start, start + freq, start + 2 * freq], dtype=np.datetime64 + ), + data={"cpu_usage": np.sin(np.linspace(0, 2 * np.pi, 3)) + 1}, + ) + with pytest.raises( + ValueError, + match=f"The passed context length {self.context_length}*", + ): + prediction_model._validate_fit_metric(ts) + + @pytest.mark.parametrize( + "create_timeseries", + ["create_univariate_timeseries", "create_multivariate_timeseries"], + ) + def test_get_forecast_index_starting_at_next_value( + self, create_timeseries, prediction_model + ): + ts = getattr(self, create_timeseries)(10) + index = ts.time_index.values[-1] + + freq = ts.frequency + next_value = index + freq + forecast_index = prediction_model._get_forecast_index(ts, 100) + assert forecast_index[0] == next_value + + @pytest.mark.parametrize( + "create_timeseries", + ["create_univariate_timeseries", "create_multivariate_timeseries"], + ) + def test_get_forecast_index_of_proper_length( + self, create_timeseries, prediction_model + ): + ts = getattr(self, create_timeseries)(10) + forecast_index = prediction_model._get_forecast_index(ts, 100) + assert len(forecast_index) == 100 + + def test_singlestep_forecast_univariate_not_fitted_before( + self, prediction_model + ): + ts = self.create_univariate_timeseries(self.ts_length) + forecast = prediction_model.predict(ts, 1) + assert len(forecast) == 1 + assert len(forecast.names) == 1 + assert forecast.names == ts.names + + def test_singlestep_forecast_multivariate_not_fitted_before( + self, prediction_model + ): + ts = self.create_multivariate_timeseries(self.ts_length) + forecast = prediction_model.predict(ts, 1) + assert len(forecast) == 1 + assert len(forecast.names) == 2 + assert forecast.names == ts.names + + def test_multistep_forecast_univariate_not_fitted_before( + self, prediction_model + ): + ts = self.create_univariate_timeseries(self.ts_length) + forecast = prediction_model.predict(ts, 100) + assert len(forecast) == 100 + assert len(forecast.names) == 1 + + def test_multistep_forecast_multivariate_not_fitted_before( + self, prediction_model + ): + ts = self.create_multivariate_timeseries(self.ts_length) + forecast = prediction_model.predict(ts, 100) + assert len(forecast) == 100 + assert len(forecast.names) == 2 + + def test_fail_on_timeseries_shorted_than_context_length( + self, prediction_model + ): + ts = self.create_univariate_timeseries(self.ts_length) + ts2 = self.create_univariate_timeseries(3) + prediction_model.fit(ts) + with pytest.raises( + ValueError, + match=r"The passed historical context \(time series\) on" + r" length*", + ): + prediction_model.predict(ts2) + + def test_fail_on_fitting_multivariate(self, prediction_model): + with pytest.raises( + ValueError, + match=r"Histogram-based Gradient Boosting Tree can be " + r"trained for univariate time series only.", + ): + prediction_model.fit( + self.create_multivariate_timeseries(self.ts_length) + ) + + def test_singlestep_univariate_forecast_fitted_before( + self, prediction_model + ): + ts = self.create_univariate_timeseries(self.ts_length) + ts_predict = self.create_univariate_timeseries(self.context_length) + forecast = prediction_model.fit(ts).predict(ts_predict, 1) + assert forecast.ndim == ts_predict.ndim + assert len(forecast) == 1 + + def test_singlestep_multivariate_forecast_fitted_before( + self, prediction_model + ): + ts = self.create_univariate_timeseries(self.ts_length) + ts_pred = self.create_multivariate_timeseries(self.context_length) + forecast = prediction_model.fit(ts).predict(ts_pred, 1) + assert forecast.ndim == ts_pred.ndim + assert len(forecast) == 1 + + def test_multistep_univariate_forecast_fitted_before( + self, prediction_model + ): + ts = self.create_univariate_timeseries(self.ts_length) + ts_pred = self.create_univariate_timeseries(self.context_length) + forecast = prediction_model.fit(ts).predict(ts_pred, 100) + assert forecast.ndim == ts_pred.ndim + assert len(forecast) == 100 + + def test_multistep_multivariate_forecast_fitted_before( + self, prediction_model + ): + ts = self.create_univariate_timeseries(self.ts_length) + ts_pred = self.create_multivariate_timeseries(self.context_length) + forecast = prediction_model.fit(ts).predict(ts_pred, 100) + assert forecast.ndim == ts_pred.ndim + assert len(forecast) == 100 + + def test_not_fit_on_predict_if_fitted_before( + self, prediction_model, mocker + ): + fit_mock = mocker.patch( + "pyoneai.ml.HgbtPredictionModel._fit", + autospec=True, + side_effect=HgbtPredictionModel._fit, + ) + ts = self.create_univariate_timeseries(self.ts_length) + ts_pred = self.create_multivariate_timeseries(self.context_length) + prediction_model.fit(ts) + prediction_model.predict(ts_pred) + fit_mock.assert_called_once() + assert np.all(fit_mock.call_args_list[0].args[1] == ts) + + def test_fit_on_predict_if_not_fitted_before( + self, prediction_model, mocker + ): + fit_mock = mocker.patch( + "pyoneai.ml.HgbtPredictionModel._fit", + autospec=True, + side_effect=HgbtPredictionModel._fit, + ) + ts = self.create_multivariate_timeseries(self.ts_length) + prediction_model.predict(ts) + assert fit_mock.call_count == ts.ndim + for i, metric_name in enumerate(ts.names): + assert np.all( + fit_mock.call_args_list[i].args[1] == ts[metric_name] + ) + + def test_save_momdel( + self, prediction_model, tmp_modelconfig_path, tmp_checkpoint_path + ): + ts = self.create_univariate_timeseries(self.ts_length) + prediction_model.fit(ts) + prediction_model.save(tmp_modelconfig_path, tmp_checkpoint_path) + assert tmp_modelconfig_path.exists() + assert tmp_checkpoint_path.exists() + + def test_load_checkpoint( + self, + prediction_model, + model_config, + tmp_modelconfig_path, + tmp_checkpoint_path, + ): + ts = self.create_univariate_timeseries(self.ts_length) + prediction_model.fit(ts) + prediction_model.save(tmp_modelconfig_path, tmp_checkpoint_path) + regressor = type(prediction_model).load( + model_config, tmp_checkpoint_path + ) + assert ( + prediction_model.gbrt_mean.get_params() + == regressor.gbrt_mean.get_params() + ) + assert ( + prediction_model.gbrt_q5.get_params() + == regressor.gbrt_q5.get_params() + ) + assert ( + prediction_model.gbrt_q95.get_params() + == regressor.gbrt_q95.get_params() + ) + + def test_fail_on_fit_timeseries_with_nans(self, prediction_model): + start = datetime(2023, 1, 1, tzinfo=timezone.utc) + freq = timedelta(hours=1) + ts = Timeseries( + time_index=Period(slice(start, start + 999 * freq, freq)).values, + data={ + "cpu_usage": np.array( + [np.nan, 1, 2, 3, 4, 5, np.nan, 7, 8, 9] * 100 + ) + }, + ) + with pytest.raises( + ValueError, match=r"Time series cannot contain NaN values." + ): + prediction_model.fit(ts) + + def test_on_predict_ts_with_nans(self, prediction_model): + ts = self.create_univariate_timeseries(self.ts_length) + start = datetime(2023, 1, 1, tzinfo=timezone.utc) + freq = timedelta(hours=1) + ts = self.create_univariate_timeseries(self.ts_length) + ts_pred = Timeseries( + time_index=Period(slice(start, start + freq * 999, freq)).values, + data={ + "cpu_usage": np.array( + [np.nan, 1, 2, 3, 4, 5, np.nan, 7, 8, 9] * 100 + ) + }, + ) + forecast = prediction_model.fit(ts).predict(ts_pred, 100) + assert np.sum(np.isnan(forecast)) == 0 + + def test_does_not_create_extra_hgbt_if_no_ci(self, model_config): + model_config.compute_ci = False + regressor = HgbtPredictionModel(model_config) + assert regressor.gbrt_q5 is None + assert regressor.gbrt_q95 is None + + def test_does_not_predict_ci_if_no_ci(self, model_config): + ts = self.create_univariate_timeseries(self.ts_length) + ts_pred = self.create_univariate_timeseries(self.context_length) + model_config.compute_ci = False + regressor = HgbtPredictionModel(model_config) + forecast = regressor.fit(ts).predict(ts_pred, 100) + assert np.all(forecast.names == ts.names) + + def test_fit_model_returns_self(self, prediction_model): + super().test_fit_model_returns_self( + prediction_model, "create_univariate_timeseries" + ) diff --git a/src/im_mad/remotes/lib/python/pyoneai/tests/unit/test_ml/test_persistence_predictor.py b/src/im_mad/remotes/lib/python/pyoneai/tests/unit/test_ml/test_persistence_predictor.py new file mode 100644 index 0000000000..ac05483696 --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/tests/unit/test_ml/test_persistence_predictor.py @@ -0,0 +1,44 @@ +import pytest + +from pyoneai.ml import ModelConfig, PersistencePredictionModel +from pyoneai.tests.unit.test_ml.test_predictors_interface import ( + TestPredictionModelInterface, +) + + +class TestPersistencePredictionModel(TestPredictionModelInterface): + """ + Test class for PersistencePredictionModel. + + Provides pytest fixtures to configure and instantiate a persistence prediction model. + """ + + __test__ = True + + @pytest.fixture + def model_config(self) -> ModelConfig: + """ + Returns a model configuration for PersistencePredictionModel. + """ + return ModelConfig( + model_class="pyoneai.ml.PersistencePredictionModel", + compute_ci=False, + hyper_params={}, + training_params={}, + sequence_length=2, + ) + + @pytest.fixture + def prediction_model( + self, model_config: ModelConfig + ) -> PersistencePredictionModel: + """ + Instantiates and returns a PersistencePredictionModel using the provided model configuration. + """ + return PersistencePredictionModel(model_config) + + def test_warn_on_unsupported_compute_ci_option(self, model_config): + model_config.compute_ci = True + return super()._test_warn_on_unsupported_compute_ci_option( + PersistencePredictionModel, model_config + ) diff --git a/src/im_mad/remotes/lib/python/pyoneai/tests/unit/test_ml/test_predictors_interface.py b/src/im_mad/remotes/lib/python/pyoneai/tests/unit/test_ml/test_predictors_interface.py new file mode 100644 index 0000000000..6af1bb67e3 --- /dev/null +++ b/src/im_mad/remotes/lib/python/pyoneai/tests/unit/test_ml/test_predictors_interface.py @@ -0,0 +1,168 @@ +from datetime import datetime, timedelta, timezone + +import numpy as np +import pytest + +from pyoneai.core.entity_uid import EntityType, EntityUID +from pyoneai.core.time import Instant, Period +from pyoneai.core.tsnumpy.timeseries import Timeseries + + +class TestPredictionModelInterface: + __test__ = False + + @pytest.fixture + def model_config(self): + raise NotImplementedError( + "The 'model_config' fixture must be provided by the test class." + ) + + @pytest.fixture + def prediction_model(self, model_config): + raise NotImplementedError( + "The 'prediction_model' fixture must be provided by the test class." + ) + + def generate_time_index(self, n): + start = datetime(2024, 7, 12, 1, 0, 10, tzinfo=timezone.utc) + freq = timedelta(seconds=10) + if n > 1: + return Period(slice(start, start + (n - 1) * freq, freq)).values + else: + return np.array([start]) + + def generate_data(self, n): + return np.random.random(n) + + def create_univariate_timeseries(self, n): + time_index = self.generate_time_index(n) + data = self.generate_data(n).reshape(-1, 1, 1) + return Timeseries( + time_idx=time_index, + metric_idx=np.array(["metric_x"]), + entity_uid_idx=np.array([EntityUID(EntityType.VIRTUAL_MACHINE, -1)]), + data=data + ) + + def create_multivariate_timeseries(self, n): + time_index = self.generate_time_index(n) + data_x = self.generate_data(n).reshape(-1, 1, 1) + data_y = self.generate_data(n).reshape(-1, 1, 1) + # Combine data for both metrics + data = np.concatenate([data_x, data_y], axis=1) + return Timeseries( + time_idx=time_index, + metric_idx=np.array(["metric_x", "metric_y"]), + entity_uid_idx=np.array([EntityUID(EntityType.VIRTUAL_MACHINE, -1)]), + data=data + ) + + @pytest.mark.parametrize( + "create_timeseries", + ["create_univariate_timeseries", "create_multivariate_timeseries"], + ) + def test_fit_model_returns_self(self, prediction_model, create_timeseries): + ts = getattr(self, create_timeseries)(10) + fitted_model = prediction_model.fit(ts) + assert isinstance( + fitted_model, type(prediction_model) + ), "fit() should return an instance of the prediction model" + + @pytest.mark.parametrize( + "create_timeseries", + ["create_univariate_timeseries", "create_multivariate_timeseries"], + ) + def test_predict_returns_timeseries( + self, prediction_model, create_timeseries + ): + ts = getattr(self, create_timeseries)(10) + predictions = prediction_model.predict(ts, horizon=5) + assert isinstance( + predictions, Timeseries + ), "predict() should return a Timeseries instance" + + @pytest.mark.parametrize( + "create_timeseries", + ["create_univariate_timeseries", "create_multivariate_timeseries"], + ) + def test_predict_returns_timeseries_correct_length( + self, prediction_model, create_timeseries + ): + ts = getattr(self, create_timeseries)(10) + for horizon in [1, 5, 10]: + predictions = prediction_model.predict(ts, horizon=horizon) + assert ( + len(predictions) == horizon + ), f"Predicted timeseries should have {horizon} time steps" + + @pytest.mark.parametrize( + "create_timeseries", + ["create_univariate_timeseries", "create_multivariate_timeseries"], + ) + def test_keep_original_metric_name( + self, prediction_model, create_timeseries + ): + ts = getattr(self, create_timeseries)(10) + predictions = prediction_model.predict(ts, horizon=1) + assert np.array_equal( + predictions.names, ts.names + ), "Metric names should be preserved in the predicted timeseries" + + def test_produce_multivariate_on_multivariate_input( + self, prediction_model + ): + ts = self.create_multivariate_timeseries(10) + predictions = prediction_model.predict(ts, horizon=1) + assert predictions.ndim == ts.ndim + + @pytest.mark.parametrize( + "create_timeseries", + ["create_univariate_timeseries", "create_multivariate_timeseries"], + ) + def test_correct_forecast_timeindex_instant( + self, prediction_model, create_timeseries + ): + ts = getattr(self, create_timeseries)(10) + predictions = prediction_model.predict(ts, horizon=1) + # For the new Timeseries class, we need to check the time index differently + if isinstance(predictions.time_index, Instant): + last_time = ts.time_index.values[-1] + freq = timedelta(seconds=10) # Using the same frequency as in generate_time_index + assert predictions.time_index.value == last_time + freq + else: + assert False, "Expected Instant time index for horizon=1" + + @pytest.mark.parametrize( + "create_timeseries", + ["create_univariate_timeseries", "create_multivariate_timeseries"], + ) + def test_correct_forecast_timeindex_period( + self, prediction_model, create_timeseries + ): + ts = getattr(self, create_timeseries)(10) + predictions = prediction_model.predict(ts, horizon=10) + # For the new Timeseries class, we need to check the time index differently + if isinstance(predictions.time_index, Period): + last_time = ts.time_index.values[-1] + freq = timedelta(seconds=10) # Using the same frequency as in generate_time_index + assert predictions.time_index.values[0] == last_time + freq + else: + assert False, "Expected Period time index for horizon=10" + + + def test_load_model_produces_correct_type( + self, prediction_model, model_config + ): + loaded_model = prediction_model.load(model_config) + assert isinstance(loaded_model, type(prediction_model)) + + def _test_warn_on_unsupported_compute_ci_option( + self, prediction_model_class, model_config + ): + with pytest.warns( + Warning, + match=r"Model of type .* does not " + r"support computation of confidence intervals. " + r"That option will be ignored", + ): + _ = prediction_model_class(model_config) diff --git a/src/oca/ruby/opennebula/virtual_machine.rb b/src/oca/ruby/opennebula/virtual_machine.rb index 9dae147ca1..00b840897c 100644 --- a/src/oca/ruby/opennebula/virtual_machine.rb +++ b/src/oca/ruby/opennebula/virtual_machine.rb @@ -297,15 +297,6 @@ module OpenNebula 'restore' ] - EXTERNAL_IP_ATTRS = [ - 'GUEST_IP', - 'AWS_IP_ADDRESS', - 'AWS_PUBLIC_IP_ADDRESS', - 'AWS_PRIVATE_IP_ADDRESS', - 'AZ_IPADDRESS', - 'SL_PRIMARYIPADDRESS' - ] - # VirtualMachineDriver constants module Driver diff --git a/src/onegate/onegate-server.rb b/src/onegate/onegate-server.rb index 35b41be8e5..ceed7120b2 100644 --- a/src/onegate/onegate-server.rb +++ b/src/onegate/onegate-server.rb @@ -632,14 +632,6 @@ def build_vm_hash(vm_hash) end end - OpenNebula::VirtualMachine::EXTERNAL_IP_ATTRS.each do |attr| - external_ip = vm_hash["MONITORING"][attr] - - if !external_ip.nil? && !nics.include?(external_ip) - nics.push({'IP' => external_ip}) - end - end - { "VM" => { "NAME" => vm_hash["NAME"],