repository_name stringclasses 316 values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1 value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1 value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
Chyroc/WechatSogou | wechatsogou/tools.py | get_first_of_element | python | def get_first_of_element(element, sub, contype=None):
content = element.xpath(sub)
return list_or_empty(content, contype) | 抽取lxml.etree库中elem对象中文字
Args:
element: lxml.etree.Element
sub: str
Returns:
elem中文字 | train | https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/tools.py#L46-L57 | [
"def list_or_empty(content, contype=None):\n assert isinstance(content, list), 'content is not list: {}'.format(content)\n\n if content:\n return contype(content[0]) if contype else content[0]\n else:\n if contype:\n if contype == int:\n return 0\n elif contype == str:\n return ''\n elif contype == list:\n return []\n else:\n raise Exception('only can deal int str list')\n else:\n return ''\n"
] | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals, print_function
import ast
import requests
from wechatsogou.five import url_parse
def list_or_empty(content, contype=None):
assert isinstance(content, list), 'content is not list: {}'.format(content)
if content:
return contype(content[0]) if contype else content[0]
else:
if contype:
if contype == int:
return 0
elif contype == str:
return ''
elif contype == list:
return []
else:
raise Exception('only can deal int str list')
else:
return ''
def get_elem_text(elem):
"""抽取lxml.etree库中elem对象中文字
Args:
elem: lxml.etree库中elem对象
Returns:
elem中文字
"""
if elem != '':
return ''.join([node.strip() for node in elem.itertext()])
else:
return ''
def get_encoding_from_reponse(r):
"""获取requests库get或post返回的对象编码
Args:
r: requests库get或post返回的对象
Returns:
对象编码
"""
encoding = requests.utils.get_encodings_from_content(r.text)
return encoding[0] if encoding else requests.utils.get_encoding_from_headers(r.headers)
def _replace_str_html(s):
"""替换html‘"’等转义内容为正常内容
Args:
s: 文字内容
Returns:
s: 处理反转义后的文字
"""
html_str_list = [
(''', '\''),
('"', '"'),
('&', '&'),
('¥', '¥'),
('amp;', ''),
('<', '<'),
('>', '>'),
(' ', ' '),
('\\', '')
]
for i in html_str_list:
s = s.replace(i[0], i[1])
return s
def replace_html(data):
if isinstance(data, dict):
return dict([(replace_html(k), replace_html(v)) for k, v in data.items()])
elif isinstance(data, list):
return [replace_html(l) for l in data]
elif isinstance(data, str) or isinstance(data, unicode):
return _replace_str_html(data)
else:
return data
def str_to_dict(json_str):
json_dict = ast.literal_eval(json_str)
return replace_html(json_dict)
def replace_space(s):
return s.replace(' ', '').replace('\r\n', '')
def get_url_param(url):
result = url_parse.urlparse(url)
return url_parse.parse_qs(result.query, True)
def format_image_url(url):
if isinstance(url, list):
return [format_image_url(i) for i in url]
if url.startswith('//'):
url = 'https:{}'.format(url)
return url
def may_int(i):
try:
return int(i)
except Exception:
return i
|
Chyroc/WechatSogou | wechatsogou/tools.py | get_encoding_from_reponse | python | def get_encoding_from_reponse(r):
encoding = requests.utils.get_encodings_from_content(r.text)
return encoding[0] if encoding else requests.utils.get_encoding_from_headers(r.headers) | 获取requests库get或post返回的对象编码
Args:
r: requests库get或post返回的对象
Returns:
对象编码 | train | https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/tools.py#L60-L70 | null | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals, print_function
import ast
import requests
from wechatsogou.five import url_parse
def list_or_empty(content, contype=None):
assert isinstance(content, list), 'content is not list: {}'.format(content)
if content:
return contype(content[0]) if contype else content[0]
else:
if contype:
if contype == int:
return 0
elif contype == str:
return ''
elif contype == list:
return []
else:
raise Exception('only can deal int str list')
else:
return ''
def get_elem_text(elem):
"""抽取lxml.etree库中elem对象中文字
Args:
elem: lxml.etree库中elem对象
Returns:
elem中文字
"""
if elem != '':
return ''.join([node.strip() for node in elem.itertext()])
else:
return ''
def get_first_of_element(element, sub, contype=None):
"""抽取lxml.etree库中elem对象中文字
Args:
element: lxml.etree.Element
sub: str
Returns:
elem中文字
"""
content = element.xpath(sub)
return list_or_empty(content, contype)
def _replace_str_html(s):
"""替换html‘"’等转义内容为正常内容
Args:
s: 文字内容
Returns:
s: 处理反转义后的文字
"""
html_str_list = [
(''', '\''),
('"', '"'),
('&', '&'),
('¥', '¥'),
('amp;', ''),
('<', '<'),
('>', '>'),
(' ', ' '),
('\\', '')
]
for i in html_str_list:
s = s.replace(i[0], i[1])
return s
def replace_html(data):
if isinstance(data, dict):
return dict([(replace_html(k), replace_html(v)) for k, v in data.items()])
elif isinstance(data, list):
return [replace_html(l) for l in data]
elif isinstance(data, str) or isinstance(data, unicode):
return _replace_str_html(data)
else:
return data
def str_to_dict(json_str):
json_dict = ast.literal_eval(json_str)
return replace_html(json_dict)
def replace_space(s):
return s.replace(' ', '').replace('\r\n', '')
def get_url_param(url):
result = url_parse.urlparse(url)
return url_parse.parse_qs(result.query, True)
def format_image_url(url):
if isinstance(url, list):
return [format_image_url(i) for i in url]
if url.startswith('//'):
url = 'https:{}'.format(url)
return url
def may_int(i):
try:
return int(i)
except Exception:
return i
|
Chyroc/WechatSogou | wechatsogou/tools.py | _replace_str_html | python | def _replace_str_html(s):
html_str_list = [
(''', '\''),
('"', '"'),
('&', '&'),
('¥', '¥'),
('amp;', ''),
('<', '<'),
('>', '>'),
(' ', ' '),
('\\', '')
]
for i in html_str_list:
s = s.replace(i[0], i[1])
return s | 替换html‘"’等转义内容为正常内容
Args:
s: 文字内容
Returns:
s: 处理反转义后的文字 | train | https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/tools.py#L73-L95 | null | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals, print_function
import ast
import requests
from wechatsogou.five import url_parse
def list_or_empty(content, contype=None):
assert isinstance(content, list), 'content is not list: {}'.format(content)
if content:
return contype(content[0]) if contype else content[0]
else:
if contype:
if contype == int:
return 0
elif contype == str:
return ''
elif contype == list:
return []
else:
raise Exception('only can deal int str list')
else:
return ''
def get_elem_text(elem):
"""抽取lxml.etree库中elem对象中文字
Args:
elem: lxml.etree库中elem对象
Returns:
elem中文字
"""
if elem != '':
return ''.join([node.strip() for node in elem.itertext()])
else:
return ''
def get_first_of_element(element, sub, contype=None):
"""抽取lxml.etree库中elem对象中文字
Args:
element: lxml.etree.Element
sub: str
Returns:
elem中文字
"""
content = element.xpath(sub)
return list_or_empty(content, contype)
def get_encoding_from_reponse(r):
"""获取requests库get或post返回的对象编码
Args:
r: requests库get或post返回的对象
Returns:
对象编码
"""
encoding = requests.utils.get_encodings_from_content(r.text)
return encoding[0] if encoding else requests.utils.get_encoding_from_headers(r.headers)
def replace_html(data):
if isinstance(data, dict):
return dict([(replace_html(k), replace_html(v)) for k, v in data.items()])
elif isinstance(data, list):
return [replace_html(l) for l in data]
elif isinstance(data, str) or isinstance(data, unicode):
return _replace_str_html(data)
else:
return data
def str_to_dict(json_str):
json_dict = ast.literal_eval(json_str)
return replace_html(json_dict)
def replace_space(s):
return s.replace(' ', '').replace('\r\n', '')
def get_url_param(url):
result = url_parse.urlparse(url)
return url_parse.parse_qs(result.query, True)
def format_image_url(url):
if isinstance(url, list):
return [format_image_url(i) for i in url]
if url.startswith('//'):
url = 'https:{}'.format(url)
return url
def may_int(i):
try:
return int(i)
except Exception:
return i
|
Chyroc/WechatSogou | wechatsogou/structuring.py | WechatSogouStructuring.get_gzh_by_search | python | def get_gzh_by_search(text):
post_view_perms = WechatSogouStructuring.__get_post_view_perm(text)
page = etree.HTML(text)
lis = page.xpath('//ul[@class="news-list2"]/li')
relist = []
for li in lis:
url = get_first_of_element(li, 'div/div[1]/a/@href')
headimage = format_image_url(get_first_of_element(li, 'div/div[1]/a/img/@src'))
wechat_name = get_elem_text(get_first_of_element(li, 'div/div[2]/p[1]'))
info = get_elem_text(get_first_of_element(li, 'div/div[2]/p[2]'))
qrcode = get_first_of_element(li, 'div/div[3]/span/img[1]/@src')
introduction = get_elem_text(get_first_of_element(li, 'dl[1]/dd'))
authentication = get_first_of_element(li, 'dl[2]/dd/text()')
relist.append({
'open_id': headimage.split('/')[-1],
'profile_url': url,
'headimage': headimage,
'wechat_name': wechat_name.replace('red_beg', '').replace('red_end', ''),
'wechat_id': info.replace('微信号:', ''),
'qrcode': qrcode,
'introduction': introduction.replace('red_beg', '').replace('red_end', ''),
'authentication': authentication,
'post_perm': -1,
'view_perm': -1,
})
if post_view_perms:
for i in relist:
if i['open_id'] in post_view_perms:
post_view_perm = post_view_perms[i['open_id']].split(',')
if len(post_view_perm) == 2:
i['post_perm'] = int(post_view_perm[0])
i['view_perm'] = int(post_view_perm[1])
return relist | 从搜索公众号获得的文本 提取公众号信息
Parameters
----------
text : str or unicode
搜索公众号获得的文本
Returns
-------
list[dict]
{
'open_id': '', # 微信号唯一ID
'profile_url': '', # 最近10条群发页链接
'headimage': '', # 头像
'wechat_name': '', # 名称
'wechat_id': '', # 微信id
'post_perm': '', # 最近一月群发数
'view_perm': '', # 最近一月阅读量
'qrcode': '', # 二维码
'introduction': '', # 介绍
'authentication': '' # 认证
} | train | https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/structuring.py#L46-L104 | [
"def get_elem_text(elem):\n \"\"\"抽取lxml.etree库中elem对象中文字\n\n Args:\n elem: lxml.etree库中elem对象\n\n Returns:\n elem中文字\n \"\"\"\n if elem != '':\n return ''.join([node.strip() for node in elem.itertext()])\n else:\n return ''\n",
"def get_first_of_element(element, sub, contype=None):\n \"\"\"抽取lxml.etree库中elem对象中文字\n\n Args:\n element: lxml.etree.Element\n sub: str\n\n Returns:\n elem中文字\n \"\"\"\n content = element.xpath(sub)\n return list_or_empty(content, contype)\n",
"def format_image_url(url):\n if isinstance(url, list):\n return [format_image_url(i) for i in url]\n\n if url.startswith('//'):\n url = 'https:{}'.format(url)\n return url\n",
"def __get_post_view_perm(text):\n result = get_post_view_perm.findall(text)\n if not result or len(result) < 1 or not result[0]:\n return None\n\n r = requests.get('http://weixin.sogou.com{}'.format(result[0]))\n if not r.ok:\n return None\n\n if r.json().get('code') != 'success':\n return None\n\n return r.json().get('msg')\n"
] | class WechatSogouStructuring(object):
@staticmethod
def __handle_content_url(content_url):
content_url = replace_html(content_url)
return ('http://mp.weixin.qq.com{}'.format(
content_url) if 'http://mp.weixin.qq.com' not in content_url else content_url) if content_url else ''
@staticmethod
def __get_post_view_perm(text):
result = get_post_view_perm.findall(text)
if not result or len(result) < 1 or not result[0]:
return None
r = requests.get('http://weixin.sogou.com{}'.format(result[0]))
if not r.ok:
return None
if r.json().get('code') != 'success':
return None
return r.json().get('msg')
@staticmethod
@staticmethod
def get_article_by_search_wap(keyword, wap_dict):
datas = []
for i in wap_dict['items']:
item = str_to_bytes(i).replace(b'\xee\x90\x8a' + str_to_bytes(keyword) + b'\xee\x90\x8b',
str_to_bytes(keyword))
root = XML(item)
display = root.find('.//display')
datas.append({
'gzh': {
'profile_url': display.find('encGzhUrl').text,
'open_id': display.find('openid').text,
'isv': display.find('isV').text,
'wechat_name': display.find('sourcename').text,
'wechat_id': display.find('username').text,
'headimage': display.find('headimage').text,
'qrcode': display.find('encQrcodeUrl').text,
},
'article': {
'title': display.find('title').text,
'url': display.find('url').text, # encArticleUrl
'main_img': display.find('imglink').text,
'abstract': display.find('content168').text,
'time': display.find('lastModified').text,
},
})
return datas
@staticmethod
def get_article_by_search(text):
"""从搜索文章获得的文本 提取章列表信息
Parameters
----------
text : str or unicode
搜索文章获得的文本
Returns
-------
list[dict]
{
'article': {
'title': '', # 文章标题
'url': '', # 文章链接
'imgs': '', # 文章图片list
'abstract': '', # 文章摘要
'time': '' # 文章推送时间
},
'gzh': {
'profile_url': '', # 公众号最近10条群发页链接
'headimage': '', # 头像
'wechat_name': '', # 名称
'isv': '', # 是否加v
}
}
"""
page = etree.HTML(text)
lis = page.xpath('//ul[@class="news-list"]/li')
articles = []
for li in lis:
url = get_first_of_element(li, 'div[1]/a/@href')
if url:
title = get_first_of_element(li, 'div[2]/h3/a')
imgs = li.xpath('div[1]/a/img/@src')
abstract = get_first_of_element(li, 'div[2]/p')
time = get_first_of_element(li, 'div[2]/div/span/script/text()')
gzh_info = li.xpath('div[2]/div/a')[0]
else:
url = get_first_of_element(li, 'div/h3/a/@href')
title = get_first_of_element(li, 'div/h3/a')
imgs = []
spans = li.xpath('div/div[1]/a')
for span in spans:
img = span.xpath('span/img/@src')
if img:
imgs.append(img)
abstract = get_first_of_element(li, 'div/p')
time = get_first_of_element(li, 'div/div[2]/span/script/text()')
gzh_info = li.xpath('div/div[2]/a')[0]
if title is not None:
title = get_elem_text(title).replace("red_beg", "").replace("red_end", "")
if abstract is not None:
abstract = get_elem_text(abstract).replace("red_beg", "").replace("red_end", "")
time = re.findall('timeConvert\(\'(.*?)\'\)', time)
time = list_or_empty(time, int)
profile_url = get_first_of_element(gzh_info, '@href')
headimage = get_first_of_element(gzh_info, '@data-headimage')
wechat_name = get_first_of_element(gzh_info, 'text()')
gzh_isv = get_first_of_element(gzh_info, '@data-isv', int)
articles.append({
'article': {
'title': title,
'url': url,
'imgs': format_image_url(imgs),
'abstract': abstract,
'time': time
},
'gzh': {
'profile_url': profile_url,
'headimage': headimage,
'wechat_name': wechat_name,
'isv': gzh_isv,
}
})
return articles
@staticmethod
def get_gzh_info_by_history(text):
"""从 历史消息页的文本 提取公众号信息
Parameters
----------
text : str or unicode
历史消息页的文本
Returns
-------
dict
{
'wechat_name': '', # 名称
'wechat_id': '', # 微信id
'introduction': '', # 描述
'authentication': '', # 认证
'headimage': '' # 头像
}
"""
page = etree.HTML(text)
profile_area = get_first_of_element(page, '//div[@class="profile_info_area"]')
profile_img = get_first_of_element(profile_area, 'div[1]/span/img/@src')
profile_name = get_first_of_element(profile_area, 'div[1]/div/strong/text()')
profile_wechat_id = get_first_of_element(profile_area, 'div[1]/div/p/text()')
profile_desc = get_first_of_element(profile_area, 'ul/li[1]/div/text()')
profile_principal = get_first_of_element(profile_area, 'ul/li[2]/div/text()')
return {
'wechat_name': profile_name.strip(),
'wechat_id': profile_wechat_id.replace('微信号: ', '').strip('\n'),
'introduction': profile_desc,
'authentication': profile_principal,
'headimage': profile_img
}
@staticmethod
def get_article_by_history_json(text, article_json=None):
"""从 历史消息页的文本 提取文章列表信息
Parameters
----------
text : str or unicode
历史消息页的文本
article_json : dict
历史消息页的文本 提取出来的文章json dict
Returns
-------
list[dict]
{
'send_id': '', # 群发id,注意不唯一,因为同一次群发多个消息,而群发id一致
'datetime': '', # 群发datatime
'type': '', # 消息类型,均是49,表示图文
'main': 0, # 是否是一次群发的第一次消息
'title': '', # 文章标题
'abstract': '', # 摘要
'fileid': '', #
'content_url': '', # 文章链接
'source_url': '', # 阅读原文的链接
'cover': '', # 封面图
'author': '', # 作者
'copyright_stat': '', # 文章类型,例如:原创啊
}
"""
if article_json is None:
article_json = find_article_json_re.findall(text)
if not article_json:
return []
article_json = article_json[0] + '}}]}'
article_json = json.loads(article_json)
items = list()
for listdic in article_json['list']:
if str(listdic['comm_msg_info'].get('type', '')) != '49':
continue
comm_msg_info = listdic['comm_msg_info']
app_msg_ext_info = listdic['app_msg_ext_info']
send_id = comm_msg_info.get('id', '')
msg_datetime = comm_msg_info.get('datetime', '')
msg_type = str(comm_msg_info.get('type', ''))
items.append({
'send_id': send_id,
'datetime': msg_datetime,
'type': msg_type,
'main': 1, 'title': app_msg_ext_info.get('title', ''),
'abstract': app_msg_ext_info.get('digest', ''),
'fileid': app_msg_ext_info.get('fileid', ''),
'content_url': WechatSogouStructuring.__handle_content_url(app_msg_ext_info.get('content_url')),
'source_url': app_msg_ext_info.get('source_url', ''),
'cover': app_msg_ext_info.get('cover', ''),
'author': app_msg_ext_info.get('author', ''),
'copyright_stat': app_msg_ext_info.get('copyright_stat', '')
})
if app_msg_ext_info.get('is_multi', 0) == 1:
for multi_dict in app_msg_ext_info['multi_app_msg_item_list']:
items.append({
'send_id': send_id,
'datetime': msg_datetime,
'type': msg_type,
'main': 0, 'title': multi_dict.get('title', ''),
'abstract': multi_dict.get('digest', ''),
'fileid': multi_dict.get('fileid', ''),
'content_url': WechatSogouStructuring.__handle_content_url(multi_dict.get('content_url')),
'source_url': multi_dict.get('source_url', ''),
'cover': multi_dict.get('cover', ''),
'author': multi_dict.get('author', ''),
'copyright_stat': multi_dict.get('copyright_stat', '')
})
return list(filter(lambda x: x['content_url'], items)) # 删除搜狗本身携带的空数据
@staticmethod
def get_gzh_info_and_article_by_history(text):
"""从 历史消息页的文本 提取公众号信息 和 文章列表信息
Parameters
----------
text : str or unicode
历史消息页的文本
Returns
-------
dict
{
'gzh': {
'wechat_name': '', # 名称
'wechat_id': '', # 微信id
'introduction': '', # 描述
'authentication': '', # 认证
'headimage': '' # 头像
},
'article': [
{
'send_id': '', # 群发id,注意不唯一,因为同一次群发多个消息,而群发id一致
'datetime': '', # 群发datatime
'type': '', # 消息类型,均是49,表示图文
'main': 0, # 是否是一次群发的第一次消息
'title': '', # 文章标题
'abstract': '', # 摘要
'fileid': '', #
'content_url': '', # 文章链接
'source_url': '', # 阅读原文的链接
'cover': '', # 封面图
'author': '', # 作者
'copyright_stat': '', # 文章类型,例如:原创啊
},
...
]
}
"""
return {
'gzh': WechatSogouStructuring.get_gzh_info_by_history(text),
'article': WechatSogouStructuring.get_article_by_history_json(text)
}
@staticmethod
def get_gzh_article_by_hot(text):
"""从 首页热门搜索 提取公众号信息 和 文章列表信息
Parameters
----------
text : str or unicode
首页热门搜索 页 中 某一页 的文本
Returns
-------
list[dict]
{
'gzh': {
'headimage': str, # 公众号头像
'wechat_name': str, # 公众号名称
},
'article': {
'url': str, # 文章临时链接
'title': str, # 文章标题
'abstract': str, # 文章摘要
'time': int, # 推送时间,10位时间戳
'open_id': str, # open id
'main_img': str # 封面图片
}
}
"""
page = etree.HTML(text)
lis = page.xpath('/html/body/li')
gzh_article_list = []
for li in lis:
url = get_first_of_element(li, 'div[1]/h4/a/@href')
title = get_first_of_element(li, 'div[1]/h4/a/div/text()')
abstract = get_first_of_element(li, 'div[1]/p[1]/text()')
xpath_time = get_first_of_element(li, 'div[1]/p[2]')
open_id = get_first_of_element(xpath_time, 'span/@data-openid')
headimage = get_first_of_element(xpath_time, 'span/@data-headimage')
gzh_name = get_first_of_element(xpath_time, 'span/text()')
send_time = xpath_time.xpath('a/span/@data-lastmodified')
main_img = get_first_of_element(li, 'div[2]/a/img/@src')
try:
send_time = int(send_time[0])
except ValueError:
send_time = send_time[0]
gzh_article_list.append({
'gzh': {
'headimage': headimage,
'wechat_name': gzh_name,
},
'article': {
'url': url,
'title': title,
'abstract': abstract,
'time': send_time,
'open_id': open_id,
'main_img': main_img
}
})
return gzh_article_list
@staticmethod
def get_article_detail(text, del_qqmusic=True, del_voice=True):
"""根据微信文章的临时链接获取明细
1. 获取文本中所有的图片链接列表
2. 获取微信文章的html内容页面(去除标题等信息)
Parameters
----------
text : str or unicode
一篇微信文章的文本
del_qqmusic: bool
删除文章中的qq音乐
del_voice: bool
删除文章中的语音内容
Returns
-------
dict
{
'content_html': str # 微信文本内容
'content_img_list': list[img_url1, img_url2, ...] # 微信文本中图片列表
}
"""
# 1. 获取微信文本content
html_obj = BeautifulSoup(text, "lxml")
content_text = html_obj.find('div', {'class': 'rich_media_content', 'id': 'js_content'})
# 2. 删除部分标签
if del_qqmusic:
qqmusic = content_text.find_all('qqmusic') or []
for music in qqmusic:
music.parent.decompose()
if del_voice:
# voice是一个p标签下的mpvoice标签以及class为'js_audio_frame db'的span构成,所以将父标签删除
voices = content_text.find_all('mpvoice') or []
for voice in voices:
voice.parent.decompose()
# 3. 获取所有的图片 [img标签,和style中的background-image]
all_img_set = set()
all_img_element = content_text.find_all('img') or []
for ele in all_img_element:
# 删除部分属性
img_url = format_image_url(ele.attrs['data-src'])
del ele.attrs['data-src']
ele.attrs['src'] = img_url
if not img_url.startswith('http'):
raise WechatSogouException('img_url [{}] 不合法'.format(img_url))
all_img_set.add(img_url)
backgroud_image = content_text.find_all(style=re.compile("background-image")) or []
for ele in backgroud_image:
# 删除部分属性
if ele.attrs.get('data-src'):
del ele.attrs['data-src']
if ele.attrs.get('data-wxurl'):
del ele.attrs['data-wxurl']
img_url = re.findall(backgroud_image_p, str(ele))
if not img_url:
continue
all_img_set.add(img_url[0])
# 4. 处理iframe
all_img_element = content_text.find_all('iframe') or []
for ele in all_img_element:
# 删除部分属性
img_url = ele.attrs['data-src']
del ele.attrs['data-src']
ele.attrs['src'] = img_url
# 5. 返回数据
all_img_list = list(all_img_set)
content_html = content_text.prettify()
# 去除div[id=js_content]
content_html = re.findall(js_content, content_html)[0][0]
return {
'content_html': content_html,
'content_img_list': all_img_list
}
|
Chyroc/WechatSogou | wechatsogou/structuring.py | WechatSogouStructuring.get_article_by_search | python | def get_article_by_search(text):
page = etree.HTML(text)
lis = page.xpath('//ul[@class="news-list"]/li')
articles = []
for li in lis:
url = get_first_of_element(li, 'div[1]/a/@href')
if url:
title = get_first_of_element(li, 'div[2]/h3/a')
imgs = li.xpath('div[1]/a/img/@src')
abstract = get_first_of_element(li, 'div[2]/p')
time = get_first_of_element(li, 'div[2]/div/span/script/text()')
gzh_info = li.xpath('div[2]/div/a')[0]
else:
url = get_first_of_element(li, 'div/h3/a/@href')
title = get_first_of_element(li, 'div/h3/a')
imgs = []
spans = li.xpath('div/div[1]/a')
for span in spans:
img = span.xpath('span/img/@src')
if img:
imgs.append(img)
abstract = get_first_of_element(li, 'div/p')
time = get_first_of_element(li, 'div/div[2]/span/script/text()')
gzh_info = li.xpath('div/div[2]/a')[0]
if title is not None:
title = get_elem_text(title).replace("red_beg", "").replace("red_end", "")
if abstract is not None:
abstract = get_elem_text(abstract).replace("red_beg", "").replace("red_end", "")
time = re.findall('timeConvert\(\'(.*?)\'\)', time)
time = list_or_empty(time, int)
profile_url = get_first_of_element(gzh_info, '@href')
headimage = get_first_of_element(gzh_info, '@data-headimage')
wechat_name = get_first_of_element(gzh_info, 'text()')
gzh_isv = get_first_of_element(gzh_info, '@data-isv', int)
articles.append({
'article': {
'title': title,
'url': url,
'imgs': format_image_url(imgs),
'abstract': abstract,
'time': time
},
'gzh': {
'profile_url': profile_url,
'headimage': headimage,
'wechat_name': wechat_name,
'isv': gzh_isv,
}
})
return articles | 从搜索文章获得的文本 提取章列表信息
Parameters
----------
text : str or unicode
搜索文章获得的文本
Returns
-------
list[dict]
{
'article': {
'title': '', # 文章标题
'url': '', # 文章链接
'imgs': '', # 文章图片list
'abstract': '', # 文章摘要
'time': '' # 文章推送时间
},
'gzh': {
'profile_url': '', # 公众号最近10条群发页链接
'headimage': '', # 头像
'wechat_name': '', # 名称
'isv': '', # 是否加v
}
} | train | https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/structuring.py#L136-L215 | [
"def get_elem_text(elem):\n \"\"\"抽取lxml.etree库中elem对象中文字\n\n Args:\n elem: lxml.etree库中elem对象\n\n Returns:\n elem中文字\n \"\"\"\n if elem != '':\n return ''.join([node.strip() for node in elem.itertext()])\n else:\n return ''\n",
"def list_or_empty(content, contype=None):\n assert isinstance(content, list), 'content is not list: {}'.format(content)\n\n if content:\n return contype(content[0]) if contype else content[0]\n else:\n if contype:\n if contype == int:\n return 0\n elif contype == str:\n return ''\n elif contype == list:\n return []\n else:\n raise Exception('only can deal int str list')\n else:\n return ''\n",
"def get_first_of_element(element, sub, contype=None):\n \"\"\"抽取lxml.etree库中elem对象中文字\n\n Args:\n element: lxml.etree.Element\n sub: str\n\n Returns:\n elem中文字\n \"\"\"\n content = element.xpath(sub)\n return list_or_empty(content, contype)\n",
"def format_image_url(url):\n if isinstance(url, list):\n return [format_image_url(i) for i in url]\n\n if url.startswith('//'):\n url = 'https:{}'.format(url)\n return url\n"
] | class WechatSogouStructuring(object):
@staticmethod
def __handle_content_url(content_url):
content_url = replace_html(content_url)
return ('http://mp.weixin.qq.com{}'.format(
content_url) if 'http://mp.weixin.qq.com' not in content_url else content_url) if content_url else ''
@staticmethod
def __get_post_view_perm(text):
result = get_post_view_perm.findall(text)
if not result or len(result) < 1 or not result[0]:
return None
r = requests.get('http://weixin.sogou.com{}'.format(result[0]))
if not r.ok:
return None
if r.json().get('code') != 'success':
return None
return r.json().get('msg')
@staticmethod
def get_gzh_by_search(text):
"""从搜索公众号获得的文本 提取公众号信息
Parameters
----------
text : str or unicode
搜索公众号获得的文本
Returns
-------
list[dict]
{
'open_id': '', # 微信号唯一ID
'profile_url': '', # 最近10条群发页链接
'headimage': '', # 头像
'wechat_name': '', # 名称
'wechat_id': '', # 微信id
'post_perm': '', # 最近一月群发数
'view_perm': '', # 最近一月阅读量
'qrcode': '', # 二维码
'introduction': '', # 介绍
'authentication': '' # 认证
}
"""
post_view_perms = WechatSogouStructuring.__get_post_view_perm(text)
page = etree.HTML(text)
lis = page.xpath('//ul[@class="news-list2"]/li')
relist = []
for li in lis:
url = get_first_of_element(li, 'div/div[1]/a/@href')
headimage = format_image_url(get_first_of_element(li, 'div/div[1]/a/img/@src'))
wechat_name = get_elem_text(get_first_of_element(li, 'div/div[2]/p[1]'))
info = get_elem_text(get_first_of_element(li, 'div/div[2]/p[2]'))
qrcode = get_first_of_element(li, 'div/div[3]/span/img[1]/@src')
introduction = get_elem_text(get_first_of_element(li, 'dl[1]/dd'))
authentication = get_first_of_element(li, 'dl[2]/dd/text()')
relist.append({
'open_id': headimage.split('/')[-1],
'profile_url': url,
'headimage': headimage,
'wechat_name': wechat_name.replace('red_beg', '').replace('red_end', ''),
'wechat_id': info.replace('微信号:', ''),
'qrcode': qrcode,
'introduction': introduction.replace('red_beg', '').replace('red_end', ''),
'authentication': authentication,
'post_perm': -1,
'view_perm': -1,
})
if post_view_perms:
for i in relist:
if i['open_id'] in post_view_perms:
post_view_perm = post_view_perms[i['open_id']].split(',')
if len(post_view_perm) == 2:
i['post_perm'] = int(post_view_perm[0])
i['view_perm'] = int(post_view_perm[1])
return relist
@staticmethod
def get_article_by_search_wap(keyword, wap_dict):
datas = []
for i in wap_dict['items']:
item = str_to_bytes(i).replace(b'\xee\x90\x8a' + str_to_bytes(keyword) + b'\xee\x90\x8b',
str_to_bytes(keyword))
root = XML(item)
display = root.find('.//display')
datas.append({
'gzh': {
'profile_url': display.find('encGzhUrl').text,
'open_id': display.find('openid').text,
'isv': display.find('isV').text,
'wechat_name': display.find('sourcename').text,
'wechat_id': display.find('username').text,
'headimage': display.find('headimage').text,
'qrcode': display.find('encQrcodeUrl').text,
},
'article': {
'title': display.find('title').text,
'url': display.find('url').text, # encArticleUrl
'main_img': display.find('imglink').text,
'abstract': display.find('content168').text,
'time': display.find('lastModified').text,
},
})
return datas
@staticmethod
@staticmethod
def get_gzh_info_by_history(text):
"""从 历史消息页的文本 提取公众号信息
Parameters
----------
text : str or unicode
历史消息页的文本
Returns
-------
dict
{
'wechat_name': '', # 名称
'wechat_id': '', # 微信id
'introduction': '', # 描述
'authentication': '', # 认证
'headimage': '' # 头像
}
"""
page = etree.HTML(text)
profile_area = get_first_of_element(page, '//div[@class="profile_info_area"]')
profile_img = get_first_of_element(profile_area, 'div[1]/span/img/@src')
profile_name = get_first_of_element(profile_area, 'div[1]/div/strong/text()')
profile_wechat_id = get_first_of_element(profile_area, 'div[1]/div/p/text()')
profile_desc = get_first_of_element(profile_area, 'ul/li[1]/div/text()')
profile_principal = get_first_of_element(profile_area, 'ul/li[2]/div/text()')
return {
'wechat_name': profile_name.strip(),
'wechat_id': profile_wechat_id.replace('微信号: ', '').strip('\n'),
'introduction': profile_desc,
'authentication': profile_principal,
'headimage': profile_img
}
@staticmethod
def get_article_by_history_json(text, article_json=None):
"""从 历史消息页的文本 提取文章列表信息
Parameters
----------
text : str or unicode
历史消息页的文本
article_json : dict
历史消息页的文本 提取出来的文章json dict
Returns
-------
list[dict]
{
'send_id': '', # 群发id,注意不唯一,因为同一次群发多个消息,而群发id一致
'datetime': '', # 群发datatime
'type': '', # 消息类型,均是49,表示图文
'main': 0, # 是否是一次群发的第一次消息
'title': '', # 文章标题
'abstract': '', # 摘要
'fileid': '', #
'content_url': '', # 文章链接
'source_url': '', # 阅读原文的链接
'cover': '', # 封面图
'author': '', # 作者
'copyright_stat': '', # 文章类型,例如:原创啊
}
"""
if article_json is None:
article_json = find_article_json_re.findall(text)
if not article_json:
return []
article_json = article_json[0] + '}}]}'
article_json = json.loads(article_json)
items = list()
for listdic in article_json['list']:
if str(listdic['comm_msg_info'].get('type', '')) != '49':
continue
comm_msg_info = listdic['comm_msg_info']
app_msg_ext_info = listdic['app_msg_ext_info']
send_id = comm_msg_info.get('id', '')
msg_datetime = comm_msg_info.get('datetime', '')
msg_type = str(comm_msg_info.get('type', ''))
items.append({
'send_id': send_id,
'datetime': msg_datetime,
'type': msg_type,
'main': 1, 'title': app_msg_ext_info.get('title', ''),
'abstract': app_msg_ext_info.get('digest', ''),
'fileid': app_msg_ext_info.get('fileid', ''),
'content_url': WechatSogouStructuring.__handle_content_url(app_msg_ext_info.get('content_url')),
'source_url': app_msg_ext_info.get('source_url', ''),
'cover': app_msg_ext_info.get('cover', ''),
'author': app_msg_ext_info.get('author', ''),
'copyright_stat': app_msg_ext_info.get('copyright_stat', '')
})
if app_msg_ext_info.get('is_multi', 0) == 1:
for multi_dict in app_msg_ext_info['multi_app_msg_item_list']:
items.append({
'send_id': send_id,
'datetime': msg_datetime,
'type': msg_type,
'main': 0, 'title': multi_dict.get('title', ''),
'abstract': multi_dict.get('digest', ''),
'fileid': multi_dict.get('fileid', ''),
'content_url': WechatSogouStructuring.__handle_content_url(multi_dict.get('content_url')),
'source_url': multi_dict.get('source_url', ''),
'cover': multi_dict.get('cover', ''),
'author': multi_dict.get('author', ''),
'copyright_stat': multi_dict.get('copyright_stat', '')
})
return list(filter(lambda x: x['content_url'], items)) # 删除搜狗本身携带的空数据
@staticmethod
def get_gzh_info_and_article_by_history(text):
"""从 历史消息页的文本 提取公众号信息 和 文章列表信息
Parameters
----------
text : str or unicode
历史消息页的文本
Returns
-------
dict
{
'gzh': {
'wechat_name': '', # 名称
'wechat_id': '', # 微信id
'introduction': '', # 描述
'authentication': '', # 认证
'headimage': '' # 头像
},
'article': [
{
'send_id': '', # 群发id,注意不唯一,因为同一次群发多个消息,而群发id一致
'datetime': '', # 群发datatime
'type': '', # 消息类型,均是49,表示图文
'main': 0, # 是否是一次群发的第一次消息
'title': '', # 文章标题
'abstract': '', # 摘要
'fileid': '', #
'content_url': '', # 文章链接
'source_url': '', # 阅读原文的链接
'cover': '', # 封面图
'author': '', # 作者
'copyright_stat': '', # 文章类型,例如:原创啊
},
...
]
}
"""
return {
'gzh': WechatSogouStructuring.get_gzh_info_by_history(text),
'article': WechatSogouStructuring.get_article_by_history_json(text)
}
@staticmethod
def get_gzh_article_by_hot(text):
"""从 首页热门搜索 提取公众号信息 和 文章列表信息
Parameters
----------
text : str or unicode
首页热门搜索 页 中 某一页 的文本
Returns
-------
list[dict]
{
'gzh': {
'headimage': str, # 公众号头像
'wechat_name': str, # 公众号名称
},
'article': {
'url': str, # 文章临时链接
'title': str, # 文章标题
'abstract': str, # 文章摘要
'time': int, # 推送时间,10位时间戳
'open_id': str, # open id
'main_img': str # 封面图片
}
}
"""
page = etree.HTML(text)
lis = page.xpath('/html/body/li')
gzh_article_list = []
for li in lis:
url = get_first_of_element(li, 'div[1]/h4/a/@href')
title = get_first_of_element(li, 'div[1]/h4/a/div/text()')
abstract = get_first_of_element(li, 'div[1]/p[1]/text()')
xpath_time = get_first_of_element(li, 'div[1]/p[2]')
open_id = get_first_of_element(xpath_time, 'span/@data-openid')
headimage = get_first_of_element(xpath_time, 'span/@data-headimage')
gzh_name = get_first_of_element(xpath_time, 'span/text()')
send_time = xpath_time.xpath('a/span/@data-lastmodified')
main_img = get_first_of_element(li, 'div[2]/a/img/@src')
try:
send_time = int(send_time[0])
except ValueError:
send_time = send_time[0]
gzh_article_list.append({
'gzh': {
'headimage': headimage,
'wechat_name': gzh_name,
},
'article': {
'url': url,
'title': title,
'abstract': abstract,
'time': send_time,
'open_id': open_id,
'main_img': main_img
}
})
return gzh_article_list
@staticmethod
def get_article_detail(text, del_qqmusic=True, del_voice=True):
"""根据微信文章的临时链接获取明细
1. 获取文本中所有的图片链接列表
2. 获取微信文章的html内容页面(去除标题等信息)
Parameters
----------
text : str or unicode
一篇微信文章的文本
del_qqmusic: bool
删除文章中的qq音乐
del_voice: bool
删除文章中的语音内容
Returns
-------
dict
{
'content_html': str # 微信文本内容
'content_img_list': list[img_url1, img_url2, ...] # 微信文本中图片列表
}
"""
# 1. 获取微信文本content
html_obj = BeautifulSoup(text, "lxml")
content_text = html_obj.find('div', {'class': 'rich_media_content', 'id': 'js_content'})
# 2. 删除部分标签
if del_qqmusic:
qqmusic = content_text.find_all('qqmusic') or []
for music in qqmusic:
music.parent.decompose()
if del_voice:
# voice是一个p标签下的mpvoice标签以及class为'js_audio_frame db'的span构成,所以将父标签删除
voices = content_text.find_all('mpvoice') or []
for voice in voices:
voice.parent.decompose()
# 3. 获取所有的图片 [img标签,和style中的background-image]
all_img_set = set()
all_img_element = content_text.find_all('img') or []
for ele in all_img_element:
# 删除部分属性
img_url = format_image_url(ele.attrs['data-src'])
del ele.attrs['data-src']
ele.attrs['src'] = img_url
if not img_url.startswith('http'):
raise WechatSogouException('img_url [{}] 不合法'.format(img_url))
all_img_set.add(img_url)
backgroud_image = content_text.find_all(style=re.compile("background-image")) or []
for ele in backgroud_image:
# 删除部分属性
if ele.attrs.get('data-src'):
del ele.attrs['data-src']
if ele.attrs.get('data-wxurl'):
del ele.attrs['data-wxurl']
img_url = re.findall(backgroud_image_p, str(ele))
if not img_url:
continue
all_img_set.add(img_url[0])
# 4. 处理iframe
all_img_element = content_text.find_all('iframe') or []
for ele in all_img_element:
# 删除部分属性
img_url = ele.attrs['data-src']
del ele.attrs['data-src']
ele.attrs['src'] = img_url
# 5. 返回数据
all_img_list = list(all_img_set)
content_html = content_text.prettify()
# 去除div[id=js_content]
content_html = re.findall(js_content, content_html)[0][0]
return {
'content_html': content_html,
'content_img_list': all_img_list
}
|
Chyroc/WechatSogou | wechatsogou/structuring.py | WechatSogouStructuring.get_gzh_info_by_history | python | def get_gzh_info_by_history(text):
page = etree.HTML(text)
profile_area = get_first_of_element(page, '//div[@class="profile_info_area"]')
profile_img = get_first_of_element(profile_area, 'div[1]/span/img/@src')
profile_name = get_first_of_element(profile_area, 'div[1]/div/strong/text()')
profile_wechat_id = get_first_of_element(profile_area, 'div[1]/div/p/text()')
profile_desc = get_first_of_element(profile_area, 'ul/li[1]/div/text()')
profile_principal = get_first_of_element(profile_area, 'ul/li[2]/div/text()')
return {
'wechat_name': profile_name.strip(),
'wechat_id': profile_wechat_id.replace('微信号: ', '').strip('\n'),
'introduction': profile_desc,
'authentication': profile_principal,
'headimage': profile_img
} | 从 历史消息页的文本 提取公众号信息
Parameters
----------
text : str or unicode
历史消息页的文本
Returns
-------
dict
{
'wechat_name': '', # 名称
'wechat_id': '', # 微信id
'introduction': '', # 描述
'authentication': '', # 认证
'headimage': '' # 头像
} | train | https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/structuring.py#L218-L253 | [
"def get_first_of_element(element, sub, contype=None):\n \"\"\"抽取lxml.etree库中elem对象中文字\n\n Args:\n element: lxml.etree.Element\n sub: str\n\n Returns:\n elem中文字\n \"\"\"\n content = element.xpath(sub)\n return list_or_empty(content, contype)\n"
] | class WechatSogouStructuring(object):
@staticmethod
def __handle_content_url(content_url):
content_url = replace_html(content_url)
return ('http://mp.weixin.qq.com{}'.format(
content_url) if 'http://mp.weixin.qq.com' not in content_url else content_url) if content_url else ''
@staticmethod
def __get_post_view_perm(text):
result = get_post_view_perm.findall(text)
if not result or len(result) < 1 or not result[0]:
return None
r = requests.get('http://weixin.sogou.com{}'.format(result[0]))
if not r.ok:
return None
if r.json().get('code') != 'success':
return None
return r.json().get('msg')
@staticmethod
def get_gzh_by_search(text):
"""从搜索公众号获得的文本 提取公众号信息
Parameters
----------
text : str or unicode
搜索公众号获得的文本
Returns
-------
list[dict]
{
'open_id': '', # 微信号唯一ID
'profile_url': '', # 最近10条群发页链接
'headimage': '', # 头像
'wechat_name': '', # 名称
'wechat_id': '', # 微信id
'post_perm': '', # 最近一月群发数
'view_perm': '', # 最近一月阅读量
'qrcode': '', # 二维码
'introduction': '', # 介绍
'authentication': '' # 认证
}
"""
post_view_perms = WechatSogouStructuring.__get_post_view_perm(text)
page = etree.HTML(text)
lis = page.xpath('//ul[@class="news-list2"]/li')
relist = []
for li in lis:
url = get_first_of_element(li, 'div/div[1]/a/@href')
headimage = format_image_url(get_first_of_element(li, 'div/div[1]/a/img/@src'))
wechat_name = get_elem_text(get_first_of_element(li, 'div/div[2]/p[1]'))
info = get_elem_text(get_first_of_element(li, 'div/div[2]/p[2]'))
qrcode = get_first_of_element(li, 'div/div[3]/span/img[1]/@src')
introduction = get_elem_text(get_first_of_element(li, 'dl[1]/dd'))
authentication = get_first_of_element(li, 'dl[2]/dd/text()')
relist.append({
'open_id': headimage.split('/')[-1],
'profile_url': url,
'headimage': headimage,
'wechat_name': wechat_name.replace('red_beg', '').replace('red_end', ''),
'wechat_id': info.replace('微信号:', ''),
'qrcode': qrcode,
'introduction': introduction.replace('red_beg', '').replace('red_end', ''),
'authentication': authentication,
'post_perm': -1,
'view_perm': -1,
})
if post_view_perms:
for i in relist:
if i['open_id'] in post_view_perms:
post_view_perm = post_view_perms[i['open_id']].split(',')
if len(post_view_perm) == 2:
i['post_perm'] = int(post_view_perm[0])
i['view_perm'] = int(post_view_perm[1])
return relist
@staticmethod
def get_article_by_search_wap(keyword, wap_dict):
datas = []
for i in wap_dict['items']:
item = str_to_bytes(i).replace(b'\xee\x90\x8a' + str_to_bytes(keyword) + b'\xee\x90\x8b',
str_to_bytes(keyword))
root = XML(item)
display = root.find('.//display')
datas.append({
'gzh': {
'profile_url': display.find('encGzhUrl').text,
'open_id': display.find('openid').text,
'isv': display.find('isV').text,
'wechat_name': display.find('sourcename').text,
'wechat_id': display.find('username').text,
'headimage': display.find('headimage').text,
'qrcode': display.find('encQrcodeUrl').text,
},
'article': {
'title': display.find('title').text,
'url': display.find('url').text, # encArticleUrl
'main_img': display.find('imglink').text,
'abstract': display.find('content168').text,
'time': display.find('lastModified').text,
},
})
return datas
@staticmethod
def get_article_by_search(text):
"""从搜索文章获得的文本 提取章列表信息
Parameters
----------
text : str or unicode
搜索文章获得的文本
Returns
-------
list[dict]
{
'article': {
'title': '', # 文章标题
'url': '', # 文章链接
'imgs': '', # 文章图片list
'abstract': '', # 文章摘要
'time': '' # 文章推送时间
},
'gzh': {
'profile_url': '', # 公众号最近10条群发页链接
'headimage': '', # 头像
'wechat_name': '', # 名称
'isv': '', # 是否加v
}
}
"""
page = etree.HTML(text)
lis = page.xpath('//ul[@class="news-list"]/li')
articles = []
for li in lis:
url = get_first_of_element(li, 'div[1]/a/@href')
if url:
title = get_first_of_element(li, 'div[2]/h3/a')
imgs = li.xpath('div[1]/a/img/@src')
abstract = get_first_of_element(li, 'div[2]/p')
time = get_first_of_element(li, 'div[2]/div/span/script/text()')
gzh_info = li.xpath('div[2]/div/a')[0]
else:
url = get_first_of_element(li, 'div/h3/a/@href')
title = get_first_of_element(li, 'div/h3/a')
imgs = []
spans = li.xpath('div/div[1]/a')
for span in spans:
img = span.xpath('span/img/@src')
if img:
imgs.append(img)
abstract = get_first_of_element(li, 'div/p')
time = get_first_of_element(li, 'div/div[2]/span/script/text()')
gzh_info = li.xpath('div/div[2]/a')[0]
if title is not None:
title = get_elem_text(title).replace("red_beg", "").replace("red_end", "")
if abstract is not None:
abstract = get_elem_text(abstract).replace("red_beg", "").replace("red_end", "")
time = re.findall('timeConvert\(\'(.*?)\'\)', time)
time = list_or_empty(time, int)
profile_url = get_first_of_element(gzh_info, '@href')
headimage = get_first_of_element(gzh_info, '@data-headimage')
wechat_name = get_first_of_element(gzh_info, 'text()')
gzh_isv = get_first_of_element(gzh_info, '@data-isv', int)
articles.append({
'article': {
'title': title,
'url': url,
'imgs': format_image_url(imgs),
'abstract': abstract,
'time': time
},
'gzh': {
'profile_url': profile_url,
'headimage': headimage,
'wechat_name': wechat_name,
'isv': gzh_isv,
}
})
return articles
@staticmethod
@staticmethod
def get_article_by_history_json(text, article_json=None):
"""从 历史消息页的文本 提取文章列表信息
Parameters
----------
text : str or unicode
历史消息页的文本
article_json : dict
历史消息页的文本 提取出来的文章json dict
Returns
-------
list[dict]
{
'send_id': '', # 群发id,注意不唯一,因为同一次群发多个消息,而群发id一致
'datetime': '', # 群发datatime
'type': '', # 消息类型,均是49,表示图文
'main': 0, # 是否是一次群发的第一次消息
'title': '', # 文章标题
'abstract': '', # 摘要
'fileid': '', #
'content_url': '', # 文章链接
'source_url': '', # 阅读原文的链接
'cover': '', # 封面图
'author': '', # 作者
'copyright_stat': '', # 文章类型,例如:原创啊
}
"""
if article_json is None:
article_json = find_article_json_re.findall(text)
if not article_json:
return []
article_json = article_json[0] + '}}]}'
article_json = json.loads(article_json)
items = list()
for listdic in article_json['list']:
if str(listdic['comm_msg_info'].get('type', '')) != '49':
continue
comm_msg_info = listdic['comm_msg_info']
app_msg_ext_info = listdic['app_msg_ext_info']
send_id = comm_msg_info.get('id', '')
msg_datetime = comm_msg_info.get('datetime', '')
msg_type = str(comm_msg_info.get('type', ''))
items.append({
'send_id': send_id,
'datetime': msg_datetime,
'type': msg_type,
'main': 1, 'title': app_msg_ext_info.get('title', ''),
'abstract': app_msg_ext_info.get('digest', ''),
'fileid': app_msg_ext_info.get('fileid', ''),
'content_url': WechatSogouStructuring.__handle_content_url(app_msg_ext_info.get('content_url')),
'source_url': app_msg_ext_info.get('source_url', ''),
'cover': app_msg_ext_info.get('cover', ''),
'author': app_msg_ext_info.get('author', ''),
'copyright_stat': app_msg_ext_info.get('copyright_stat', '')
})
if app_msg_ext_info.get('is_multi', 0) == 1:
for multi_dict in app_msg_ext_info['multi_app_msg_item_list']:
items.append({
'send_id': send_id,
'datetime': msg_datetime,
'type': msg_type,
'main': 0, 'title': multi_dict.get('title', ''),
'abstract': multi_dict.get('digest', ''),
'fileid': multi_dict.get('fileid', ''),
'content_url': WechatSogouStructuring.__handle_content_url(multi_dict.get('content_url')),
'source_url': multi_dict.get('source_url', ''),
'cover': multi_dict.get('cover', ''),
'author': multi_dict.get('author', ''),
'copyright_stat': multi_dict.get('copyright_stat', '')
})
return list(filter(lambda x: x['content_url'], items)) # 删除搜狗本身携带的空数据
@staticmethod
def get_gzh_info_and_article_by_history(text):
"""从 历史消息页的文本 提取公众号信息 和 文章列表信息
Parameters
----------
text : str or unicode
历史消息页的文本
Returns
-------
dict
{
'gzh': {
'wechat_name': '', # 名称
'wechat_id': '', # 微信id
'introduction': '', # 描述
'authentication': '', # 认证
'headimage': '' # 头像
},
'article': [
{
'send_id': '', # 群发id,注意不唯一,因为同一次群发多个消息,而群发id一致
'datetime': '', # 群发datatime
'type': '', # 消息类型,均是49,表示图文
'main': 0, # 是否是一次群发的第一次消息
'title': '', # 文章标题
'abstract': '', # 摘要
'fileid': '', #
'content_url': '', # 文章链接
'source_url': '', # 阅读原文的链接
'cover': '', # 封面图
'author': '', # 作者
'copyright_stat': '', # 文章类型,例如:原创啊
},
...
]
}
"""
return {
'gzh': WechatSogouStructuring.get_gzh_info_by_history(text),
'article': WechatSogouStructuring.get_article_by_history_json(text)
}
@staticmethod
def get_gzh_article_by_hot(text):
"""从 首页热门搜索 提取公众号信息 和 文章列表信息
Parameters
----------
text : str or unicode
首页热门搜索 页 中 某一页 的文本
Returns
-------
list[dict]
{
'gzh': {
'headimage': str, # 公众号头像
'wechat_name': str, # 公众号名称
},
'article': {
'url': str, # 文章临时链接
'title': str, # 文章标题
'abstract': str, # 文章摘要
'time': int, # 推送时间,10位时间戳
'open_id': str, # open id
'main_img': str # 封面图片
}
}
"""
page = etree.HTML(text)
lis = page.xpath('/html/body/li')
gzh_article_list = []
for li in lis:
url = get_first_of_element(li, 'div[1]/h4/a/@href')
title = get_first_of_element(li, 'div[1]/h4/a/div/text()')
abstract = get_first_of_element(li, 'div[1]/p[1]/text()')
xpath_time = get_first_of_element(li, 'div[1]/p[2]')
open_id = get_first_of_element(xpath_time, 'span/@data-openid')
headimage = get_first_of_element(xpath_time, 'span/@data-headimage')
gzh_name = get_first_of_element(xpath_time, 'span/text()')
send_time = xpath_time.xpath('a/span/@data-lastmodified')
main_img = get_first_of_element(li, 'div[2]/a/img/@src')
try:
send_time = int(send_time[0])
except ValueError:
send_time = send_time[0]
gzh_article_list.append({
'gzh': {
'headimage': headimage,
'wechat_name': gzh_name,
},
'article': {
'url': url,
'title': title,
'abstract': abstract,
'time': send_time,
'open_id': open_id,
'main_img': main_img
}
})
return gzh_article_list
@staticmethod
def get_article_detail(text, del_qqmusic=True, del_voice=True):
"""根据微信文章的临时链接获取明细
1. 获取文本中所有的图片链接列表
2. 获取微信文章的html内容页面(去除标题等信息)
Parameters
----------
text : str or unicode
一篇微信文章的文本
del_qqmusic: bool
删除文章中的qq音乐
del_voice: bool
删除文章中的语音内容
Returns
-------
dict
{
'content_html': str # 微信文本内容
'content_img_list': list[img_url1, img_url2, ...] # 微信文本中图片列表
}
"""
# 1. 获取微信文本content
html_obj = BeautifulSoup(text, "lxml")
content_text = html_obj.find('div', {'class': 'rich_media_content', 'id': 'js_content'})
# 2. 删除部分标签
if del_qqmusic:
qqmusic = content_text.find_all('qqmusic') or []
for music in qqmusic:
music.parent.decompose()
if del_voice:
# voice是一个p标签下的mpvoice标签以及class为'js_audio_frame db'的span构成,所以将父标签删除
voices = content_text.find_all('mpvoice') or []
for voice in voices:
voice.parent.decompose()
# 3. 获取所有的图片 [img标签,和style中的background-image]
all_img_set = set()
all_img_element = content_text.find_all('img') or []
for ele in all_img_element:
# 删除部分属性
img_url = format_image_url(ele.attrs['data-src'])
del ele.attrs['data-src']
ele.attrs['src'] = img_url
if not img_url.startswith('http'):
raise WechatSogouException('img_url [{}] 不合法'.format(img_url))
all_img_set.add(img_url)
backgroud_image = content_text.find_all(style=re.compile("background-image")) or []
for ele in backgroud_image:
# 删除部分属性
if ele.attrs.get('data-src'):
del ele.attrs['data-src']
if ele.attrs.get('data-wxurl'):
del ele.attrs['data-wxurl']
img_url = re.findall(backgroud_image_p, str(ele))
if not img_url:
continue
all_img_set.add(img_url[0])
# 4. 处理iframe
all_img_element = content_text.find_all('iframe') or []
for ele in all_img_element:
# 删除部分属性
img_url = ele.attrs['data-src']
del ele.attrs['data-src']
ele.attrs['src'] = img_url
# 5. 返回数据
all_img_list = list(all_img_set)
content_html = content_text.prettify()
# 去除div[id=js_content]
content_html = re.findall(js_content, content_html)[0][0]
return {
'content_html': content_html,
'content_img_list': all_img_list
}
|
Chyroc/WechatSogou | wechatsogou/structuring.py | WechatSogouStructuring.get_article_by_history_json | python | def get_article_by_history_json(text, article_json=None):
if article_json is None:
article_json = find_article_json_re.findall(text)
if not article_json:
return []
article_json = article_json[0] + '}}]}'
article_json = json.loads(article_json)
items = list()
for listdic in article_json['list']:
if str(listdic['comm_msg_info'].get('type', '')) != '49':
continue
comm_msg_info = listdic['comm_msg_info']
app_msg_ext_info = listdic['app_msg_ext_info']
send_id = comm_msg_info.get('id', '')
msg_datetime = comm_msg_info.get('datetime', '')
msg_type = str(comm_msg_info.get('type', ''))
items.append({
'send_id': send_id,
'datetime': msg_datetime,
'type': msg_type,
'main': 1, 'title': app_msg_ext_info.get('title', ''),
'abstract': app_msg_ext_info.get('digest', ''),
'fileid': app_msg_ext_info.get('fileid', ''),
'content_url': WechatSogouStructuring.__handle_content_url(app_msg_ext_info.get('content_url')),
'source_url': app_msg_ext_info.get('source_url', ''),
'cover': app_msg_ext_info.get('cover', ''),
'author': app_msg_ext_info.get('author', ''),
'copyright_stat': app_msg_ext_info.get('copyright_stat', '')
})
if app_msg_ext_info.get('is_multi', 0) == 1:
for multi_dict in app_msg_ext_info['multi_app_msg_item_list']:
items.append({
'send_id': send_id,
'datetime': msg_datetime,
'type': msg_type,
'main': 0, 'title': multi_dict.get('title', ''),
'abstract': multi_dict.get('digest', ''),
'fileid': multi_dict.get('fileid', ''),
'content_url': WechatSogouStructuring.__handle_content_url(multi_dict.get('content_url')),
'source_url': multi_dict.get('source_url', ''),
'cover': multi_dict.get('cover', ''),
'author': multi_dict.get('author', ''),
'copyright_stat': multi_dict.get('copyright_stat', '')
})
return list(filter(lambda x: x['content_url'], items)) | 从 历史消息页的文本 提取文章列表信息
Parameters
----------
text : str or unicode
历史消息页的文本
article_json : dict
历史消息页的文本 提取出来的文章json dict
Returns
-------
list[dict]
{
'send_id': '', # 群发id,注意不唯一,因为同一次群发多个消息,而群发id一致
'datetime': '', # 群发datatime
'type': '', # 消息类型,均是49,表示图文
'main': 0, # 是否是一次群发的第一次消息
'title': '', # 文章标题
'abstract': '', # 摘要
'fileid': '', #
'content_url': '', # 文章链接
'source_url': '', # 阅读原文的链接
'cover': '', # 封面图
'author': '', # 作者
'copyright_stat': '', # 文章类型,例如:原创啊
} | train | https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/structuring.py#L256-L334 | null | class WechatSogouStructuring(object):
@staticmethod
def __handle_content_url(content_url):
content_url = replace_html(content_url)
return ('http://mp.weixin.qq.com{}'.format(
content_url) if 'http://mp.weixin.qq.com' not in content_url else content_url) if content_url else ''
@staticmethod
def __get_post_view_perm(text):
result = get_post_view_perm.findall(text)
if not result or len(result) < 1 or not result[0]:
return None
r = requests.get('http://weixin.sogou.com{}'.format(result[0]))
if not r.ok:
return None
if r.json().get('code') != 'success':
return None
return r.json().get('msg')
@staticmethod
def get_gzh_by_search(text):
"""从搜索公众号获得的文本 提取公众号信息
Parameters
----------
text : str or unicode
搜索公众号获得的文本
Returns
-------
list[dict]
{
'open_id': '', # 微信号唯一ID
'profile_url': '', # 最近10条群发页链接
'headimage': '', # 头像
'wechat_name': '', # 名称
'wechat_id': '', # 微信id
'post_perm': '', # 最近一月群发数
'view_perm': '', # 最近一月阅读量
'qrcode': '', # 二维码
'introduction': '', # 介绍
'authentication': '' # 认证
}
"""
post_view_perms = WechatSogouStructuring.__get_post_view_perm(text)
page = etree.HTML(text)
lis = page.xpath('//ul[@class="news-list2"]/li')
relist = []
for li in lis:
url = get_first_of_element(li, 'div/div[1]/a/@href')
headimage = format_image_url(get_first_of_element(li, 'div/div[1]/a/img/@src'))
wechat_name = get_elem_text(get_first_of_element(li, 'div/div[2]/p[1]'))
info = get_elem_text(get_first_of_element(li, 'div/div[2]/p[2]'))
qrcode = get_first_of_element(li, 'div/div[3]/span/img[1]/@src')
introduction = get_elem_text(get_first_of_element(li, 'dl[1]/dd'))
authentication = get_first_of_element(li, 'dl[2]/dd/text()')
relist.append({
'open_id': headimage.split('/')[-1],
'profile_url': url,
'headimage': headimage,
'wechat_name': wechat_name.replace('red_beg', '').replace('red_end', ''),
'wechat_id': info.replace('微信号:', ''),
'qrcode': qrcode,
'introduction': introduction.replace('red_beg', '').replace('red_end', ''),
'authentication': authentication,
'post_perm': -1,
'view_perm': -1,
})
if post_view_perms:
for i in relist:
if i['open_id'] in post_view_perms:
post_view_perm = post_view_perms[i['open_id']].split(',')
if len(post_view_perm) == 2:
i['post_perm'] = int(post_view_perm[0])
i['view_perm'] = int(post_view_perm[1])
return relist
@staticmethod
def get_article_by_search_wap(keyword, wap_dict):
datas = []
for i in wap_dict['items']:
item = str_to_bytes(i).replace(b'\xee\x90\x8a' + str_to_bytes(keyword) + b'\xee\x90\x8b',
str_to_bytes(keyword))
root = XML(item)
display = root.find('.//display')
datas.append({
'gzh': {
'profile_url': display.find('encGzhUrl').text,
'open_id': display.find('openid').text,
'isv': display.find('isV').text,
'wechat_name': display.find('sourcename').text,
'wechat_id': display.find('username').text,
'headimage': display.find('headimage').text,
'qrcode': display.find('encQrcodeUrl').text,
},
'article': {
'title': display.find('title').text,
'url': display.find('url').text, # encArticleUrl
'main_img': display.find('imglink').text,
'abstract': display.find('content168').text,
'time': display.find('lastModified').text,
},
})
return datas
@staticmethod
def get_article_by_search(text):
"""从搜索文章获得的文本 提取章列表信息
Parameters
----------
text : str or unicode
搜索文章获得的文本
Returns
-------
list[dict]
{
'article': {
'title': '', # 文章标题
'url': '', # 文章链接
'imgs': '', # 文章图片list
'abstract': '', # 文章摘要
'time': '' # 文章推送时间
},
'gzh': {
'profile_url': '', # 公众号最近10条群发页链接
'headimage': '', # 头像
'wechat_name': '', # 名称
'isv': '', # 是否加v
}
}
"""
page = etree.HTML(text)
lis = page.xpath('//ul[@class="news-list"]/li')
articles = []
for li in lis:
url = get_first_of_element(li, 'div[1]/a/@href')
if url:
title = get_first_of_element(li, 'div[2]/h3/a')
imgs = li.xpath('div[1]/a/img/@src')
abstract = get_first_of_element(li, 'div[2]/p')
time = get_first_of_element(li, 'div[2]/div/span/script/text()')
gzh_info = li.xpath('div[2]/div/a')[0]
else:
url = get_first_of_element(li, 'div/h3/a/@href')
title = get_first_of_element(li, 'div/h3/a')
imgs = []
spans = li.xpath('div/div[1]/a')
for span in spans:
img = span.xpath('span/img/@src')
if img:
imgs.append(img)
abstract = get_first_of_element(li, 'div/p')
time = get_first_of_element(li, 'div/div[2]/span/script/text()')
gzh_info = li.xpath('div/div[2]/a')[0]
if title is not None:
title = get_elem_text(title).replace("red_beg", "").replace("red_end", "")
if abstract is not None:
abstract = get_elem_text(abstract).replace("red_beg", "").replace("red_end", "")
time = re.findall('timeConvert\(\'(.*?)\'\)', time)
time = list_or_empty(time, int)
profile_url = get_first_of_element(gzh_info, '@href')
headimage = get_first_of_element(gzh_info, '@data-headimage')
wechat_name = get_first_of_element(gzh_info, 'text()')
gzh_isv = get_first_of_element(gzh_info, '@data-isv', int)
articles.append({
'article': {
'title': title,
'url': url,
'imgs': format_image_url(imgs),
'abstract': abstract,
'time': time
},
'gzh': {
'profile_url': profile_url,
'headimage': headimage,
'wechat_name': wechat_name,
'isv': gzh_isv,
}
})
return articles
@staticmethod
def get_gzh_info_by_history(text):
"""从 历史消息页的文本 提取公众号信息
Parameters
----------
text : str or unicode
历史消息页的文本
Returns
-------
dict
{
'wechat_name': '', # 名称
'wechat_id': '', # 微信id
'introduction': '', # 描述
'authentication': '', # 认证
'headimage': '' # 头像
}
"""
page = etree.HTML(text)
profile_area = get_first_of_element(page, '//div[@class="profile_info_area"]')
profile_img = get_first_of_element(profile_area, 'div[1]/span/img/@src')
profile_name = get_first_of_element(profile_area, 'div[1]/div/strong/text()')
profile_wechat_id = get_first_of_element(profile_area, 'div[1]/div/p/text()')
profile_desc = get_first_of_element(profile_area, 'ul/li[1]/div/text()')
profile_principal = get_first_of_element(profile_area, 'ul/li[2]/div/text()')
return {
'wechat_name': profile_name.strip(),
'wechat_id': profile_wechat_id.replace('微信号: ', '').strip('\n'),
'introduction': profile_desc,
'authentication': profile_principal,
'headimage': profile_img
}
@staticmethod
# 删除搜狗本身携带的空数据
@staticmethod
def get_gzh_info_and_article_by_history(text):
"""从 历史消息页的文本 提取公众号信息 和 文章列表信息
Parameters
----------
text : str or unicode
历史消息页的文本
Returns
-------
dict
{
'gzh': {
'wechat_name': '', # 名称
'wechat_id': '', # 微信id
'introduction': '', # 描述
'authentication': '', # 认证
'headimage': '' # 头像
},
'article': [
{
'send_id': '', # 群发id,注意不唯一,因为同一次群发多个消息,而群发id一致
'datetime': '', # 群发datatime
'type': '', # 消息类型,均是49,表示图文
'main': 0, # 是否是一次群发的第一次消息
'title': '', # 文章标题
'abstract': '', # 摘要
'fileid': '', #
'content_url': '', # 文章链接
'source_url': '', # 阅读原文的链接
'cover': '', # 封面图
'author': '', # 作者
'copyright_stat': '', # 文章类型,例如:原创啊
},
...
]
}
"""
return {
'gzh': WechatSogouStructuring.get_gzh_info_by_history(text),
'article': WechatSogouStructuring.get_article_by_history_json(text)
}
@staticmethod
def get_gzh_article_by_hot(text):
"""从 首页热门搜索 提取公众号信息 和 文章列表信息
Parameters
----------
text : str or unicode
首页热门搜索 页 中 某一页 的文本
Returns
-------
list[dict]
{
'gzh': {
'headimage': str, # 公众号头像
'wechat_name': str, # 公众号名称
},
'article': {
'url': str, # 文章临时链接
'title': str, # 文章标题
'abstract': str, # 文章摘要
'time': int, # 推送时间,10位时间戳
'open_id': str, # open id
'main_img': str # 封面图片
}
}
"""
page = etree.HTML(text)
lis = page.xpath('/html/body/li')
gzh_article_list = []
for li in lis:
url = get_first_of_element(li, 'div[1]/h4/a/@href')
title = get_first_of_element(li, 'div[1]/h4/a/div/text()')
abstract = get_first_of_element(li, 'div[1]/p[1]/text()')
xpath_time = get_first_of_element(li, 'div[1]/p[2]')
open_id = get_first_of_element(xpath_time, 'span/@data-openid')
headimage = get_first_of_element(xpath_time, 'span/@data-headimage')
gzh_name = get_first_of_element(xpath_time, 'span/text()')
send_time = xpath_time.xpath('a/span/@data-lastmodified')
main_img = get_first_of_element(li, 'div[2]/a/img/@src')
try:
send_time = int(send_time[0])
except ValueError:
send_time = send_time[0]
gzh_article_list.append({
'gzh': {
'headimage': headimage,
'wechat_name': gzh_name,
},
'article': {
'url': url,
'title': title,
'abstract': abstract,
'time': send_time,
'open_id': open_id,
'main_img': main_img
}
})
return gzh_article_list
@staticmethod
def get_article_detail(text, del_qqmusic=True, del_voice=True):
"""根据微信文章的临时链接获取明细
1. 获取文本中所有的图片链接列表
2. 获取微信文章的html内容页面(去除标题等信息)
Parameters
----------
text : str or unicode
一篇微信文章的文本
del_qqmusic: bool
删除文章中的qq音乐
del_voice: bool
删除文章中的语音内容
Returns
-------
dict
{
'content_html': str # 微信文本内容
'content_img_list': list[img_url1, img_url2, ...] # 微信文本中图片列表
}
"""
# 1. 获取微信文本content
html_obj = BeautifulSoup(text, "lxml")
content_text = html_obj.find('div', {'class': 'rich_media_content', 'id': 'js_content'})
# 2. 删除部分标签
if del_qqmusic:
qqmusic = content_text.find_all('qqmusic') or []
for music in qqmusic:
music.parent.decompose()
if del_voice:
# voice是一个p标签下的mpvoice标签以及class为'js_audio_frame db'的span构成,所以将父标签删除
voices = content_text.find_all('mpvoice') or []
for voice in voices:
voice.parent.decompose()
# 3. 获取所有的图片 [img标签,和style中的background-image]
all_img_set = set()
all_img_element = content_text.find_all('img') or []
for ele in all_img_element:
# 删除部分属性
img_url = format_image_url(ele.attrs['data-src'])
del ele.attrs['data-src']
ele.attrs['src'] = img_url
if not img_url.startswith('http'):
raise WechatSogouException('img_url [{}] 不合法'.format(img_url))
all_img_set.add(img_url)
backgroud_image = content_text.find_all(style=re.compile("background-image")) or []
for ele in backgroud_image:
# 删除部分属性
if ele.attrs.get('data-src'):
del ele.attrs['data-src']
if ele.attrs.get('data-wxurl'):
del ele.attrs['data-wxurl']
img_url = re.findall(backgroud_image_p, str(ele))
if not img_url:
continue
all_img_set.add(img_url[0])
# 4. 处理iframe
all_img_element = content_text.find_all('iframe') or []
for ele in all_img_element:
# 删除部分属性
img_url = ele.attrs['data-src']
del ele.attrs['data-src']
ele.attrs['src'] = img_url
# 5. 返回数据
all_img_list = list(all_img_set)
content_html = content_text.prettify()
# 去除div[id=js_content]
content_html = re.findall(js_content, content_html)[0][0]
return {
'content_html': content_html,
'content_img_list': all_img_list
}
|
Chyroc/WechatSogou | wechatsogou/structuring.py | WechatSogouStructuring.get_gzh_article_by_hot | python | def get_gzh_article_by_hot(text):
page = etree.HTML(text)
lis = page.xpath('/html/body/li')
gzh_article_list = []
for li in lis:
url = get_first_of_element(li, 'div[1]/h4/a/@href')
title = get_first_of_element(li, 'div[1]/h4/a/div/text()')
abstract = get_first_of_element(li, 'div[1]/p[1]/text()')
xpath_time = get_first_of_element(li, 'div[1]/p[2]')
open_id = get_first_of_element(xpath_time, 'span/@data-openid')
headimage = get_first_of_element(xpath_time, 'span/@data-headimage')
gzh_name = get_first_of_element(xpath_time, 'span/text()')
send_time = xpath_time.xpath('a/span/@data-lastmodified')
main_img = get_first_of_element(li, 'div[2]/a/img/@src')
try:
send_time = int(send_time[0])
except ValueError:
send_time = send_time[0]
gzh_article_list.append({
'gzh': {
'headimage': headimage,
'wechat_name': gzh_name,
},
'article': {
'url': url,
'title': title,
'abstract': abstract,
'time': send_time,
'open_id': open_id,
'main_img': main_img
}
})
return gzh_article_list | 从 首页热门搜索 提取公众号信息 和 文章列表信息
Parameters
----------
text : str or unicode
首页热门搜索 页 中 某一页 的文本
Returns
-------
list[dict]
{
'gzh': {
'headimage': str, # 公众号头像
'wechat_name': str, # 公众号名称
},
'article': {
'url': str, # 文章临时链接
'title': str, # 文章标题
'abstract': str, # 文章摘要
'time': int, # 推送时间,10位时间戳
'open_id': str, # open id
'main_img': str # 封面图片
}
} | train | https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/structuring.py#L381-L441 | [
"def get_first_of_element(element, sub, contype=None):\n \"\"\"抽取lxml.etree库中elem对象中文字\n\n Args:\n element: lxml.etree.Element\n sub: str\n\n Returns:\n elem中文字\n \"\"\"\n content = element.xpath(sub)\n return list_or_empty(content, contype)\n"
] | class WechatSogouStructuring(object):
@staticmethod
def __handle_content_url(content_url):
content_url = replace_html(content_url)
return ('http://mp.weixin.qq.com{}'.format(
content_url) if 'http://mp.weixin.qq.com' not in content_url else content_url) if content_url else ''
@staticmethod
def __get_post_view_perm(text):
result = get_post_view_perm.findall(text)
if not result or len(result) < 1 or not result[0]:
return None
r = requests.get('http://weixin.sogou.com{}'.format(result[0]))
if not r.ok:
return None
if r.json().get('code') != 'success':
return None
return r.json().get('msg')
@staticmethod
def get_gzh_by_search(text):
"""从搜索公众号获得的文本 提取公众号信息
Parameters
----------
text : str or unicode
搜索公众号获得的文本
Returns
-------
list[dict]
{
'open_id': '', # 微信号唯一ID
'profile_url': '', # 最近10条群发页链接
'headimage': '', # 头像
'wechat_name': '', # 名称
'wechat_id': '', # 微信id
'post_perm': '', # 最近一月群发数
'view_perm': '', # 最近一月阅读量
'qrcode': '', # 二维码
'introduction': '', # 介绍
'authentication': '' # 认证
}
"""
post_view_perms = WechatSogouStructuring.__get_post_view_perm(text)
page = etree.HTML(text)
lis = page.xpath('//ul[@class="news-list2"]/li')
relist = []
for li in lis:
url = get_first_of_element(li, 'div/div[1]/a/@href')
headimage = format_image_url(get_first_of_element(li, 'div/div[1]/a/img/@src'))
wechat_name = get_elem_text(get_first_of_element(li, 'div/div[2]/p[1]'))
info = get_elem_text(get_first_of_element(li, 'div/div[2]/p[2]'))
qrcode = get_first_of_element(li, 'div/div[3]/span/img[1]/@src')
introduction = get_elem_text(get_first_of_element(li, 'dl[1]/dd'))
authentication = get_first_of_element(li, 'dl[2]/dd/text()')
relist.append({
'open_id': headimage.split('/')[-1],
'profile_url': url,
'headimage': headimage,
'wechat_name': wechat_name.replace('red_beg', '').replace('red_end', ''),
'wechat_id': info.replace('微信号:', ''),
'qrcode': qrcode,
'introduction': introduction.replace('red_beg', '').replace('red_end', ''),
'authentication': authentication,
'post_perm': -1,
'view_perm': -1,
})
if post_view_perms:
for i in relist:
if i['open_id'] in post_view_perms:
post_view_perm = post_view_perms[i['open_id']].split(',')
if len(post_view_perm) == 2:
i['post_perm'] = int(post_view_perm[0])
i['view_perm'] = int(post_view_perm[1])
return relist
@staticmethod
def get_article_by_search_wap(keyword, wap_dict):
datas = []
for i in wap_dict['items']:
item = str_to_bytes(i).replace(b'\xee\x90\x8a' + str_to_bytes(keyword) + b'\xee\x90\x8b',
str_to_bytes(keyword))
root = XML(item)
display = root.find('.//display')
datas.append({
'gzh': {
'profile_url': display.find('encGzhUrl').text,
'open_id': display.find('openid').text,
'isv': display.find('isV').text,
'wechat_name': display.find('sourcename').text,
'wechat_id': display.find('username').text,
'headimage': display.find('headimage').text,
'qrcode': display.find('encQrcodeUrl').text,
},
'article': {
'title': display.find('title').text,
'url': display.find('url').text, # encArticleUrl
'main_img': display.find('imglink').text,
'abstract': display.find('content168').text,
'time': display.find('lastModified').text,
},
})
return datas
@staticmethod
def get_article_by_search(text):
"""从搜索文章获得的文本 提取章列表信息
Parameters
----------
text : str or unicode
搜索文章获得的文本
Returns
-------
list[dict]
{
'article': {
'title': '', # 文章标题
'url': '', # 文章链接
'imgs': '', # 文章图片list
'abstract': '', # 文章摘要
'time': '' # 文章推送时间
},
'gzh': {
'profile_url': '', # 公众号最近10条群发页链接
'headimage': '', # 头像
'wechat_name': '', # 名称
'isv': '', # 是否加v
}
}
"""
page = etree.HTML(text)
lis = page.xpath('//ul[@class="news-list"]/li')
articles = []
for li in lis:
url = get_first_of_element(li, 'div[1]/a/@href')
if url:
title = get_first_of_element(li, 'div[2]/h3/a')
imgs = li.xpath('div[1]/a/img/@src')
abstract = get_first_of_element(li, 'div[2]/p')
time = get_first_of_element(li, 'div[2]/div/span/script/text()')
gzh_info = li.xpath('div[2]/div/a')[0]
else:
url = get_first_of_element(li, 'div/h3/a/@href')
title = get_first_of_element(li, 'div/h3/a')
imgs = []
spans = li.xpath('div/div[1]/a')
for span in spans:
img = span.xpath('span/img/@src')
if img:
imgs.append(img)
abstract = get_first_of_element(li, 'div/p')
time = get_first_of_element(li, 'div/div[2]/span/script/text()')
gzh_info = li.xpath('div/div[2]/a')[0]
if title is not None:
title = get_elem_text(title).replace("red_beg", "").replace("red_end", "")
if abstract is not None:
abstract = get_elem_text(abstract).replace("red_beg", "").replace("red_end", "")
time = re.findall('timeConvert\(\'(.*?)\'\)', time)
time = list_or_empty(time, int)
profile_url = get_first_of_element(gzh_info, '@href')
headimage = get_first_of_element(gzh_info, '@data-headimage')
wechat_name = get_first_of_element(gzh_info, 'text()')
gzh_isv = get_first_of_element(gzh_info, '@data-isv', int)
articles.append({
'article': {
'title': title,
'url': url,
'imgs': format_image_url(imgs),
'abstract': abstract,
'time': time
},
'gzh': {
'profile_url': profile_url,
'headimage': headimage,
'wechat_name': wechat_name,
'isv': gzh_isv,
}
})
return articles
@staticmethod
def get_gzh_info_by_history(text):
"""从 历史消息页的文本 提取公众号信息
Parameters
----------
text : str or unicode
历史消息页的文本
Returns
-------
dict
{
'wechat_name': '', # 名称
'wechat_id': '', # 微信id
'introduction': '', # 描述
'authentication': '', # 认证
'headimage': '' # 头像
}
"""
page = etree.HTML(text)
profile_area = get_first_of_element(page, '//div[@class="profile_info_area"]')
profile_img = get_first_of_element(profile_area, 'div[1]/span/img/@src')
profile_name = get_first_of_element(profile_area, 'div[1]/div/strong/text()')
profile_wechat_id = get_first_of_element(profile_area, 'div[1]/div/p/text()')
profile_desc = get_first_of_element(profile_area, 'ul/li[1]/div/text()')
profile_principal = get_first_of_element(profile_area, 'ul/li[2]/div/text()')
return {
'wechat_name': profile_name.strip(),
'wechat_id': profile_wechat_id.replace('微信号: ', '').strip('\n'),
'introduction': profile_desc,
'authentication': profile_principal,
'headimage': profile_img
}
@staticmethod
def get_article_by_history_json(text, article_json=None):
"""从 历史消息页的文本 提取文章列表信息
Parameters
----------
text : str or unicode
历史消息页的文本
article_json : dict
历史消息页的文本 提取出来的文章json dict
Returns
-------
list[dict]
{
'send_id': '', # 群发id,注意不唯一,因为同一次群发多个消息,而群发id一致
'datetime': '', # 群发datatime
'type': '', # 消息类型,均是49,表示图文
'main': 0, # 是否是一次群发的第一次消息
'title': '', # 文章标题
'abstract': '', # 摘要
'fileid': '', #
'content_url': '', # 文章链接
'source_url': '', # 阅读原文的链接
'cover': '', # 封面图
'author': '', # 作者
'copyright_stat': '', # 文章类型,例如:原创啊
}
"""
if article_json is None:
article_json = find_article_json_re.findall(text)
if not article_json:
return []
article_json = article_json[0] + '}}]}'
article_json = json.loads(article_json)
items = list()
for listdic in article_json['list']:
if str(listdic['comm_msg_info'].get('type', '')) != '49':
continue
comm_msg_info = listdic['comm_msg_info']
app_msg_ext_info = listdic['app_msg_ext_info']
send_id = comm_msg_info.get('id', '')
msg_datetime = comm_msg_info.get('datetime', '')
msg_type = str(comm_msg_info.get('type', ''))
items.append({
'send_id': send_id,
'datetime': msg_datetime,
'type': msg_type,
'main': 1, 'title': app_msg_ext_info.get('title', ''),
'abstract': app_msg_ext_info.get('digest', ''),
'fileid': app_msg_ext_info.get('fileid', ''),
'content_url': WechatSogouStructuring.__handle_content_url(app_msg_ext_info.get('content_url')),
'source_url': app_msg_ext_info.get('source_url', ''),
'cover': app_msg_ext_info.get('cover', ''),
'author': app_msg_ext_info.get('author', ''),
'copyright_stat': app_msg_ext_info.get('copyright_stat', '')
})
if app_msg_ext_info.get('is_multi', 0) == 1:
for multi_dict in app_msg_ext_info['multi_app_msg_item_list']:
items.append({
'send_id': send_id,
'datetime': msg_datetime,
'type': msg_type,
'main': 0, 'title': multi_dict.get('title', ''),
'abstract': multi_dict.get('digest', ''),
'fileid': multi_dict.get('fileid', ''),
'content_url': WechatSogouStructuring.__handle_content_url(multi_dict.get('content_url')),
'source_url': multi_dict.get('source_url', ''),
'cover': multi_dict.get('cover', ''),
'author': multi_dict.get('author', ''),
'copyright_stat': multi_dict.get('copyright_stat', '')
})
return list(filter(lambda x: x['content_url'], items)) # 删除搜狗本身携带的空数据
@staticmethod
def get_gzh_info_and_article_by_history(text):
"""从 历史消息页的文本 提取公众号信息 和 文章列表信息
Parameters
----------
text : str or unicode
历史消息页的文本
Returns
-------
dict
{
'gzh': {
'wechat_name': '', # 名称
'wechat_id': '', # 微信id
'introduction': '', # 描述
'authentication': '', # 认证
'headimage': '' # 头像
},
'article': [
{
'send_id': '', # 群发id,注意不唯一,因为同一次群发多个消息,而群发id一致
'datetime': '', # 群发datatime
'type': '', # 消息类型,均是49,表示图文
'main': 0, # 是否是一次群发的第一次消息
'title': '', # 文章标题
'abstract': '', # 摘要
'fileid': '', #
'content_url': '', # 文章链接
'source_url': '', # 阅读原文的链接
'cover': '', # 封面图
'author': '', # 作者
'copyright_stat': '', # 文章类型,例如:原创啊
},
...
]
}
"""
return {
'gzh': WechatSogouStructuring.get_gzh_info_by_history(text),
'article': WechatSogouStructuring.get_article_by_history_json(text)
}
@staticmethod
@staticmethod
def get_article_detail(text, del_qqmusic=True, del_voice=True):
"""根据微信文章的临时链接获取明细
1. 获取文本中所有的图片链接列表
2. 获取微信文章的html内容页面(去除标题等信息)
Parameters
----------
text : str or unicode
一篇微信文章的文本
del_qqmusic: bool
删除文章中的qq音乐
del_voice: bool
删除文章中的语音内容
Returns
-------
dict
{
'content_html': str # 微信文本内容
'content_img_list': list[img_url1, img_url2, ...] # 微信文本中图片列表
}
"""
# 1. 获取微信文本content
html_obj = BeautifulSoup(text, "lxml")
content_text = html_obj.find('div', {'class': 'rich_media_content', 'id': 'js_content'})
# 2. 删除部分标签
if del_qqmusic:
qqmusic = content_text.find_all('qqmusic') or []
for music in qqmusic:
music.parent.decompose()
if del_voice:
# voice是一个p标签下的mpvoice标签以及class为'js_audio_frame db'的span构成,所以将父标签删除
voices = content_text.find_all('mpvoice') or []
for voice in voices:
voice.parent.decompose()
# 3. 获取所有的图片 [img标签,和style中的background-image]
all_img_set = set()
all_img_element = content_text.find_all('img') or []
for ele in all_img_element:
# 删除部分属性
img_url = format_image_url(ele.attrs['data-src'])
del ele.attrs['data-src']
ele.attrs['src'] = img_url
if not img_url.startswith('http'):
raise WechatSogouException('img_url [{}] 不合法'.format(img_url))
all_img_set.add(img_url)
backgroud_image = content_text.find_all(style=re.compile("background-image")) or []
for ele in backgroud_image:
# 删除部分属性
if ele.attrs.get('data-src'):
del ele.attrs['data-src']
if ele.attrs.get('data-wxurl'):
del ele.attrs['data-wxurl']
img_url = re.findall(backgroud_image_p, str(ele))
if not img_url:
continue
all_img_set.add(img_url[0])
# 4. 处理iframe
all_img_element = content_text.find_all('iframe') or []
for ele in all_img_element:
# 删除部分属性
img_url = ele.attrs['data-src']
del ele.attrs['data-src']
ele.attrs['src'] = img_url
# 5. 返回数据
all_img_list = list(all_img_set)
content_html = content_text.prettify()
# 去除div[id=js_content]
content_html = re.findall(js_content, content_html)[0][0]
return {
'content_html': content_html,
'content_img_list': all_img_list
}
|
Chyroc/WechatSogou | wechatsogou/structuring.py | WechatSogouStructuring.get_article_detail | python | def get_article_detail(text, del_qqmusic=True, del_voice=True):
# 1. 获取微信文本content
html_obj = BeautifulSoup(text, "lxml")
content_text = html_obj.find('div', {'class': 'rich_media_content', 'id': 'js_content'})
# 2. 删除部分标签
if del_qqmusic:
qqmusic = content_text.find_all('qqmusic') or []
for music in qqmusic:
music.parent.decompose()
if del_voice:
# voice是一个p标签下的mpvoice标签以及class为'js_audio_frame db'的span构成,所以将父标签删除
voices = content_text.find_all('mpvoice') or []
for voice in voices:
voice.parent.decompose()
# 3. 获取所有的图片 [img标签,和style中的background-image]
all_img_set = set()
all_img_element = content_text.find_all('img') or []
for ele in all_img_element:
# 删除部分属性
img_url = format_image_url(ele.attrs['data-src'])
del ele.attrs['data-src']
ele.attrs['src'] = img_url
if not img_url.startswith('http'):
raise WechatSogouException('img_url [{}] 不合法'.format(img_url))
all_img_set.add(img_url)
backgroud_image = content_text.find_all(style=re.compile("background-image")) or []
for ele in backgroud_image:
# 删除部分属性
if ele.attrs.get('data-src'):
del ele.attrs['data-src']
if ele.attrs.get('data-wxurl'):
del ele.attrs['data-wxurl']
img_url = re.findall(backgroud_image_p, str(ele))
if not img_url:
continue
all_img_set.add(img_url[0])
# 4. 处理iframe
all_img_element = content_text.find_all('iframe') or []
for ele in all_img_element:
# 删除部分属性
img_url = ele.attrs['data-src']
del ele.attrs['data-src']
ele.attrs['src'] = img_url
# 5. 返回数据
all_img_list = list(all_img_set)
content_html = content_text.prettify()
# 去除div[id=js_content]
content_html = re.findall(js_content, content_html)[0][0]
return {
'content_html': content_html,
'content_img_list': all_img_list
} | 根据微信文章的临时链接获取明细
1. 获取文本中所有的图片链接列表
2. 获取微信文章的html内容页面(去除标题等信息)
Parameters
----------
text : str or unicode
一篇微信文章的文本
del_qqmusic: bool
删除文章中的qq音乐
del_voice: bool
删除文章中的语音内容
Returns
-------
dict
{
'content_html': str # 微信文本内容
'content_img_list': list[img_url1, img_url2, ...] # 微信文本中图片列表
} | train | https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/structuring.py#L444-L527 | [
"def format_image_url(url):\n if isinstance(url, list):\n return [format_image_url(i) for i in url]\n\n if url.startswith('//'):\n url = 'https:{}'.format(url)\n return url\n"
] | class WechatSogouStructuring(object):
@staticmethod
def __handle_content_url(content_url):
content_url = replace_html(content_url)
return ('http://mp.weixin.qq.com{}'.format(
content_url) if 'http://mp.weixin.qq.com' not in content_url else content_url) if content_url else ''
@staticmethod
def __get_post_view_perm(text):
result = get_post_view_perm.findall(text)
if not result or len(result) < 1 or not result[0]:
return None
r = requests.get('http://weixin.sogou.com{}'.format(result[0]))
if not r.ok:
return None
if r.json().get('code') != 'success':
return None
return r.json().get('msg')
@staticmethod
def get_gzh_by_search(text):
"""从搜索公众号获得的文本 提取公众号信息
Parameters
----------
text : str or unicode
搜索公众号获得的文本
Returns
-------
list[dict]
{
'open_id': '', # 微信号唯一ID
'profile_url': '', # 最近10条群发页链接
'headimage': '', # 头像
'wechat_name': '', # 名称
'wechat_id': '', # 微信id
'post_perm': '', # 最近一月群发数
'view_perm': '', # 最近一月阅读量
'qrcode': '', # 二维码
'introduction': '', # 介绍
'authentication': '' # 认证
}
"""
post_view_perms = WechatSogouStructuring.__get_post_view_perm(text)
page = etree.HTML(text)
lis = page.xpath('//ul[@class="news-list2"]/li')
relist = []
for li in lis:
url = get_first_of_element(li, 'div/div[1]/a/@href')
headimage = format_image_url(get_first_of_element(li, 'div/div[1]/a/img/@src'))
wechat_name = get_elem_text(get_first_of_element(li, 'div/div[2]/p[1]'))
info = get_elem_text(get_first_of_element(li, 'div/div[2]/p[2]'))
qrcode = get_first_of_element(li, 'div/div[3]/span/img[1]/@src')
introduction = get_elem_text(get_first_of_element(li, 'dl[1]/dd'))
authentication = get_first_of_element(li, 'dl[2]/dd/text()')
relist.append({
'open_id': headimage.split('/')[-1],
'profile_url': url,
'headimage': headimage,
'wechat_name': wechat_name.replace('red_beg', '').replace('red_end', ''),
'wechat_id': info.replace('微信号:', ''),
'qrcode': qrcode,
'introduction': introduction.replace('red_beg', '').replace('red_end', ''),
'authentication': authentication,
'post_perm': -1,
'view_perm': -1,
})
if post_view_perms:
for i in relist:
if i['open_id'] in post_view_perms:
post_view_perm = post_view_perms[i['open_id']].split(',')
if len(post_view_perm) == 2:
i['post_perm'] = int(post_view_perm[0])
i['view_perm'] = int(post_view_perm[1])
return relist
@staticmethod
def get_article_by_search_wap(keyword, wap_dict):
datas = []
for i in wap_dict['items']:
item = str_to_bytes(i).replace(b'\xee\x90\x8a' + str_to_bytes(keyword) + b'\xee\x90\x8b',
str_to_bytes(keyword))
root = XML(item)
display = root.find('.//display')
datas.append({
'gzh': {
'profile_url': display.find('encGzhUrl').text,
'open_id': display.find('openid').text,
'isv': display.find('isV').text,
'wechat_name': display.find('sourcename').text,
'wechat_id': display.find('username').text,
'headimage': display.find('headimage').text,
'qrcode': display.find('encQrcodeUrl').text,
},
'article': {
'title': display.find('title').text,
'url': display.find('url').text, # encArticleUrl
'main_img': display.find('imglink').text,
'abstract': display.find('content168').text,
'time': display.find('lastModified').text,
},
})
return datas
@staticmethod
def get_article_by_search(text):
"""从搜索文章获得的文本 提取章列表信息
Parameters
----------
text : str or unicode
搜索文章获得的文本
Returns
-------
list[dict]
{
'article': {
'title': '', # 文章标题
'url': '', # 文章链接
'imgs': '', # 文章图片list
'abstract': '', # 文章摘要
'time': '' # 文章推送时间
},
'gzh': {
'profile_url': '', # 公众号最近10条群发页链接
'headimage': '', # 头像
'wechat_name': '', # 名称
'isv': '', # 是否加v
}
}
"""
page = etree.HTML(text)
lis = page.xpath('//ul[@class="news-list"]/li')
articles = []
for li in lis:
url = get_first_of_element(li, 'div[1]/a/@href')
if url:
title = get_first_of_element(li, 'div[2]/h3/a')
imgs = li.xpath('div[1]/a/img/@src')
abstract = get_first_of_element(li, 'div[2]/p')
time = get_first_of_element(li, 'div[2]/div/span/script/text()')
gzh_info = li.xpath('div[2]/div/a')[0]
else:
url = get_first_of_element(li, 'div/h3/a/@href')
title = get_first_of_element(li, 'div/h3/a')
imgs = []
spans = li.xpath('div/div[1]/a')
for span in spans:
img = span.xpath('span/img/@src')
if img:
imgs.append(img)
abstract = get_first_of_element(li, 'div/p')
time = get_first_of_element(li, 'div/div[2]/span/script/text()')
gzh_info = li.xpath('div/div[2]/a')[0]
if title is not None:
title = get_elem_text(title).replace("red_beg", "").replace("red_end", "")
if abstract is not None:
abstract = get_elem_text(abstract).replace("red_beg", "").replace("red_end", "")
time = re.findall('timeConvert\(\'(.*?)\'\)', time)
time = list_or_empty(time, int)
profile_url = get_first_of_element(gzh_info, '@href')
headimage = get_first_of_element(gzh_info, '@data-headimage')
wechat_name = get_first_of_element(gzh_info, 'text()')
gzh_isv = get_first_of_element(gzh_info, '@data-isv', int)
articles.append({
'article': {
'title': title,
'url': url,
'imgs': format_image_url(imgs),
'abstract': abstract,
'time': time
},
'gzh': {
'profile_url': profile_url,
'headimage': headimage,
'wechat_name': wechat_name,
'isv': gzh_isv,
}
})
return articles
@staticmethod
def get_gzh_info_by_history(text):
"""从 历史消息页的文本 提取公众号信息
Parameters
----------
text : str or unicode
历史消息页的文本
Returns
-------
dict
{
'wechat_name': '', # 名称
'wechat_id': '', # 微信id
'introduction': '', # 描述
'authentication': '', # 认证
'headimage': '' # 头像
}
"""
page = etree.HTML(text)
profile_area = get_first_of_element(page, '//div[@class="profile_info_area"]')
profile_img = get_first_of_element(profile_area, 'div[1]/span/img/@src')
profile_name = get_first_of_element(profile_area, 'div[1]/div/strong/text()')
profile_wechat_id = get_first_of_element(profile_area, 'div[1]/div/p/text()')
profile_desc = get_first_of_element(profile_area, 'ul/li[1]/div/text()')
profile_principal = get_first_of_element(profile_area, 'ul/li[2]/div/text()')
return {
'wechat_name': profile_name.strip(),
'wechat_id': profile_wechat_id.replace('微信号: ', '').strip('\n'),
'introduction': profile_desc,
'authentication': profile_principal,
'headimage': profile_img
}
@staticmethod
def get_article_by_history_json(text, article_json=None):
"""从 历史消息页的文本 提取文章列表信息
Parameters
----------
text : str or unicode
历史消息页的文本
article_json : dict
历史消息页的文本 提取出来的文章json dict
Returns
-------
list[dict]
{
'send_id': '', # 群发id,注意不唯一,因为同一次群发多个消息,而群发id一致
'datetime': '', # 群发datatime
'type': '', # 消息类型,均是49,表示图文
'main': 0, # 是否是一次群发的第一次消息
'title': '', # 文章标题
'abstract': '', # 摘要
'fileid': '', #
'content_url': '', # 文章链接
'source_url': '', # 阅读原文的链接
'cover': '', # 封面图
'author': '', # 作者
'copyright_stat': '', # 文章类型,例如:原创啊
}
"""
if article_json is None:
article_json = find_article_json_re.findall(text)
if not article_json:
return []
article_json = article_json[0] + '}}]}'
article_json = json.loads(article_json)
items = list()
for listdic in article_json['list']:
if str(listdic['comm_msg_info'].get('type', '')) != '49':
continue
comm_msg_info = listdic['comm_msg_info']
app_msg_ext_info = listdic['app_msg_ext_info']
send_id = comm_msg_info.get('id', '')
msg_datetime = comm_msg_info.get('datetime', '')
msg_type = str(comm_msg_info.get('type', ''))
items.append({
'send_id': send_id,
'datetime': msg_datetime,
'type': msg_type,
'main': 1, 'title': app_msg_ext_info.get('title', ''),
'abstract': app_msg_ext_info.get('digest', ''),
'fileid': app_msg_ext_info.get('fileid', ''),
'content_url': WechatSogouStructuring.__handle_content_url(app_msg_ext_info.get('content_url')),
'source_url': app_msg_ext_info.get('source_url', ''),
'cover': app_msg_ext_info.get('cover', ''),
'author': app_msg_ext_info.get('author', ''),
'copyright_stat': app_msg_ext_info.get('copyright_stat', '')
})
if app_msg_ext_info.get('is_multi', 0) == 1:
for multi_dict in app_msg_ext_info['multi_app_msg_item_list']:
items.append({
'send_id': send_id,
'datetime': msg_datetime,
'type': msg_type,
'main': 0, 'title': multi_dict.get('title', ''),
'abstract': multi_dict.get('digest', ''),
'fileid': multi_dict.get('fileid', ''),
'content_url': WechatSogouStructuring.__handle_content_url(multi_dict.get('content_url')),
'source_url': multi_dict.get('source_url', ''),
'cover': multi_dict.get('cover', ''),
'author': multi_dict.get('author', ''),
'copyright_stat': multi_dict.get('copyright_stat', '')
})
return list(filter(lambda x: x['content_url'], items)) # 删除搜狗本身携带的空数据
@staticmethod
def get_gzh_info_and_article_by_history(text):
"""从 历史消息页的文本 提取公众号信息 和 文章列表信息
Parameters
----------
text : str or unicode
历史消息页的文本
Returns
-------
dict
{
'gzh': {
'wechat_name': '', # 名称
'wechat_id': '', # 微信id
'introduction': '', # 描述
'authentication': '', # 认证
'headimage': '' # 头像
},
'article': [
{
'send_id': '', # 群发id,注意不唯一,因为同一次群发多个消息,而群发id一致
'datetime': '', # 群发datatime
'type': '', # 消息类型,均是49,表示图文
'main': 0, # 是否是一次群发的第一次消息
'title': '', # 文章标题
'abstract': '', # 摘要
'fileid': '', #
'content_url': '', # 文章链接
'source_url': '', # 阅读原文的链接
'cover': '', # 封面图
'author': '', # 作者
'copyright_stat': '', # 文章类型,例如:原创啊
},
...
]
}
"""
return {
'gzh': WechatSogouStructuring.get_gzh_info_by_history(text),
'article': WechatSogouStructuring.get_article_by_history_json(text)
}
@staticmethod
def get_gzh_article_by_hot(text):
"""从 首页热门搜索 提取公众号信息 和 文章列表信息
Parameters
----------
text : str or unicode
首页热门搜索 页 中 某一页 的文本
Returns
-------
list[dict]
{
'gzh': {
'headimage': str, # 公众号头像
'wechat_name': str, # 公众号名称
},
'article': {
'url': str, # 文章临时链接
'title': str, # 文章标题
'abstract': str, # 文章摘要
'time': int, # 推送时间,10位时间戳
'open_id': str, # open id
'main_img': str # 封面图片
}
}
"""
page = etree.HTML(text)
lis = page.xpath('/html/body/li')
gzh_article_list = []
for li in lis:
url = get_first_of_element(li, 'div[1]/h4/a/@href')
title = get_first_of_element(li, 'div[1]/h4/a/div/text()')
abstract = get_first_of_element(li, 'div[1]/p[1]/text()')
xpath_time = get_first_of_element(li, 'div[1]/p[2]')
open_id = get_first_of_element(xpath_time, 'span/@data-openid')
headimage = get_first_of_element(xpath_time, 'span/@data-headimage')
gzh_name = get_first_of_element(xpath_time, 'span/text()')
send_time = xpath_time.xpath('a/span/@data-lastmodified')
main_img = get_first_of_element(li, 'div[2]/a/img/@src')
try:
send_time = int(send_time[0])
except ValueError:
send_time = send_time[0]
gzh_article_list.append({
'gzh': {
'headimage': headimage,
'wechat_name': gzh_name,
},
'article': {
'url': url,
'title': title,
'abstract': abstract,
'time': send_time,
'open_id': open_id,
'main_img': main_img
}
})
return gzh_article_list
@staticmethod
|
s0md3v/Photon | plugins/exporter.py | exporter | python | def exporter(directory, method, datasets):
if method.lower() == 'json':
# Convert json_dict to a JSON styled string
json_string = json.dumps(datasets, indent=4)
savefile = open('{}/exported.json'.format(directory), 'w+')
savefile.write(json_string)
savefile.close()
if method.lower() == 'csv':
with open('{}/exported.csv'.format(directory), 'w+') as csvfile:
csv_writer = csv.writer(
csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
for key, values in datasets.items():
if values is None:
csv_writer.writerow([key])
else:
csv_writer.writerow([key] + values)
csvfile.close() | Export the results. | train | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/plugins/exporter.py#L6-L24 | null | """Support for exporting the results."""
import csv
import json
|
s0md3v/Photon | plugins/wayback.py | time_machine | python | def time_machine(host, mode):
now = datetime.datetime.now()
to = str(now.year) + str(now.day) + str(now.month)
if now.month > 6:
fro = str(now.year) + str(now.day) + str(now.month - 6)
else:
fro = str(now.year - 1) + str(now.day) + str(now.month + 6)
url = "http://web.archive.org/cdx/search?url=%s&matchType=%s&collapse=urlkey&fl=original&filter=mimetype:text/html&filter=statuscode:200&output=json&from=%s&to=%s" % (host, mode, fro, to)
response = get(url).text
parsed = json.loads(response)[1:]
urls = []
for item in parsed:
urls.append(item[0])
return urls | Query archive.org. | train | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/plugins/wayback.py#L8-L22 | null | """Support for archive.org."""
import datetime
import json
from requests import get
|
s0md3v/Photon | core/zap.py | zap | python | def zap(input_url, archive, domain, host, internal, robots, proxies):
if archive:
print('%s Fetching URLs from archive.org' % run)
if False:
archived_urls = time_machine(domain, 'domain')
else:
archived_urls = time_machine(host, 'host')
print('%s Retrieved %i URLs from archive.org' % (
good, len(archived_urls) - 1))
for url in archived_urls:
verb('Internal page', url)
internal.add(url)
# Makes request to robots.txt
response = requests.get(input_url + '/robots.txt',
proxies=random.choice(proxies)).text
# Making sure robots.txt isn't some fancy 404 page
if '<body' not in response:
# If you know it, you know it
matches = re.findall(r'Allow: (.*)|Disallow: (.*)', response)
if matches:
# Iterating over the matches, match is a tuple here
for match in matches:
# One item in match will always be empty so will combine both
# items
match = ''.join(match)
# If the URL doesn't use a wildcard
if '*' not in match:
url = input_url + match
# Add the URL to internal list for crawling
internal.add(url)
# Add the URL to robots list
robots.add(url)
print('%s URLs retrieved from robots.txt: %s' % (good, len(robots)))
# Makes request to sitemap.xml
response = requests.get(input_url + '/sitemap.xml',
proxies=random.choice(proxies)).text
# Making sure robots.txt isn't some fancy 404 page
if '<body' not in response:
matches = xml_parser(response)
if matches: # if there are any matches
print('%s URLs retrieved from sitemap.xml: %s' % (
good, len(matches)))
for match in matches:
verb('Internal page', match)
# Cleaning up the URL and adding it to the internal list for
# crawling
internal.add(match) | Extract links from robots.txt and sitemap.xml. | train | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/core/zap.py#L10-L57 | [
"def verb(kind, string):\n \"\"\"Enable verbose output.\"\"\"\n if VERBOSE:\n print('%s %s: %s' % (info, kind, string))\n",
"def xml_parser(response):\n \"\"\"Extract links from .xml files.\"\"\"\n # Regex for extracting URLs\n return re.findall(r'<loc>(.*?)</loc>', response)\n",
"def time_machine(host, mode):\n \"\"\"Query archive.org.\"\"\"\n now = datetime.datetime.now()\n to = str(now.year) + str(now.day) + str(now.month)\n if now.month > 6:\n \tfro = str(now.year) + str(now.day) + str(now.month - 6)\n else:\n \tfro = str(now.year - 1) + str(now.day) + str(now.month + 6)\n url = \"http://web.archive.org/cdx/search?url=%s&matchType=%s&collapse=urlkey&fl=original&filter=mimetype:text/html&filter=statuscode:200&output=json&from=%s&to=%s\" % (host, mode, fro, to)\n response = get(url).text\n parsed = json.loads(response)[1:]\n urls = []\n for item in parsed:\n urls.append(item[0])\n return urls\n"
] | import re
import requests
import random
from core.utils import verb, xml_parser
from core.colors import run, good
from plugins.wayback import time_machine
|
s0md3v/Photon | core/requester.py | requester | python | def requester(
url,
main_url=None,
delay=0,
cook=None,
headers=None,
timeout=10,
host=None,
proxies=[None],
user_agents=[None],
failed=None,
processed=None
):
cook = cook or set()
headers = headers or set()
user_agents = user_agents or ['Photon']
failed = failed or set()
processed = processed or set()
# Mark the URL as crawled
processed.add(url)
# Pause/sleep the program for specified time
time.sleep(delay)
def make_request(url):
"""Default request"""
final_headers = headers or {
'Host': host,
# Selecting a random user-agent
'User-Agent': random.choice(user_agents),
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip',
'DNT': '1',
'Connection': 'close',
}
try:
response = SESSION.get(
url,
cookies=cook,
headers=final_headers,
verify=False,
timeout=timeout,
stream=True,
proxies=random.choice(proxies)
)
except TooManyRedirects:
return 'dummy'
if 'text/html' in response.headers['content-type'] or \
'text/plain' in response.headers['content-type']:
if response.status_code != '404':
return response.text
else:
response.close()
failed.add(url)
return 'dummy'
else:
response.close()
return 'dummy'
return make_request(url) | Handle the requests and return the response body. | train | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/core/requester.py#L11-L72 | [
"def make_request(url):\n \"\"\"Default request\"\"\"\n final_headers = headers or {\n 'Host': host,\n # Selecting a random user-agent\n 'User-Agent': random.choice(user_agents),\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Language': 'en-US,en;q=0.5',\n 'Accept-Encoding': 'gzip',\n 'DNT': '1',\n 'Connection': 'close',\n }\n try:\n response = SESSION.get(\n url,\n cookies=cook,\n headers=final_headers,\n verify=False,\n timeout=timeout,\n stream=True,\n proxies=random.choice(proxies)\n )\n except TooManyRedirects:\n return 'dummy'\n\n if 'text/html' in response.headers['content-type'] or \\\n 'text/plain' in response.headers['content-type']:\n if response.status_code != '404':\n return response.text\n else:\n response.close()\n failed.add(url)\n return 'dummy'\n else:\n response.close()\n return 'dummy'\n"
] | import random
import time
import requests
from requests.exceptions import TooManyRedirects
SESSION = requests.Session()
SESSION.max_redirects = 3
|
s0md3v/Photon | photon.py | intel_extractor | python | def intel_extractor(url, response):
"""Extract intel from the response body."""
for rintel in rintels:
res = re.sub(r'<(script).*?</\1>(?s)', '', response)
res = re.sub(r'<[^<]+?>', '', res)
matches = rintel[0].findall(res)
if matches:
for match in matches:
verb('Intel', match)
bad_intel.add((match, rintel[1], url)) | Extract intel from the response body. | train | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/photon.py#L208-L217 | [
"def verb(kind, string):\n \"\"\"Enable verbose output.\"\"\"\n if VERBOSE:\n print('%s %s: %s' % (info, kind, string))\n"
] | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""The Photon main part."""
from __future__ import print_function
import argparse
import os
import re
import requests
import sys
import time
import warnings
import random
from core.colors import good, info, run, green, red, white, end, bad
# Just a fancy ass banner
print('''%s ____ __ __
/ %s__%s \/ /_ ____ / /_____ ____
/ %s/_/%s / __ \/ %s__%s \/ __/ %s__%s \/ __ \\
/ ____/ / / / %s/_/%s / /_/ %s/_/%s / / / /
/_/ /_/ /_/\____/\__/\____/_/ /_/ %sv1.3.2%s\n''' %
(red, white, red, white, red, white, red, white, red, white, red, white,
red, white, end))
try:
from urllib.parse import urlparse # For Python 3
except ImportError:
print('%s Photon runs only on Python 3.2 and above.' % info)
quit()
import core.config
from core.config import INTELS
from core.flash import flash
from core.mirror import mirror
from core.prompt import prompt
from core.requester import requester
from core.updater import updater
from core.utils import (luhn,
proxy_type,
is_good_proxy,
top_level,
extract_headers,
verb, is_link,
entropy, regxy,
remove_regex,
timer,
writer)
from core.regex import rintels, rendpoint, rhref, rscript, rentropy
from core.zap import zap
# Disable SSL related warnings
warnings.filterwarnings('ignore')
# Processing command line arguments
parser = argparse.ArgumentParser()
# Options
parser.add_argument('-u', '--url', help='root url', dest='root')
parser.add_argument('-c', '--cookie', help='cookie', dest='cook')
parser.add_argument('-r', '--regex', help='regex pattern', dest='regex')
parser.add_argument('-e', '--export', help='export format', dest='export', choices=['csv', 'json'])
parser.add_argument('-o', '--output', help='output directory', dest='output')
parser.add_argument('-l', '--level', help='levels to crawl', dest='level',
type=int)
parser.add_argument('-t', '--threads', help='number of threads', dest='threads',
type=int)
parser.add_argument('-d', '--delay', help='delay between requests',
dest='delay', type=float)
parser.add_argument('-v', '--verbose', help='verbose output', dest='verbose',
action='store_true')
parser.add_argument('-s', '--seeds', help='additional seed URLs', dest='seeds',
nargs="+", default=[])
parser.add_argument('--stdout', help='send variables to stdout', dest='std')
parser.add_argument('--user-agent', help='custom user agent(s)',
dest='user_agent')
parser.add_argument('--exclude', help='exclude URLs matching this regex',
dest='exclude')
parser.add_argument('--timeout', help='http request timeout', dest='timeout',
type=float)
parser.add_argument('-p', '--proxy', help='Proxy server IP:PORT or DOMAIN:PORT', dest='proxies',
type=proxy_type)
# Switches
parser.add_argument('--clone', help='clone the website locally', dest='clone',
action='store_true')
parser.add_argument('--headers', help='add headers', dest='headers',
action='store_true')
parser.add_argument('--dns', help='enumerate subdomains and DNS data',
dest='dns', action='store_true')
parser.add_argument('--keys', help='find secret keys', dest='api',
action='store_true')
parser.add_argument('--update', help='update photon', dest='update',
action='store_true')
parser.add_argument('--only-urls', help='only extract URLs', dest='only_urls',
action='store_true')
parser.add_argument('--wayback', help='fetch URLs from archive.org as seeds',
dest='archive', action='store_true')
args = parser.parse_args()
# If the user has supplied --update argument
if args.update:
updater()
quit()
# If the user has supplied a URL
if args.root:
main_inp = args.root
if main_inp.endswith('/'):
# We will remove it as it can cause problems later in the code
main_inp = main_inp[:-1]
# If the user hasn't supplied an URL
else:
print('\n' + parser.format_help().lower())
quit()
clone = args.clone
headers = args.headers # prompt for headers
verbose = args.verbose # verbose output
delay = args.delay or 0 # Delay between requests
timeout = args.timeout or 6 # HTTP request timeout
cook = args.cook or None # Cookie
api = bool(args.api) # Extract high entropy strings i.e. API keys and stuff
proxies = []
if args.proxies:
print("%s Testing proxies, can take a while..." % info)
for proxy in args.proxies:
if is_good_proxy(proxy):
proxies.append(proxy)
else:
print("%s Proxy %s doesn't seem to work or timedout" %
(bad, proxy['http']))
print("%s Done" % info)
if not proxies:
print("%s no working proxies, quitting!" % bad)
exit()
else:
proxies.append(None)
crawl_level = args.level or 2 # Crawling level
thread_count = args.threads or 2 # Number of threads
only_urls = bool(args.only_urls) # Only URLs mode is off by default
# Variables we are gonna use later to store stuff
keys = set() # High entropy strings, prolly secret keys
files = set() # The pdf, css, png, etc files.
intel = set() # The email addresses, website accounts, AWS buckets etc.
robots = set() # The entries of robots.txt
custom = set() # Strings extracted by custom regex pattern
failed = set() # URLs that photon failed to crawl
scripts = set() # THe Javascript files
external = set() # URLs that don't belong to the target i.e. out-of-scope
# URLs that have get params in them e.g. example.com/page.php?id=2
fuzzable = set()
endpoints = set() # URLs found from javascript files
processed = set(['dummy']) # URLs that have been crawled
# URLs that belong to the target i.e. in-scope
internal = set(args.seeds)
everything = []
bad_scripts = set() # Unclean javascript file urls
bad_intel = set() # needed for intel filtering
core.config.verbose = verbose
if headers:
try:
prompt = prompt()
except FileNotFoundError as e:
print('Could not load headers prompt: {}'.format(e))
quit()
headers = extract_headers(prompt)
# If the user hasn't supplied the root URL with http(s), we will handle it
if main_inp.startswith('http'):
main_url = main_inp
else:
try:
requests.get('https://' + main_inp, proxies=random.choice(proxies))
main_url = 'https://' + main_inp
except:
main_url = 'http://' + main_inp
schema = main_url.split('//')[0] # https: or http:?
# Adding the root URL to internal for crawling
internal.add(main_url)
# Extracts host out of the URL
host = urlparse(main_url).netloc
output_dir = args.output or host
try:
domain = top_level(main_url)
except:
domain = host
if args.user_agent:
user_agents = args.user_agent.split(',')
else:
with open(sys.path[0] + '/core/user-agents.txt', 'r') as uas:
user_agents = [agent.strip('\n') for agent in uas]
supress_regex = False
def intel_extractor(url, response):
"""Extract intel from the response body."""
for rintel in rintels:
res = re.sub(r'<(script).*?</\1>(?s)', '', response)
res = re.sub(r'<[^<]+?>', '', res)
matches = rintel[0].findall(res)
if matches:
for match in matches:
verb('Intel', match)
bad_intel.add((match, rintel[1], url))
def js_extractor(response):
"""Extract js files from the response body"""
# Extract .js files
matches = rscript.findall(response)
for match in matches:
match = match[2].replace('\'', '').replace('"', '')
verb('JS file', match)
bad_scripts.add(match)
def remove_file(url):
if url.count('/') > 2:
replacable = re.search(r'/[^/]*?$', url).group()
if replacable != '/':
return url.replace(replacable, '')
else:
return url
else:
return url
def extractor(url):
"""Extract details from the response body."""
response = requester(url, main_url, delay, cook, headers, timeout, host, proxies, user_agents, failed, processed)
if clone:
mirror(url, response)
matches = rhref.findall(response)
for link in matches:
# Remove everything after a "#" to deal with in-page anchors
link = link[1].replace('\'', '').replace('"', '').split('#')[0]
# Checks if the URLs should be crawled
if is_link(link, processed, files):
if link[:4] == 'http':
if link.startswith(main_url):
verb('Internal page', link)
internal.add(link)
else:
verb('External page', link)
external.add(link)
elif link[:2] == '//':
if link.split('/')[2].startswith(host):
verb('Internal page', link)
internal.add(schema + '://' + link)
else:
verb('External page', link)
external.add(link)
elif link[:1] == '/':
verb('Internal page', link)
internal.add(remove_file(url) + link)
else:
verb('Internal page', link)
usable_url = remove_file(url)
if usable_url.endswith('/'):
internal.add(usable_url + link)
elif link.startswith('/'):
internal.add(usable_url + link)
else:
internal.add(usable_url + '/' + link)
if not only_urls:
intel_extractor(url, response)
js_extractor(response)
if args.regex and not supress_regex:
regxy(args.regex, response, supress_regex, custom)
if api:
matches = rentropy.findall(response)
for match in matches:
if entropy(match) >= 4:
verb('Key', match)
keys.add(url + ': ' + match)
def jscanner(url):
"""Extract endpoints from JavaScript code."""
response = requester(url, main_url, delay, cook, headers, timeout, host, proxies, user_agents, failed, processed)
# Extract URLs/endpoints
matches = rendpoint.findall(response)
# Iterate over the matches, match is a tuple
for match in matches:
# Combining the items because one of them is always empty
match = match[0] + match[1]
# Making sure it's not some JavaScript code
if not re.search(r'[}{><"\']', match) and not match == '/':
verb('JS endpoint', match)
endpoints.add(match)
# Records the time at which crawling started
then = time.time()
# Step 1. Extract urls from robots.txt & sitemap.xml
zap(main_url, args.archive, domain, host, internal, robots, proxies)
# This is so the level 1 emails are parsed as well
internal = set(remove_regex(internal, args.exclude))
# Step 2. Crawl recursively to the limit specified in "crawl_level"
for level in range(crawl_level):
# Links to crawl = (all links - already crawled links) - links not to crawl
links = remove_regex(internal - processed, args.exclude)
# If links to crawl are 0 i.e. all links have been crawled
if not links:
break
# if crawled links are somehow more than all links. Possible? ;/
elif len(internal) <= len(processed):
if len(internal) > 2 + len(args.seeds):
break
print('%s Level %i: %i URLs' % (run, level + 1, len(links)))
try:
flash(extractor, links, thread_count)
except KeyboardInterrupt:
print('')
break
if not only_urls:
for match in bad_scripts:
if match.startswith(main_url):
scripts.add(match)
elif match.startswith('/') and not match.startswith('//'):
scripts.add(main_url + match)
elif not match.startswith('http') and not match.startswith('//'):
scripts.add(main_url + '/' + match)
# Step 3. Scan the JavaScript files for endpoints
print('%s Crawling %i JavaScript files' % (run, len(scripts)))
flash(jscanner, scripts, thread_count)
for url in internal:
if '=' in url:
fuzzable.add(url)
for match, intel_name, url in bad_intel:
if isinstance(match, tuple):
for x in match: # Because "match" is a tuple
if x != '': # If the value isn't empty
if intel_name == "CREDIT_CARD":
if not luhn(match):
# garbage number
continue
intel.add("%s:%s" % (intel_name, x))
else:
if intel_name == "CREDIT_CARD":
if not luhn(match):
# garbage number
continue
intel.add("%s:%s:%s" % (url, intel_name, match))
for url in external:
try:
if top_level(url, fix_protocol=True) in INTELS:
intel.add(url)
except:
pass
# Records the time at which crawling stopped
now = time.time()
# Finds total time taken
diff = (now - then)
minutes, seconds, time_per_request = timer(diff, processed)
# Step 4. Save the results
if not os.path.exists(output_dir): # if the directory doesn't exist
os.mkdir(output_dir) # create a new directory
datasets = [files, intel, robots, custom, failed, internal, scripts,
external, fuzzable, endpoints, keys]
dataset_names = ['files', 'intel', 'robots', 'custom', 'failed', 'internal',
'scripts', 'external', 'fuzzable', 'endpoints', 'keys']
writer(datasets, dataset_names, output_dir)
# Printing out results
print(('%s-%s' % (red, end)) * 50)
for dataset, dataset_name in zip(datasets, dataset_names):
if dataset:
print('%s %s: %s' % (good, dataset_name.capitalize(), len(dataset)))
print(('%s-%s' % (red, end)) * 50)
print('%s Total requests made: %i' % (info, len(processed)))
print('%s Total time taken: %i minutes %i seconds' % (info, minutes, seconds))
print('%s Requests per second: %i' % (info, int(len(processed) / diff)))
datasets = {
'files': list(files), 'intel': list(intel), 'robots': list(robots),
'custom': list(custom), 'failed': list(failed), 'internal': list(internal),
'scripts': list(scripts), 'external': list(external),
'fuzzable': list(fuzzable), 'endpoints': list(endpoints),
'keys': list(keys)
}
if args.dns:
print('%s Enumerating subdomains' % run)
from plugins.find_subdomains import find_subdomains
subdomains = find_subdomains(domain)
print('%s %i subdomains found' % (info, len(subdomains)))
writer([subdomains], ['subdomains'], output_dir)
datasets['subdomains'] = subdomains
from plugins.dnsdumpster import dnsdumpster
print('%s Generating DNS map' % run)
dnsdumpster(domain, output_dir)
if args.export:
from plugins.exporter import exporter
# exporter(directory, format, datasets)
exporter(output_dir, args.export, datasets)
print('%s Results saved in %s%s%s directory' % (good, green, output_dir, end))
if args.std:
for string in datasets[args.std]:
sys.stdout.write(string + '\n')
|
s0md3v/Photon | photon.py | js_extractor | python | def js_extractor(response):
"""Extract js files from the response body"""
# Extract .js files
matches = rscript.findall(response)
for match in matches:
match = match[2].replace('\'', '').replace('"', '')
verb('JS file', match)
bad_scripts.add(match) | Extract js files from the response body | train | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/photon.py#L220-L227 | [
"def verb(kind, string):\n \"\"\"Enable verbose output.\"\"\"\n if VERBOSE:\n print('%s %s: %s' % (info, kind, string))\n"
] | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""The Photon main part."""
from __future__ import print_function
import argparse
import os
import re
import requests
import sys
import time
import warnings
import random
from core.colors import good, info, run, green, red, white, end, bad
# Just a fancy ass banner
print('''%s ____ __ __
/ %s__%s \/ /_ ____ / /_____ ____
/ %s/_/%s / __ \/ %s__%s \/ __/ %s__%s \/ __ \\
/ ____/ / / / %s/_/%s / /_/ %s/_/%s / / / /
/_/ /_/ /_/\____/\__/\____/_/ /_/ %sv1.3.2%s\n''' %
(red, white, red, white, red, white, red, white, red, white, red, white,
red, white, end))
try:
from urllib.parse import urlparse # For Python 3
except ImportError:
print('%s Photon runs only on Python 3.2 and above.' % info)
quit()
import core.config
from core.config import INTELS
from core.flash import flash
from core.mirror import mirror
from core.prompt import prompt
from core.requester import requester
from core.updater import updater
from core.utils import (luhn,
proxy_type,
is_good_proxy,
top_level,
extract_headers,
verb, is_link,
entropy, regxy,
remove_regex,
timer,
writer)
from core.regex import rintels, rendpoint, rhref, rscript, rentropy
from core.zap import zap
# Disable SSL related warnings
warnings.filterwarnings('ignore')
# Processing command line arguments
parser = argparse.ArgumentParser()
# Options
parser.add_argument('-u', '--url', help='root url', dest='root')
parser.add_argument('-c', '--cookie', help='cookie', dest='cook')
parser.add_argument('-r', '--regex', help='regex pattern', dest='regex')
parser.add_argument('-e', '--export', help='export format', dest='export', choices=['csv', 'json'])
parser.add_argument('-o', '--output', help='output directory', dest='output')
parser.add_argument('-l', '--level', help='levels to crawl', dest='level',
type=int)
parser.add_argument('-t', '--threads', help='number of threads', dest='threads',
type=int)
parser.add_argument('-d', '--delay', help='delay between requests',
dest='delay', type=float)
parser.add_argument('-v', '--verbose', help='verbose output', dest='verbose',
action='store_true')
parser.add_argument('-s', '--seeds', help='additional seed URLs', dest='seeds',
nargs="+", default=[])
parser.add_argument('--stdout', help='send variables to stdout', dest='std')
parser.add_argument('--user-agent', help='custom user agent(s)',
dest='user_agent')
parser.add_argument('--exclude', help='exclude URLs matching this regex',
dest='exclude')
parser.add_argument('--timeout', help='http request timeout', dest='timeout',
type=float)
parser.add_argument('-p', '--proxy', help='Proxy server IP:PORT or DOMAIN:PORT', dest='proxies',
type=proxy_type)
# Switches
parser.add_argument('--clone', help='clone the website locally', dest='clone',
action='store_true')
parser.add_argument('--headers', help='add headers', dest='headers',
action='store_true')
parser.add_argument('--dns', help='enumerate subdomains and DNS data',
dest='dns', action='store_true')
parser.add_argument('--keys', help='find secret keys', dest='api',
action='store_true')
parser.add_argument('--update', help='update photon', dest='update',
action='store_true')
parser.add_argument('--only-urls', help='only extract URLs', dest='only_urls',
action='store_true')
parser.add_argument('--wayback', help='fetch URLs from archive.org as seeds',
dest='archive', action='store_true')
args = parser.parse_args()
# If the user has supplied --update argument
if args.update:
updater()
quit()
# If the user has supplied a URL
if args.root:
main_inp = args.root
if main_inp.endswith('/'):
# We will remove it as it can cause problems later in the code
main_inp = main_inp[:-1]
# If the user hasn't supplied an URL
else:
print('\n' + parser.format_help().lower())
quit()
clone = args.clone
headers = args.headers # prompt for headers
verbose = args.verbose # verbose output
delay = args.delay or 0 # Delay between requests
timeout = args.timeout or 6 # HTTP request timeout
cook = args.cook or None # Cookie
api = bool(args.api) # Extract high entropy strings i.e. API keys and stuff
proxies = []
if args.proxies:
print("%s Testing proxies, can take a while..." % info)
for proxy in args.proxies:
if is_good_proxy(proxy):
proxies.append(proxy)
else:
print("%s Proxy %s doesn't seem to work or timedout" %
(bad, proxy['http']))
print("%s Done" % info)
if not proxies:
print("%s no working proxies, quitting!" % bad)
exit()
else:
proxies.append(None)
crawl_level = args.level or 2 # Crawling level
thread_count = args.threads or 2 # Number of threads
only_urls = bool(args.only_urls) # Only URLs mode is off by default
# Variables we are gonna use later to store stuff
keys = set() # High entropy strings, prolly secret keys
files = set() # The pdf, css, png, etc files.
intel = set() # The email addresses, website accounts, AWS buckets etc.
robots = set() # The entries of robots.txt
custom = set() # Strings extracted by custom regex pattern
failed = set() # URLs that photon failed to crawl
scripts = set() # THe Javascript files
external = set() # URLs that don't belong to the target i.e. out-of-scope
# URLs that have get params in them e.g. example.com/page.php?id=2
fuzzable = set()
endpoints = set() # URLs found from javascript files
processed = set(['dummy']) # URLs that have been crawled
# URLs that belong to the target i.e. in-scope
internal = set(args.seeds)
everything = []
bad_scripts = set() # Unclean javascript file urls
bad_intel = set() # needed for intel filtering
core.config.verbose = verbose
if headers:
try:
prompt = prompt()
except FileNotFoundError as e:
print('Could not load headers prompt: {}'.format(e))
quit()
headers = extract_headers(prompt)
# If the user hasn't supplied the root URL with http(s), we will handle it
if main_inp.startswith('http'):
main_url = main_inp
else:
try:
requests.get('https://' + main_inp, proxies=random.choice(proxies))
main_url = 'https://' + main_inp
except:
main_url = 'http://' + main_inp
schema = main_url.split('//')[0] # https: or http:?
# Adding the root URL to internal for crawling
internal.add(main_url)
# Extracts host out of the URL
host = urlparse(main_url).netloc
output_dir = args.output or host
try:
domain = top_level(main_url)
except:
domain = host
if args.user_agent:
user_agents = args.user_agent.split(',')
else:
with open(sys.path[0] + '/core/user-agents.txt', 'r') as uas:
user_agents = [agent.strip('\n') for agent in uas]
supress_regex = False
def intel_extractor(url, response):
"""Extract intel from the response body."""
for rintel in rintels:
res = re.sub(r'<(script).*?</\1>(?s)', '', response)
res = re.sub(r'<[^<]+?>', '', res)
matches = rintel[0].findall(res)
if matches:
for match in matches:
verb('Intel', match)
bad_intel.add((match, rintel[1], url))
def js_extractor(response):
"""Extract js files from the response body"""
# Extract .js files
matches = rscript.findall(response)
for match in matches:
match = match[2].replace('\'', '').replace('"', '')
verb('JS file', match)
bad_scripts.add(match)
def remove_file(url):
if url.count('/') > 2:
replacable = re.search(r'/[^/]*?$', url).group()
if replacable != '/':
return url.replace(replacable, '')
else:
return url
else:
return url
def extractor(url):
"""Extract details from the response body."""
response = requester(url, main_url, delay, cook, headers, timeout, host, proxies, user_agents, failed, processed)
if clone:
mirror(url, response)
matches = rhref.findall(response)
for link in matches:
# Remove everything after a "#" to deal with in-page anchors
link = link[1].replace('\'', '').replace('"', '').split('#')[0]
# Checks if the URLs should be crawled
if is_link(link, processed, files):
if link[:4] == 'http':
if link.startswith(main_url):
verb('Internal page', link)
internal.add(link)
else:
verb('External page', link)
external.add(link)
elif link[:2] == '//':
if link.split('/')[2].startswith(host):
verb('Internal page', link)
internal.add(schema + '://' + link)
else:
verb('External page', link)
external.add(link)
elif link[:1] == '/':
verb('Internal page', link)
internal.add(remove_file(url) + link)
else:
verb('Internal page', link)
usable_url = remove_file(url)
if usable_url.endswith('/'):
internal.add(usable_url + link)
elif link.startswith('/'):
internal.add(usable_url + link)
else:
internal.add(usable_url + '/' + link)
if not only_urls:
intel_extractor(url, response)
js_extractor(response)
if args.regex and not supress_regex:
regxy(args.regex, response, supress_regex, custom)
if api:
matches = rentropy.findall(response)
for match in matches:
if entropy(match) >= 4:
verb('Key', match)
keys.add(url + ': ' + match)
def jscanner(url):
"""Extract endpoints from JavaScript code."""
response = requester(url, main_url, delay, cook, headers, timeout, host, proxies, user_agents, failed, processed)
# Extract URLs/endpoints
matches = rendpoint.findall(response)
# Iterate over the matches, match is a tuple
for match in matches:
# Combining the items because one of them is always empty
match = match[0] + match[1]
# Making sure it's not some JavaScript code
if not re.search(r'[}{><"\']', match) and not match == '/':
verb('JS endpoint', match)
endpoints.add(match)
# Records the time at which crawling started
then = time.time()
# Step 1. Extract urls from robots.txt & sitemap.xml
zap(main_url, args.archive, domain, host, internal, robots, proxies)
# This is so the level 1 emails are parsed as well
internal = set(remove_regex(internal, args.exclude))
# Step 2. Crawl recursively to the limit specified in "crawl_level"
for level in range(crawl_level):
# Links to crawl = (all links - already crawled links) - links not to crawl
links = remove_regex(internal - processed, args.exclude)
# If links to crawl are 0 i.e. all links have been crawled
if not links:
break
# if crawled links are somehow more than all links. Possible? ;/
elif len(internal) <= len(processed):
if len(internal) > 2 + len(args.seeds):
break
print('%s Level %i: %i URLs' % (run, level + 1, len(links)))
try:
flash(extractor, links, thread_count)
except KeyboardInterrupt:
print('')
break
if not only_urls:
for match in bad_scripts:
if match.startswith(main_url):
scripts.add(match)
elif match.startswith('/') and not match.startswith('//'):
scripts.add(main_url + match)
elif not match.startswith('http') and not match.startswith('//'):
scripts.add(main_url + '/' + match)
# Step 3. Scan the JavaScript files for endpoints
print('%s Crawling %i JavaScript files' % (run, len(scripts)))
flash(jscanner, scripts, thread_count)
for url in internal:
if '=' in url:
fuzzable.add(url)
for match, intel_name, url in bad_intel:
if isinstance(match, tuple):
for x in match: # Because "match" is a tuple
if x != '': # If the value isn't empty
if intel_name == "CREDIT_CARD":
if not luhn(match):
# garbage number
continue
intel.add("%s:%s" % (intel_name, x))
else:
if intel_name == "CREDIT_CARD":
if not luhn(match):
# garbage number
continue
intel.add("%s:%s:%s" % (url, intel_name, match))
for url in external:
try:
if top_level(url, fix_protocol=True) in INTELS:
intel.add(url)
except:
pass
# Records the time at which crawling stopped
now = time.time()
# Finds total time taken
diff = (now - then)
minutes, seconds, time_per_request = timer(diff, processed)
# Step 4. Save the results
if not os.path.exists(output_dir): # if the directory doesn't exist
os.mkdir(output_dir) # create a new directory
datasets = [files, intel, robots, custom, failed, internal, scripts,
external, fuzzable, endpoints, keys]
dataset_names = ['files', 'intel', 'robots', 'custom', 'failed', 'internal',
'scripts', 'external', 'fuzzable', 'endpoints', 'keys']
writer(datasets, dataset_names, output_dir)
# Printing out results
print(('%s-%s' % (red, end)) * 50)
for dataset, dataset_name in zip(datasets, dataset_names):
if dataset:
print('%s %s: %s' % (good, dataset_name.capitalize(), len(dataset)))
print(('%s-%s' % (red, end)) * 50)
print('%s Total requests made: %i' % (info, len(processed)))
print('%s Total time taken: %i minutes %i seconds' % (info, minutes, seconds))
print('%s Requests per second: %i' % (info, int(len(processed) / diff)))
datasets = {
'files': list(files), 'intel': list(intel), 'robots': list(robots),
'custom': list(custom), 'failed': list(failed), 'internal': list(internal),
'scripts': list(scripts), 'external': list(external),
'fuzzable': list(fuzzable), 'endpoints': list(endpoints),
'keys': list(keys)
}
if args.dns:
print('%s Enumerating subdomains' % run)
from plugins.find_subdomains import find_subdomains
subdomains = find_subdomains(domain)
print('%s %i subdomains found' % (info, len(subdomains)))
writer([subdomains], ['subdomains'], output_dir)
datasets['subdomains'] = subdomains
from plugins.dnsdumpster import dnsdumpster
print('%s Generating DNS map' % run)
dnsdumpster(domain, output_dir)
if args.export:
from plugins.exporter import exporter
# exporter(directory, format, datasets)
exporter(output_dir, args.export, datasets)
print('%s Results saved in %s%s%s directory' % (good, green, output_dir, end))
if args.std:
for string in datasets[args.std]:
sys.stdout.write(string + '\n')
|
s0md3v/Photon | photon.py | extractor | python | def extractor(url):
"""Extract details from the response body."""
response = requester(url, main_url, delay, cook, headers, timeout, host, proxies, user_agents, failed, processed)
if clone:
mirror(url, response)
matches = rhref.findall(response)
for link in matches:
# Remove everything after a "#" to deal with in-page anchors
link = link[1].replace('\'', '').replace('"', '').split('#')[0]
# Checks if the URLs should be crawled
if is_link(link, processed, files):
if link[:4] == 'http':
if link.startswith(main_url):
verb('Internal page', link)
internal.add(link)
else:
verb('External page', link)
external.add(link)
elif link[:2] == '//':
if link.split('/')[2].startswith(host):
verb('Internal page', link)
internal.add(schema + '://' + link)
else:
verb('External page', link)
external.add(link)
elif link[:1] == '/':
verb('Internal page', link)
internal.add(remove_file(url) + link)
else:
verb('Internal page', link)
usable_url = remove_file(url)
if usable_url.endswith('/'):
internal.add(usable_url + link)
elif link.startswith('/'):
internal.add(usable_url + link)
else:
internal.add(usable_url + '/' + link)
if not only_urls:
intel_extractor(url, response)
js_extractor(response)
if args.regex and not supress_regex:
regxy(args.regex, response, supress_regex, custom)
if api:
matches = rentropy.findall(response)
for match in matches:
if entropy(match) >= 4:
verb('Key', match)
keys.add(url + ': ' + match) | Extract details from the response body. | train | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/photon.py#L239-L287 | [
"def mirror(url, response):\n if response != 'dummy':\n clean_url = url.replace('http://', '').replace('https://', '').rstrip('/')\n parts = clean_url.split('?')[0].split('/')\n root = parts[0]\n webpage = parts[-1]\n parts.remove(root)\n try:\n parts.remove(webpage)\n except ValueError:\n pass\n prefix = root + '_mirror'\n try:\n os.mkdir(prefix)\n except OSError:\n pass\n suffix = ''\n if parts:\n for directory in parts:\n suffix += directory + '/'\n try:\n os.mkdir(prefix + '/' + suffix)\n except OSError:\n pass\n path = prefix + '/' + suffix\n trail = ''\n if '.' not in webpage:\n trail += '.html'\n if webpage == root:\n name = 'index.html'\n else:\n name = webpage\n if len(url.split('?')) > 1:\n trail += '?' + url.split('?')[1]\n with open(path + name + trail, 'w+') as out_file:\n out_file.write(response.encode('utf-8'))\n",
"def requester(\n url,\n main_url=None,\n delay=0,\n cook=None,\n headers=None,\n timeout=10,\n host=None,\n proxies=[None],\n user_agents=[None],\n failed=None,\n processed=None\n ):\n \"\"\"Handle the requests and return the response body.\"\"\"\n cook = cook or set()\n headers = headers or set()\n user_agents = user_agents or ['Photon']\n failed = failed or set()\n processed = processed or set()\n # Mark the URL as crawled\n processed.add(url)\n # Pause/sleep the program for specified time\n time.sleep(delay)\n\n def make_request(url):\n \"\"\"Default request\"\"\"\n final_headers = headers or {\n 'Host': host,\n # Selecting a random user-agent\n 'User-Agent': random.choice(user_agents),\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Language': 'en-US,en;q=0.5',\n 'Accept-Encoding': 'gzip',\n 'DNT': '1',\n 'Connection': 'close',\n }\n try:\n response = SESSION.get(\n url,\n cookies=cook,\n headers=final_headers,\n verify=False,\n timeout=timeout,\n stream=True,\n proxies=random.choice(proxies)\n )\n except TooManyRedirects:\n return 'dummy'\n\n if 'text/html' in response.headers['content-type'] or \\\n 'text/plain' in response.headers['content-type']:\n if response.status_code != '404':\n return response.text\n else:\n response.close()\n failed.add(url)\n return 'dummy'\n else:\n response.close()\n return 'dummy'\n\n return make_request(url)\n",
"def verb(kind, string):\n \"\"\"Enable verbose output.\"\"\"\n if VERBOSE:\n print('%s %s: %s' % (info, kind, string))\n",
"def is_link(url, processed, files):\n \"\"\"\n Determine whether or not a link should be crawled\n A url should not be crawled if it\n - Is a file\n - Has already been crawled\n\n Args:\n url: str Url to be processed\n processed: list[str] List of urls that have already been crawled\n\n Returns:\n bool If `url` should be crawled\n \"\"\"\n if url not in processed:\n is_file = url.endswith(BAD_TYPES)\n if is_file:\n files.add(url)\n return False\n return True\n return False\n",
"def entropy(string):\n \"\"\"Calculate the entropy of a string.\"\"\"\n entropy = 0\n for number in range(256):\n result = float(string.encode('utf-8').count(\n chr(number))) / len(string.encode('utf-8'))\n if result != 0:\n entropy = entropy - result * math.log(result, 2)\n return entropy\n",
"def regxy(pattern, response, supress_regex, custom):\n \"\"\"Extract a string based on regex pattern supplied by user.\"\"\"\n try:\n matches = re.findall(r'%s' % pattern, response)\n for match in matches:\n verb('Custom regex', match)\n custom.add(match)\n except:\n supress_regex = True\n",
"def intel_extractor(url, response):\n \"\"\"Extract intel from the response body.\"\"\"\n for rintel in rintels:\n res = re.sub(r'<(script).*?</\\1>(?s)', '', response)\n res = re.sub(r'<[^<]+?>', '', res)\n matches = rintel[0].findall(res)\n if matches:\n for match in matches:\n verb('Intel', match)\n bad_intel.add((match, rintel[1], url))\n",
"def js_extractor(response):\n \"\"\"Extract js files from the response body\"\"\"\n # Extract .js files\n matches = rscript.findall(response)\n for match in matches:\n match = match[2].replace('\\'', '').replace('\"', '')\n verb('JS file', match)\n bad_scripts.add(match)\n"
] | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""The Photon main part."""
from __future__ import print_function
import argparse
import os
import re
import requests
import sys
import time
import warnings
import random
from core.colors import good, info, run, green, red, white, end, bad
# Just a fancy ass banner
print('''%s ____ __ __
/ %s__%s \/ /_ ____ / /_____ ____
/ %s/_/%s / __ \/ %s__%s \/ __/ %s__%s \/ __ \\
/ ____/ / / / %s/_/%s / /_/ %s/_/%s / / / /
/_/ /_/ /_/\____/\__/\____/_/ /_/ %sv1.3.2%s\n''' %
(red, white, red, white, red, white, red, white, red, white, red, white,
red, white, end))
try:
from urllib.parse import urlparse # For Python 3
except ImportError:
print('%s Photon runs only on Python 3.2 and above.' % info)
quit()
import core.config
from core.config import INTELS
from core.flash import flash
from core.mirror import mirror
from core.prompt import prompt
from core.requester import requester
from core.updater import updater
from core.utils import (luhn,
proxy_type,
is_good_proxy,
top_level,
extract_headers,
verb, is_link,
entropy, regxy,
remove_regex,
timer,
writer)
from core.regex import rintels, rendpoint, rhref, rscript, rentropy
from core.zap import zap
# Disable SSL related warnings
warnings.filterwarnings('ignore')
# Processing command line arguments
parser = argparse.ArgumentParser()
# Options
parser.add_argument('-u', '--url', help='root url', dest='root')
parser.add_argument('-c', '--cookie', help='cookie', dest='cook')
parser.add_argument('-r', '--regex', help='regex pattern', dest='regex')
parser.add_argument('-e', '--export', help='export format', dest='export', choices=['csv', 'json'])
parser.add_argument('-o', '--output', help='output directory', dest='output')
parser.add_argument('-l', '--level', help='levels to crawl', dest='level',
type=int)
parser.add_argument('-t', '--threads', help='number of threads', dest='threads',
type=int)
parser.add_argument('-d', '--delay', help='delay between requests',
dest='delay', type=float)
parser.add_argument('-v', '--verbose', help='verbose output', dest='verbose',
action='store_true')
parser.add_argument('-s', '--seeds', help='additional seed URLs', dest='seeds',
nargs="+", default=[])
parser.add_argument('--stdout', help='send variables to stdout', dest='std')
parser.add_argument('--user-agent', help='custom user agent(s)',
dest='user_agent')
parser.add_argument('--exclude', help='exclude URLs matching this regex',
dest='exclude')
parser.add_argument('--timeout', help='http request timeout', dest='timeout',
type=float)
parser.add_argument('-p', '--proxy', help='Proxy server IP:PORT or DOMAIN:PORT', dest='proxies',
type=proxy_type)
# Switches
parser.add_argument('--clone', help='clone the website locally', dest='clone',
action='store_true')
parser.add_argument('--headers', help='add headers', dest='headers',
action='store_true')
parser.add_argument('--dns', help='enumerate subdomains and DNS data',
dest='dns', action='store_true')
parser.add_argument('--keys', help='find secret keys', dest='api',
action='store_true')
parser.add_argument('--update', help='update photon', dest='update',
action='store_true')
parser.add_argument('--only-urls', help='only extract URLs', dest='only_urls',
action='store_true')
parser.add_argument('--wayback', help='fetch URLs from archive.org as seeds',
dest='archive', action='store_true')
args = parser.parse_args()
# If the user has supplied --update argument
if args.update:
updater()
quit()
# If the user has supplied a URL
if args.root:
main_inp = args.root
if main_inp.endswith('/'):
# We will remove it as it can cause problems later in the code
main_inp = main_inp[:-1]
# If the user hasn't supplied an URL
else:
print('\n' + parser.format_help().lower())
quit()
clone = args.clone
headers = args.headers # prompt for headers
verbose = args.verbose # verbose output
delay = args.delay or 0 # Delay between requests
timeout = args.timeout or 6 # HTTP request timeout
cook = args.cook or None # Cookie
api = bool(args.api) # Extract high entropy strings i.e. API keys and stuff
proxies = []
if args.proxies:
print("%s Testing proxies, can take a while..." % info)
for proxy in args.proxies:
if is_good_proxy(proxy):
proxies.append(proxy)
else:
print("%s Proxy %s doesn't seem to work or timedout" %
(bad, proxy['http']))
print("%s Done" % info)
if not proxies:
print("%s no working proxies, quitting!" % bad)
exit()
else:
proxies.append(None)
crawl_level = args.level or 2 # Crawling level
thread_count = args.threads or 2 # Number of threads
only_urls = bool(args.only_urls) # Only URLs mode is off by default
# Variables we are gonna use later to store stuff
keys = set() # High entropy strings, prolly secret keys
files = set() # The pdf, css, png, etc files.
intel = set() # The email addresses, website accounts, AWS buckets etc.
robots = set() # The entries of robots.txt
custom = set() # Strings extracted by custom regex pattern
failed = set() # URLs that photon failed to crawl
scripts = set() # THe Javascript files
external = set() # URLs that don't belong to the target i.e. out-of-scope
# URLs that have get params in them e.g. example.com/page.php?id=2
fuzzable = set()
endpoints = set() # URLs found from javascript files
processed = set(['dummy']) # URLs that have been crawled
# URLs that belong to the target i.e. in-scope
internal = set(args.seeds)
everything = []
bad_scripts = set() # Unclean javascript file urls
bad_intel = set() # needed for intel filtering
core.config.verbose = verbose
if headers:
try:
prompt = prompt()
except FileNotFoundError as e:
print('Could not load headers prompt: {}'.format(e))
quit()
headers = extract_headers(prompt)
# If the user hasn't supplied the root URL with http(s), we will handle it
if main_inp.startswith('http'):
main_url = main_inp
else:
try:
requests.get('https://' + main_inp, proxies=random.choice(proxies))
main_url = 'https://' + main_inp
except:
main_url = 'http://' + main_inp
schema = main_url.split('//')[0] # https: or http:?
# Adding the root URL to internal for crawling
internal.add(main_url)
# Extracts host out of the URL
host = urlparse(main_url).netloc
output_dir = args.output or host
try:
domain = top_level(main_url)
except:
domain = host
if args.user_agent:
user_agents = args.user_agent.split(',')
else:
with open(sys.path[0] + '/core/user-agents.txt', 'r') as uas:
user_agents = [agent.strip('\n') for agent in uas]
supress_regex = False
def intel_extractor(url, response):
"""Extract intel from the response body."""
for rintel in rintels:
res = re.sub(r'<(script).*?</\1>(?s)', '', response)
res = re.sub(r'<[^<]+?>', '', res)
matches = rintel[0].findall(res)
if matches:
for match in matches:
verb('Intel', match)
bad_intel.add((match, rintel[1], url))
def js_extractor(response):
"""Extract js files from the response body"""
# Extract .js files
matches = rscript.findall(response)
for match in matches:
match = match[2].replace('\'', '').replace('"', '')
verb('JS file', match)
bad_scripts.add(match)
def remove_file(url):
if url.count('/') > 2:
replacable = re.search(r'/[^/]*?$', url).group()
if replacable != '/':
return url.replace(replacable, '')
else:
return url
else:
return url
def extractor(url):
"""Extract details from the response body."""
response = requester(url, main_url, delay, cook, headers, timeout, host, proxies, user_agents, failed, processed)
if clone:
mirror(url, response)
matches = rhref.findall(response)
for link in matches:
# Remove everything after a "#" to deal with in-page anchors
link = link[1].replace('\'', '').replace('"', '').split('#')[0]
# Checks if the URLs should be crawled
if is_link(link, processed, files):
if link[:4] == 'http':
if link.startswith(main_url):
verb('Internal page', link)
internal.add(link)
else:
verb('External page', link)
external.add(link)
elif link[:2] == '//':
if link.split('/')[2].startswith(host):
verb('Internal page', link)
internal.add(schema + '://' + link)
else:
verb('External page', link)
external.add(link)
elif link[:1] == '/':
verb('Internal page', link)
internal.add(remove_file(url) + link)
else:
verb('Internal page', link)
usable_url = remove_file(url)
if usable_url.endswith('/'):
internal.add(usable_url + link)
elif link.startswith('/'):
internal.add(usable_url + link)
else:
internal.add(usable_url + '/' + link)
if not only_urls:
intel_extractor(url, response)
js_extractor(response)
if args.regex and not supress_regex:
regxy(args.regex, response, supress_regex, custom)
if api:
matches = rentropy.findall(response)
for match in matches:
if entropy(match) >= 4:
verb('Key', match)
keys.add(url + ': ' + match)
def jscanner(url):
"""Extract endpoints from JavaScript code."""
response = requester(url, main_url, delay, cook, headers, timeout, host, proxies, user_agents, failed, processed)
# Extract URLs/endpoints
matches = rendpoint.findall(response)
# Iterate over the matches, match is a tuple
for match in matches:
# Combining the items because one of them is always empty
match = match[0] + match[1]
# Making sure it's not some JavaScript code
if not re.search(r'[}{><"\']', match) and not match == '/':
verb('JS endpoint', match)
endpoints.add(match)
# Records the time at which crawling started
then = time.time()
# Step 1. Extract urls from robots.txt & sitemap.xml
zap(main_url, args.archive, domain, host, internal, robots, proxies)
# This is so the level 1 emails are parsed as well
internal = set(remove_regex(internal, args.exclude))
# Step 2. Crawl recursively to the limit specified in "crawl_level"
for level in range(crawl_level):
# Links to crawl = (all links - already crawled links) - links not to crawl
links = remove_regex(internal - processed, args.exclude)
# If links to crawl are 0 i.e. all links have been crawled
if not links:
break
# if crawled links are somehow more than all links. Possible? ;/
elif len(internal) <= len(processed):
if len(internal) > 2 + len(args.seeds):
break
print('%s Level %i: %i URLs' % (run, level + 1, len(links)))
try:
flash(extractor, links, thread_count)
except KeyboardInterrupt:
print('')
break
if not only_urls:
for match in bad_scripts:
if match.startswith(main_url):
scripts.add(match)
elif match.startswith('/') and not match.startswith('//'):
scripts.add(main_url + match)
elif not match.startswith('http') and not match.startswith('//'):
scripts.add(main_url + '/' + match)
# Step 3. Scan the JavaScript files for endpoints
print('%s Crawling %i JavaScript files' % (run, len(scripts)))
flash(jscanner, scripts, thread_count)
for url in internal:
if '=' in url:
fuzzable.add(url)
for match, intel_name, url in bad_intel:
if isinstance(match, tuple):
for x in match: # Because "match" is a tuple
if x != '': # If the value isn't empty
if intel_name == "CREDIT_CARD":
if not luhn(match):
# garbage number
continue
intel.add("%s:%s" % (intel_name, x))
else:
if intel_name == "CREDIT_CARD":
if not luhn(match):
# garbage number
continue
intel.add("%s:%s:%s" % (url, intel_name, match))
for url in external:
try:
if top_level(url, fix_protocol=True) in INTELS:
intel.add(url)
except:
pass
# Records the time at which crawling stopped
now = time.time()
# Finds total time taken
diff = (now - then)
minutes, seconds, time_per_request = timer(diff, processed)
# Step 4. Save the results
if not os.path.exists(output_dir): # if the directory doesn't exist
os.mkdir(output_dir) # create a new directory
datasets = [files, intel, robots, custom, failed, internal, scripts,
external, fuzzable, endpoints, keys]
dataset_names = ['files', 'intel', 'robots', 'custom', 'failed', 'internal',
'scripts', 'external', 'fuzzable', 'endpoints', 'keys']
writer(datasets, dataset_names, output_dir)
# Printing out results
print(('%s-%s' % (red, end)) * 50)
for dataset, dataset_name in zip(datasets, dataset_names):
if dataset:
print('%s %s: %s' % (good, dataset_name.capitalize(), len(dataset)))
print(('%s-%s' % (red, end)) * 50)
print('%s Total requests made: %i' % (info, len(processed)))
print('%s Total time taken: %i minutes %i seconds' % (info, minutes, seconds))
print('%s Requests per second: %i' % (info, int(len(processed) / diff)))
datasets = {
'files': list(files), 'intel': list(intel), 'robots': list(robots),
'custom': list(custom), 'failed': list(failed), 'internal': list(internal),
'scripts': list(scripts), 'external': list(external),
'fuzzable': list(fuzzable), 'endpoints': list(endpoints),
'keys': list(keys)
}
if args.dns:
print('%s Enumerating subdomains' % run)
from plugins.find_subdomains import find_subdomains
subdomains = find_subdomains(domain)
print('%s %i subdomains found' % (info, len(subdomains)))
writer([subdomains], ['subdomains'], output_dir)
datasets['subdomains'] = subdomains
from plugins.dnsdumpster import dnsdumpster
print('%s Generating DNS map' % run)
dnsdumpster(domain, output_dir)
if args.export:
from plugins.exporter import exporter
# exporter(directory, format, datasets)
exporter(output_dir, args.export, datasets)
print('%s Results saved in %s%s%s directory' % (good, green, output_dir, end))
if args.std:
for string in datasets[args.std]:
sys.stdout.write(string + '\n')
|
s0md3v/Photon | photon.py | jscanner | python | def jscanner(url):
"""Extract endpoints from JavaScript code."""
response = requester(url, main_url, delay, cook, headers, timeout, host, proxies, user_agents, failed, processed)
# Extract URLs/endpoints
matches = rendpoint.findall(response)
# Iterate over the matches, match is a tuple
for match in matches:
# Combining the items because one of them is always empty
match = match[0] + match[1]
# Making sure it's not some JavaScript code
if not re.search(r'[}{><"\']', match) and not match == '/':
verb('JS endpoint', match)
endpoints.add(match) | Extract endpoints from JavaScript code. | train | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/photon.py#L290-L302 | [
"def requester(\n url,\n main_url=None,\n delay=0,\n cook=None,\n headers=None,\n timeout=10,\n host=None,\n proxies=[None],\n user_agents=[None],\n failed=None,\n processed=None\n ):\n \"\"\"Handle the requests and return the response body.\"\"\"\n cook = cook or set()\n headers = headers or set()\n user_agents = user_agents or ['Photon']\n failed = failed or set()\n processed = processed or set()\n # Mark the URL as crawled\n processed.add(url)\n # Pause/sleep the program for specified time\n time.sleep(delay)\n\n def make_request(url):\n \"\"\"Default request\"\"\"\n final_headers = headers or {\n 'Host': host,\n # Selecting a random user-agent\n 'User-Agent': random.choice(user_agents),\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Language': 'en-US,en;q=0.5',\n 'Accept-Encoding': 'gzip',\n 'DNT': '1',\n 'Connection': 'close',\n }\n try:\n response = SESSION.get(\n url,\n cookies=cook,\n headers=final_headers,\n verify=False,\n timeout=timeout,\n stream=True,\n proxies=random.choice(proxies)\n )\n except TooManyRedirects:\n return 'dummy'\n\n if 'text/html' in response.headers['content-type'] or \\\n 'text/plain' in response.headers['content-type']:\n if response.status_code != '404':\n return response.text\n else:\n response.close()\n failed.add(url)\n return 'dummy'\n else:\n response.close()\n return 'dummy'\n\n return make_request(url)\n"
] | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""The Photon main part."""
from __future__ import print_function
import argparse
import os
import re
import requests
import sys
import time
import warnings
import random
from core.colors import good, info, run, green, red, white, end, bad
# Just a fancy ass banner
print('''%s ____ __ __
/ %s__%s \/ /_ ____ / /_____ ____
/ %s/_/%s / __ \/ %s__%s \/ __/ %s__%s \/ __ \\
/ ____/ / / / %s/_/%s / /_/ %s/_/%s / / / /
/_/ /_/ /_/\____/\__/\____/_/ /_/ %sv1.3.2%s\n''' %
(red, white, red, white, red, white, red, white, red, white, red, white,
red, white, end))
try:
from urllib.parse import urlparse # For Python 3
except ImportError:
print('%s Photon runs only on Python 3.2 and above.' % info)
quit()
import core.config
from core.config import INTELS
from core.flash import flash
from core.mirror import mirror
from core.prompt import prompt
from core.requester import requester
from core.updater import updater
from core.utils import (luhn,
proxy_type,
is_good_proxy,
top_level,
extract_headers,
verb, is_link,
entropy, regxy,
remove_regex,
timer,
writer)
from core.regex import rintels, rendpoint, rhref, rscript, rentropy
from core.zap import zap
# Disable SSL related warnings
warnings.filterwarnings('ignore')
# Processing command line arguments
parser = argparse.ArgumentParser()
# Options
parser.add_argument('-u', '--url', help='root url', dest='root')
parser.add_argument('-c', '--cookie', help='cookie', dest='cook')
parser.add_argument('-r', '--regex', help='regex pattern', dest='regex')
parser.add_argument('-e', '--export', help='export format', dest='export', choices=['csv', 'json'])
parser.add_argument('-o', '--output', help='output directory', dest='output')
parser.add_argument('-l', '--level', help='levels to crawl', dest='level',
type=int)
parser.add_argument('-t', '--threads', help='number of threads', dest='threads',
type=int)
parser.add_argument('-d', '--delay', help='delay between requests',
dest='delay', type=float)
parser.add_argument('-v', '--verbose', help='verbose output', dest='verbose',
action='store_true')
parser.add_argument('-s', '--seeds', help='additional seed URLs', dest='seeds',
nargs="+", default=[])
parser.add_argument('--stdout', help='send variables to stdout', dest='std')
parser.add_argument('--user-agent', help='custom user agent(s)',
dest='user_agent')
parser.add_argument('--exclude', help='exclude URLs matching this regex',
dest='exclude')
parser.add_argument('--timeout', help='http request timeout', dest='timeout',
type=float)
parser.add_argument('-p', '--proxy', help='Proxy server IP:PORT or DOMAIN:PORT', dest='proxies',
type=proxy_type)
# Switches
parser.add_argument('--clone', help='clone the website locally', dest='clone',
action='store_true')
parser.add_argument('--headers', help='add headers', dest='headers',
action='store_true')
parser.add_argument('--dns', help='enumerate subdomains and DNS data',
dest='dns', action='store_true')
parser.add_argument('--keys', help='find secret keys', dest='api',
action='store_true')
parser.add_argument('--update', help='update photon', dest='update',
action='store_true')
parser.add_argument('--only-urls', help='only extract URLs', dest='only_urls',
action='store_true')
parser.add_argument('--wayback', help='fetch URLs from archive.org as seeds',
dest='archive', action='store_true')
args = parser.parse_args()
# If the user has supplied --update argument
if args.update:
updater()
quit()
# If the user has supplied a URL
if args.root:
main_inp = args.root
if main_inp.endswith('/'):
# We will remove it as it can cause problems later in the code
main_inp = main_inp[:-1]
# If the user hasn't supplied an URL
else:
print('\n' + parser.format_help().lower())
quit()
clone = args.clone
headers = args.headers # prompt for headers
verbose = args.verbose # verbose output
delay = args.delay or 0 # Delay between requests
timeout = args.timeout or 6 # HTTP request timeout
cook = args.cook or None # Cookie
api = bool(args.api) # Extract high entropy strings i.e. API keys and stuff
proxies = []
if args.proxies:
print("%s Testing proxies, can take a while..." % info)
for proxy in args.proxies:
if is_good_proxy(proxy):
proxies.append(proxy)
else:
print("%s Proxy %s doesn't seem to work or timedout" %
(bad, proxy['http']))
print("%s Done" % info)
if not proxies:
print("%s no working proxies, quitting!" % bad)
exit()
else:
proxies.append(None)
crawl_level = args.level or 2 # Crawling level
thread_count = args.threads or 2 # Number of threads
only_urls = bool(args.only_urls) # Only URLs mode is off by default
# Variables we are gonna use later to store stuff
keys = set() # High entropy strings, prolly secret keys
files = set() # The pdf, css, png, etc files.
intel = set() # The email addresses, website accounts, AWS buckets etc.
robots = set() # The entries of robots.txt
custom = set() # Strings extracted by custom regex pattern
failed = set() # URLs that photon failed to crawl
scripts = set() # THe Javascript files
external = set() # URLs that don't belong to the target i.e. out-of-scope
# URLs that have get params in them e.g. example.com/page.php?id=2
fuzzable = set()
endpoints = set() # URLs found from javascript files
processed = set(['dummy']) # URLs that have been crawled
# URLs that belong to the target i.e. in-scope
internal = set(args.seeds)
everything = []
bad_scripts = set() # Unclean javascript file urls
bad_intel = set() # needed for intel filtering
core.config.verbose = verbose
if headers:
try:
prompt = prompt()
except FileNotFoundError as e:
print('Could not load headers prompt: {}'.format(e))
quit()
headers = extract_headers(prompt)
# If the user hasn't supplied the root URL with http(s), we will handle it
if main_inp.startswith('http'):
main_url = main_inp
else:
try:
requests.get('https://' + main_inp, proxies=random.choice(proxies))
main_url = 'https://' + main_inp
except:
main_url = 'http://' + main_inp
schema = main_url.split('//')[0] # https: or http:?
# Adding the root URL to internal for crawling
internal.add(main_url)
# Extracts host out of the URL
host = urlparse(main_url).netloc
output_dir = args.output or host
try:
domain = top_level(main_url)
except:
domain = host
if args.user_agent:
user_agents = args.user_agent.split(',')
else:
with open(sys.path[0] + '/core/user-agents.txt', 'r') as uas:
user_agents = [agent.strip('\n') for agent in uas]
supress_regex = False
def intel_extractor(url, response):
"""Extract intel from the response body."""
for rintel in rintels:
res = re.sub(r'<(script).*?</\1>(?s)', '', response)
res = re.sub(r'<[^<]+?>', '', res)
matches = rintel[0].findall(res)
if matches:
for match in matches:
verb('Intel', match)
bad_intel.add((match, rintel[1], url))
def js_extractor(response):
"""Extract js files from the response body"""
# Extract .js files
matches = rscript.findall(response)
for match in matches:
match = match[2].replace('\'', '').replace('"', '')
verb('JS file', match)
bad_scripts.add(match)
def remove_file(url):
if url.count('/') > 2:
replacable = re.search(r'/[^/]*?$', url).group()
if replacable != '/':
return url.replace(replacable, '')
else:
return url
else:
return url
def extractor(url):
"""Extract details from the response body."""
response = requester(url, main_url, delay, cook, headers, timeout, host, proxies, user_agents, failed, processed)
if clone:
mirror(url, response)
matches = rhref.findall(response)
for link in matches:
# Remove everything after a "#" to deal with in-page anchors
link = link[1].replace('\'', '').replace('"', '').split('#')[0]
# Checks if the URLs should be crawled
if is_link(link, processed, files):
if link[:4] == 'http':
if link.startswith(main_url):
verb('Internal page', link)
internal.add(link)
else:
verb('External page', link)
external.add(link)
elif link[:2] == '//':
if link.split('/')[2].startswith(host):
verb('Internal page', link)
internal.add(schema + '://' + link)
else:
verb('External page', link)
external.add(link)
elif link[:1] == '/':
verb('Internal page', link)
internal.add(remove_file(url) + link)
else:
verb('Internal page', link)
usable_url = remove_file(url)
if usable_url.endswith('/'):
internal.add(usable_url + link)
elif link.startswith('/'):
internal.add(usable_url + link)
else:
internal.add(usable_url + '/' + link)
if not only_urls:
intel_extractor(url, response)
js_extractor(response)
if args.regex and not supress_regex:
regxy(args.regex, response, supress_regex, custom)
if api:
matches = rentropy.findall(response)
for match in matches:
if entropy(match) >= 4:
verb('Key', match)
keys.add(url + ': ' + match)
def jscanner(url):
"""Extract endpoints from JavaScript code."""
response = requester(url, main_url, delay, cook, headers, timeout, host, proxies, user_agents, failed, processed)
# Extract URLs/endpoints
matches = rendpoint.findall(response)
# Iterate over the matches, match is a tuple
for match in matches:
# Combining the items because one of them is always empty
match = match[0] + match[1]
# Making sure it's not some JavaScript code
if not re.search(r'[}{><"\']', match) and not match == '/':
verb('JS endpoint', match)
endpoints.add(match)
# Records the time at which crawling started
then = time.time()
# Step 1. Extract urls from robots.txt & sitemap.xml
zap(main_url, args.archive, domain, host, internal, robots, proxies)
# This is so the level 1 emails are parsed as well
internal = set(remove_regex(internal, args.exclude))
# Step 2. Crawl recursively to the limit specified in "crawl_level"
for level in range(crawl_level):
# Links to crawl = (all links - already crawled links) - links not to crawl
links = remove_regex(internal - processed, args.exclude)
# If links to crawl are 0 i.e. all links have been crawled
if not links:
break
# if crawled links are somehow more than all links. Possible? ;/
elif len(internal) <= len(processed):
if len(internal) > 2 + len(args.seeds):
break
print('%s Level %i: %i URLs' % (run, level + 1, len(links)))
try:
flash(extractor, links, thread_count)
except KeyboardInterrupt:
print('')
break
if not only_urls:
for match in bad_scripts:
if match.startswith(main_url):
scripts.add(match)
elif match.startswith('/') and not match.startswith('//'):
scripts.add(main_url + match)
elif not match.startswith('http') and not match.startswith('//'):
scripts.add(main_url + '/' + match)
# Step 3. Scan the JavaScript files for endpoints
print('%s Crawling %i JavaScript files' % (run, len(scripts)))
flash(jscanner, scripts, thread_count)
for url in internal:
if '=' in url:
fuzzable.add(url)
for match, intel_name, url in bad_intel:
if isinstance(match, tuple):
for x in match: # Because "match" is a tuple
if x != '': # If the value isn't empty
if intel_name == "CREDIT_CARD":
if not luhn(match):
# garbage number
continue
intel.add("%s:%s" % (intel_name, x))
else:
if intel_name == "CREDIT_CARD":
if not luhn(match):
# garbage number
continue
intel.add("%s:%s:%s" % (url, intel_name, match))
for url in external:
try:
if top_level(url, fix_protocol=True) in INTELS:
intel.add(url)
except:
pass
# Records the time at which crawling stopped
now = time.time()
# Finds total time taken
diff = (now - then)
minutes, seconds, time_per_request = timer(diff, processed)
# Step 4. Save the results
if not os.path.exists(output_dir): # if the directory doesn't exist
os.mkdir(output_dir) # create a new directory
datasets = [files, intel, robots, custom, failed, internal, scripts,
external, fuzzable, endpoints, keys]
dataset_names = ['files', 'intel', 'robots', 'custom', 'failed', 'internal',
'scripts', 'external', 'fuzzable', 'endpoints', 'keys']
writer(datasets, dataset_names, output_dir)
# Printing out results
print(('%s-%s' % (red, end)) * 50)
for dataset, dataset_name in zip(datasets, dataset_names):
if dataset:
print('%s %s: %s' % (good, dataset_name.capitalize(), len(dataset)))
print(('%s-%s' % (red, end)) * 50)
print('%s Total requests made: %i' % (info, len(processed)))
print('%s Total time taken: %i minutes %i seconds' % (info, minutes, seconds))
print('%s Requests per second: %i' % (info, int(len(processed) / diff)))
datasets = {
'files': list(files), 'intel': list(intel), 'robots': list(robots),
'custom': list(custom), 'failed': list(failed), 'internal': list(internal),
'scripts': list(scripts), 'external': list(external),
'fuzzable': list(fuzzable), 'endpoints': list(endpoints),
'keys': list(keys)
}
if args.dns:
print('%s Enumerating subdomains' % run)
from plugins.find_subdomains import find_subdomains
subdomains = find_subdomains(domain)
print('%s %i subdomains found' % (info, len(subdomains)))
writer([subdomains], ['subdomains'], output_dir)
datasets['subdomains'] = subdomains
from plugins.dnsdumpster import dnsdumpster
print('%s Generating DNS map' % run)
dnsdumpster(domain, output_dir)
if args.export:
from plugins.exporter import exporter
# exporter(directory, format, datasets)
exporter(output_dir, args.export, datasets)
print('%s Results saved in %s%s%s directory' % (good, green, output_dir, end))
if args.std:
for string in datasets[args.std]:
sys.stdout.write(string + '\n')
|
s0md3v/Photon | core/updater.py | updater | python | def updater():
print('%s Checking for updates' % run)
# Changes must be separated by ;
changes = '''major bug fixes;removed ninja mode;dropped python < 3.2 support;fixed unicode output;proxy support;more intels'''
latest_commit = requester('https://raw.githubusercontent.com/s0md3v/Photon/master/core/updater.py', host='raw.githubusercontent.com')
# Just a hack to see if a new version is available
if changes not in latest_commit:
changelog = re.search(r"changes = '''(.*?)'''", latest_commit)
# Splitting the changes to form a list
changelog = changelog.group(1).split(';')
print('%s A new version of Photon is available.' % good)
print('%s Changes:' % info)
for change in changelog: # print changes
print('%s>%s %s' % (green, end, change))
current_path = os.getcwd().split('/') # if you know it, you know it
folder = current_path[-1] # current directory name
path = '/'.join(current_path) # current directory path
choice = input('%s Would you like to update? [Y/n] ' % que).lower()
if choice != 'n':
print('%s Updating Photon' % run)
os.system('git clone --quiet https://github.com/s0md3v/Photon %s'
% (folder))
os.system('cp -r %s/%s/* %s && rm -r %s/%s/ 2>/dev/null'
% (path, folder, path, path, folder))
print('%s Update successful!' % good)
else:
print('%s Photon is up to date!' % good) | Update the current installation.
git clones the latest version and merges it with the current directory. | train | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/core/updater.py#L8-L40 | [
"def requester(\n url,\n main_url=None,\n delay=0,\n cook=None,\n headers=None,\n timeout=10,\n host=None,\n proxies=[None],\n user_agents=[None],\n failed=None,\n processed=None\n ):\n \"\"\"Handle the requests and return the response body.\"\"\"\n cook = cook or set()\n headers = headers or set()\n user_agents = user_agents or ['Photon']\n failed = failed or set()\n processed = processed or set()\n # Mark the URL as crawled\n processed.add(url)\n # Pause/sleep the program for specified time\n time.sleep(delay)\n\n def make_request(url):\n \"\"\"Default request\"\"\"\n final_headers = headers or {\n 'Host': host,\n # Selecting a random user-agent\n 'User-Agent': random.choice(user_agents),\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Language': 'en-US,en;q=0.5',\n 'Accept-Encoding': 'gzip',\n 'DNT': '1',\n 'Connection': 'close',\n }\n try:\n response = SESSION.get(\n url,\n cookies=cook,\n headers=final_headers,\n verify=False,\n timeout=timeout,\n stream=True,\n proxies=random.choice(proxies)\n )\n except TooManyRedirects:\n return 'dummy'\n\n if 'text/html' in response.headers['content-type'] or \\\n 'text/plain' in response.headers['content-type']:\n if response.status_code != '404':\n return response.text\n else:\n response.close()\n failed.add(url)\n return 'dummy'\n else:\n response.close()\n return 'dummy'\n\n return make_request(url)\n"
] | import os
import re
from core.colors import run, que, good, green, end, info
from core.requester import requester
|
s0md3v/Photon | plugins/find_subdomains.py | find_subdomains | python | def find_subdomains(domain):
result = set()
response = get('https://findsubdomains.com/subdomains-of/' + domain).text
matches = findall(r'(?s)<div class="domains js-domain-name">(.*?)</div>', response)
for match in matches:
result.add(match.replace(' ', '').replace('\n', ''))
return list(result) | Find subdomains according to the TLD. | train | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/plugins/find_subdomains.py#L7-L14 | null | """Support for findsubdomains.com."""
from re import findall
from requests import get
|
s0md3v/Photon | core/flash.py | flash | python | def flash(function, links, thread_count):
# Convert links (set) to list
links = list(links)
threadpool = concurrent.futures.ThreadPoolExecutor(
max_workers=thread_count)
futures = (threadpool.submit(function, link) for link in links)
for i, _ in enumerate(concurrent.futures.as_completed(futures)):
if i + 1 == len(links) or (i + 1) % thread_count == 0:
print('%s Progress: %i/%i' % (info, i + 1, len(links)),
end='\r')
print('') | Process the URLs and uses a threadpool to execute a function. | train | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/core/flash.py#L6-L17 | null | from __future__ import print_function
import concurrent.futures
from core.colors import info
|
s0md3v/Photon | core/utils.py | regxy | python | def regxy(pattern, response, supress_regex, custom):
try:
matches = re.findall(r'%s' % pattern, response)
for match in matches:
verb('Custom regex', match)
custom.add(match)
except:
supress_regex = True | Extract a string based on regex pattern supplied by user. | train | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/core/utils.py#L15-L23 | [
"def verb(kind, string):\n \"\"\"Enable verbose output.\"\"\"\n if VERBOSE:\n print('%s %s: %s' % (info, kind, string))\n"
] | import requests
import math
import os.path
import re
import argparse
import tld
from core.colors import info
from core.config import VERBOSE, BAD_TYPES
from urllib.parse import urlparse
def is_link(url, processed, files):
"""
Determine whether or not a link should be crawled
A url should not be crawled if it
- Is a file
- Has already been crawled
Args:
url: str Url to be processed
processed: list[str] List of urls that have already been crawled
Returns:
bool If `url` should be crawled
"""
if url not in processed:
is_file = url.endswith(BAD_TYPES)
if is_file:
files.add(url)
return False
return True
return False
def remove_regex(urls, regex):
"""
Parse a list for non-matches to a regex.
Args:
urls: iterable of urls
regex: string regex to be parsed for
Returns:
list of strings not matching regex
"""
if not regex:
return urls
# To avoid iterating over the characters of a string
if not isinstance(urls, (list, set, tuple)):
urls = [urls]
try:
non_matching_urls = [url for url in urls if not re.search(regex, url)]
except TypeError:
return []
return non_matching_urls
def writer(datasets, dataset_names, output_dir):
"""Write the results."""
for dataset, dataset_name in zip(datasets, dataset_names):
if dataset:
filepath = output_dir + '/' + dataset_name + '.txt'
with open(filepath, 'w+') as out_file:
joined = '\n'.join(dataset)
out_file.write(str(joined.encode('utf-8').decode('utf-8')))
out_file.write('\n')
def timer(diff, processed):
"""Return the passed time."""
# Changes seconds into minutes and seconds
minutes, seconds = divmod(diff, 60)
try:
# Finds average time taken by requests
time_per_request = diff / float(len(processed))
except ZeroDivisionError:
time_per_request = 0
return minutes, seconds, time_per_request
def entropy(string):
"""Calculate the entropy of a string."""
entropy = 0
for number in range(256):
result = float(string.encode('utf-8').count(
chr(number))) / len(string.encode('utf-8'))
if result != 0:
entropy = entropy - result * math.log(result, 2)
return entropy
def xml_parser(response):
"""Extract links from .xml files."""
# Regex for extracting URLs
return re.findall(r'<loc>(.*?)</loc>', response)
def verb(kind, string):
"""Enable verbose output."""
if VERBOSE:
print('%s %s: %s' % (info, kind, string))
def extract_headers(headers):
"""This function extracts valid headers from interactive input."""
sorted_headers = {}
matches = re.findall(r'(.*):\s(.*)', headers)
for match in matches:
header = match[0]
value = match[1]
try:
if value[-1] == ',':
value = value[:-1]
sorted_headers[header] = value
except IndexError:
pass
return sorted_headers
def top_level(url, fix_protocol=True):
"""Extract the top level domain from an URL."""
ext = tld.get_tld(url, fix_protocol=fix_protocol)
toplevel = '.'.join(urlparse(url).netloc.split('.')[-2:]).split(
ext)[0] + ext
return toplevel
def is_proxy_list(v, proxies):
if os.path.isfile(v):
with open(v, 'r') as _file:
for line in _file:
line = line.strip()
if re.match(r"((http|socks5):\/\/.)?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})", line) or \
re.match(r"((http|socks5):\/\/.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}:(\d{1,5})", line):
proxies.append({"http": line,
"https": line})
else:
print("%s ignored" % line)
if proxies:
return True
return False
def proxy_type(v):
""" Match IP:PORT or DOMAIN:PORT in a losse manner """
proxies = []
if re.match(r"((http|socks5):\/\/.)?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})", v):
proxies.append({"http": v,
"https": v})
return proxies
elif re.match(r"((http|socks5):\/\/.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}:(\d{1,5})", v):
proxies.append({"http": v,
"https": v})
return proxies
elif is_proxy_list(v, proxies):
return proxies
else:
raise argparse.ArgumentTypeError(
"Proxy should follow IP:PORT or DOMAIN:PORT format")
def luhn(purported):
# sum_of_digits (index * 2)
LUHN_ODD_LOOKUP = (0, 2, 4, 6, 8, 1, 3, 5, 7, 9)
if not isinstance(purported, str):
purported = str(purported)
try:
evens = sum(int(p) for p in purported[-1::-2])
odds = sum(LUHN_ODD_LOOKUP[int(p)] for p in purported[-2::-2])
return (evens + odds) % 10 == 0
except ValueError: # Raised if an int conversion fails
return False
def is_good_proxy(pip):
try:
requests.get('http://example.com', proxies=pip, timeout=3)
except requests.exceptions.ConnectTimeout as e:
return False
except Exception as detail:
return False
return True
|
s0md3v/Photon | core/utils.py | is_link | python | def is_link(url, processed, files):
if url not in processed:
is_file = url.endswith(BAD_TYPES)
if is_file:
files.add(url)
return False
return True
return False | Determine whether or not a link should be crawled
A url should not be crawled if it
- Is a file
- Has already been crawled
Args:
url: str Url to be processed
processed: list[str] List of urls that have already been crawled
Returns:
bool If `url` should be crawled | train | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/core/utils.py#L26-L46 | null | import requests
import math
import os.path
import re
import argparse
import tld
from core.colors import info
from core.config import VERBOSE, BAD_TYPES
from urllib.parse import urlparse
def regxy(pattern, response, supress_regex, custom):
"""Extract a string based on regex pattern supplied by user."""
try:
matches = re.findall(r'%s' % pattern, response)
for match in matches:
verb('Custom regex', match)
custom.add(match)
except:
supress_regex = True
def remove_regex(urls, regex):
"""
Parse a list for non-matches to a regex.
Args:
urls: iterable of urls
regex: string regex to be parsed for
Returns:
list of strings not matching regex
"""
if not regex:
return urls
# To avoid iterating over the characters of a string
if not isinstance(urls, (list, set, tuple)):
urls = [urls]
try:
non_matching_urls = [url for url in urls if not re.search(regex, url)]
except TypeError:
return []
return non_matching_urls
def writer(datasets, dataset_names, output_dir):
"""Write the results."""
for dataset, dataset_name in zip(datasets, dataset_names):
if dataset:
filepath = output_dir + '/' + dataset_name + '.txt'
with open(filepath, 'w+') as out_file:
joined = '\n'.join(dataset)
out_file.write(str(joined.encode('utf-8').decode('utf-8')))
out_file.write('\n')
def timer(diff, processed):
"""Return the passed time."""
# Changes seconds into minutes and seconds
minutes, seconds = divmod(diff, 60)
try:
# Finds average time taken by requests
time_per_request = diff / float(len(processed))
except ZeroDivisionError:
time_per_request = 0
return minutes, seconds, time_per_request
def entropy(string):
"""Calculate the entropy of a string."""
entropy = 0
for number in range(256):
result = float(string.encode('utf-8').count(
chr(number))) / len(string.encode('utf-8'))
if result != 0:
entropy = entropy - result * math.log(result, 2)
return entropy
def xml_parser(response):
"""Extract links from .xml files."""
# Regex for extracting URLs
return re.findall(r'<loc>(.*?)</loc>', response)
def verb(kind, string):
"""Enable verbose output."""
if VERBOSE:
print('%s %s: %s' % (info, kind, string))
def extract_headers(headers):
"""This function extracts valid headers from interactive input."""
sorted_headers = {}
matches = re.findall(r'(.*):\s(.*)', headers)
for match in matches:
header = match[0]
value = match[1]
try:
if value[-1] == ',':
value = value[:-1]
sorted_headers[header] = value
except IndexError:
pass
return sorted_headers
def top_level(url, fix_protocol=True):
"""Extract the top level domain from an URL."""
ext = tld.get_tld(url, fix_protocol=fix_protocol)
toplevel = '.'.join(urlparse(url).netloc.split('.')[-2:]).split(
ext)[0] + ext
return toplevel
def is_proxy_list(v, proxies):
if os.path.isfile(v):
with open(v, 'r') as _file:
for line in _file:
line = line.strip()
if re.match(r"((http|socks5):\/\/.)?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})", line) or \
re.match(r"((http|socks5):\/\/.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}:(\d{1,5})", line):
proxies.append({"http": line,
"https": line})
else:
print("%s ignored" % line)
if proxies:
return True
return False
def proxy_type(v):
""" Match IP:PORT or DOMAIN:PORT in a losse manner """
proxies = []
if re.match(r"((http|socks5):\/\/.)?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})", v):
proxies.append({"http": v,
"https": v})
return proxies
elif re.match(r"((http|socks5):\/\/.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}:(\d{1,5})", v):
proxies.append({"http": v,
"https": v})
return proxies
elif is_proxy_list(v, proxies):
return proxies
else:
raise argparse.ArgumentTypeError(
"Proxy should follow IP:PORT or DOMAIN:PORT format")
def luhn(purported):
# sum_of_digits (index * 2)
LUHN_ODD_LOOKUP = (0, 2, 4, 6, 8, 1, 3, 5, 7, 9)
if not isinstance(purported, str):
purported = str(purported)
try:
evens = sum(int(p) for p in purported[-1::-2])
odds = sum(LUHN_ODD_LOOKUP[int(p)] for p in purported[-2::-2])
return (evens + odds) % 10 == 0
except ValueError: # Raised if an int conversion fails
return False
def is_good_proxy(pip):
try:
requests.get('http://example.com', proxies=pip, timeout=3)
except requests.exceptions.ConnectTimeout as e:
return False
except Exception as detail:
return False
return True
|
s0md3v/Photon | core/utils.py | remove_regex | python | def remove_regex(urls, regex):
if not regex:
return urls
# To avoid iterating over the characters of a string
if not isinstance(urls, (list, set, tuple)):
urls = [urls]
try:
non_matching_urls = [url for url in urls if not re.search(regex, url)]
except TypeError:
return []
return non_matching_urls | Parse a list for non-matches to a regex.
Args:
urls: iterable of urls
regex: string regex to be parsed for
Returns:
list of strings not matching regex | train | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/core/utils.py#L49-L73 | null | import requests
import math
import os.path
import re
import argparse
import tld
from core.colors import info
from core.config import VERBOSE, BAD_TYPES
from urllib.parse import urlparse
def regxy(pattern, response, supress_regex, custom):
"""Extract a string based on regex pattern supplied by user."""
try:
matches = re.findall(r'%s' % pattern, response)
for match in matches:
verb('Custom regex', match)
custom.add(match)
except:
supress_regex = True
def is_link(url, processed, files):
"""
Determine whether or not a link should be crawled
A url should not be crawled if it
- Is a file
- Has already been crawled
Args:
url: str Url to be processed
processed: list[str] List of urls that have already been crawled
Returns:
bool If `url` should be crawled
"""
if url not in processed:
is_file = url.endswith(BAD_TYPES)
if is_file:
files.add(url)
return False
return True
return False
def writer(datasets, dataset_names, output_dir):
"""Write the results."""
for dataset, dataset_name in zip(datasets, dataset_names):
if dataset:
filepath = output_dir + '/' + dataset_name + '.txt'
with open(filepath, 'w+') as out_file:
joined = '\n'.join(dataset)
out_file.write(str(joined.encode('utf-8').decode('utf-8')))
out_file.write('\n')
def timer(diff, processed):
"""Return the passed time."""
# Changes seconds into minutes and seconds
minutes, seconds = divmod(diff, 60)
try:
# Finds average time taken by requests
time_per_request = diff / float(len(processed))
except ZeroDivisionError:
time_per_request = 0
return minutes, seconds, time_per_request
def entropy(string):
"""Calculate the entropy of a string."""
entropy = 0
for number in range(256):
result = float(string.encode('utf-8').count(
chr(number))) / len(string.encode('utf-8'))
if result != 0:
entropy = entropy - result * math.log(result, 2)
return entropy
def xml_parser(response):
"""Extract links from .xml files."""
# Regex for extracting URLs
return re.findall(r'<loc>(.*?)</loc>', response)
def verb(kind, string):
"""Enable verbose output."""
if VERBOSE:
print('%s %s: %s' % (info, kind, string))
def extract_headers(headers):
"""This function extracts valid headers from interactive input."""
sorted_headers = {}
matches = re.findall(r'(.*):\s(.*)', headers)
for match in matches:
header = match[0]
value = match[1]
try:
if value[-1] == ',':
value = value[:-1]
sorted_headers[header] = value
except IndexError:
pass
return sorted_headers
def top_level(url, fix_protocol=True):
"""Extract the top level domain from an URL."""
ext = tld.get_tld(url, fix_protocol=fix_protocol)
toplevel = '.'.join(urlparse(url).netloc.split('.')[-2:]).split(
ext)[0] + ext
return toplevel
def is_proxy_list(v, proxies):
if os.path.isfile(v):
with open(v, 'r') as _file:
for line in _file:
line = line.strip()
if re.match(r"((http|socks5):\/\/.)?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})", line) or \
re.match(r"((http|socks5):\/\/.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}:(\d{1,5})", line):
proxies.append({"http": line,
"https": line})
else:
print("%s ignored" % line)
if proxies:
return True
return False
def proxy_type(v):
""" Match IP:PORT or DOMAIN:PORT in a losse manner """
proxies = []
if re.match(r"((http|socks5):\/\/.)?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})", v):
proxies.append({"http": v,
"https": v})
return proxies
elif re.match(r"((http|socks5):\/\/.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}:(\d{1,5})", v):
proxies.append({"http": v,
"https": v})
return proxies
elif is_proxy_list(v, proxies):
return proxies
else:
raise argparse.ArgumentTypeError(
"Proxy should follow IP:PORT or DOMAIN:PORT format")
def luhn(purported):
# sum_of_digits (index * 2)
LUHN_ODD_LOOKUP = (0, 2, 4, 6, 8, 1, 3, 5, 7, 9)
if not isinstance(purported, str):
purported = str(purported)
try:
evens = sum(int(p) for p in purported[-1::-2])
odds = sum(LUHN_ODD_LOOKUP[int(p)] for p in purported[-2::-2])
return (evens + odds) % 10 == 0
except ValueError: # Raised if an int conversion fails
return False
def is_good_proxy(pip):
try:
requests.get('http://example.com', proxies=pip, timeout=3)
except requests.exceptions.ConnectTimeout as e:
return False
except Exception as detail:
return False
return True
|
s0md3v/Photon | core/utils.py | writer | python | def writer(datasets, dataset_names, output_dir):
for dataset, dataset_name in zip(datasets, dataset_names):
if dataset:
filepath = output_dir + '/' + dataset_name + '.txt'
with open(filepath, 'w+') as out_file:
joined = '\n'.join(dataset)
out_file.write(str(joined.encode('utf-8').decode('utf-8')))
out_file.write('\n') | Write the results. | train | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/core/utils.py#L76-L84 | null | import requests
import math
import os.path
import re
import argparse
import tld
from core.colors import info
from core.config import VERBOSE, BAD_TYPES
from urllib.parse import urlparse
def regxy(pattern, response, supress_regex, custom):
"""Extract a string based on regex pattern supplied by user."""
try:
matches = re.findall(r'%s' % pattern, response)
for match in matches:
verb('Custom regex', match)
custom.add(match)
except:
supress_regex = True
def is_link(url, processed, files):
"""
Determine whether or not a link should be crawled
A url should not be crawled if it
- Is a file
- Has already been crawled
Args:
url: str Url to be processed
processed: list[str] List of urls that have already been crawled
Returns:
bool If `url` should be crawled
"""
if url not in processed:
is_file = url.endswith(BAD_TYPES)
if is_file:
files.add(url)
return False
return True
return False
def remove_regex(urls, regex):
"""
Parse a list for non-matches to a regex.
Args:
urls: iterable of urls
regex: string regex to be parsed for
Returns:
list of strings not matching regex
"""
if not regex:
return urls
# To avoid iterating over the characters of a string
if not isinstance(urls, (list, set, tuple)):
urls = [urls]
try:
non_matching_urls = [url for url in urls if not re.search(regex, url)]
except TypeError:
return []
return non_matching_urls
def timer(diff, processed):
"""Return the passed time."""
# Changes seconds into minutes and seconds
minutes, seconds = divmod(diff, 60)
try:
# Finds average time taken by requests
time_per_request = diff / float(len(processed))
except ZeroDivisionError:
time_per_request = 0
return minutes, seconds, time_per_request
def entropy(string):
"""Calculate the entropy of a string."""
entropy = 0
for number in range(256):
result = float(string.encode('utf-8').count(
chr(number))) / len(string.encode('utf-8'))
if result != 0:
entropy = entropy - result * math.log(result, 2)
return entropy
def xml_parser(response):
"""Extract links from .xml files."""
# Regex for extracting URLs
return re.findall(r'<loc>(.*?)</loc>', response)
def verb(kind, string):
"""Enable verbose output."""
if VERBOSE:
print('%s %s: %s' % (info, kind, string))
def extract_headers(headers):
"""This function extracts valid headers from interactive input."""
sorted_headers = {}
matches = re.findall(r'(.*):\s(.*)', headers)
for match in matches:
header = match[0]
value = match[1]
try:
if value[-1] == ',':
value = value[:-1]
sorted_headers[header] = value
except IndexError:
pass
return sorted_headers
def top_level(url, fix_protocol=True):
"""Extract the top level domain from an URL."""
ext = tld.get_tld(url, fix_protocol=fix_protocol)
toplevel = '.'.join(urlparse(url).netloc.split('.')[-2:]).split(
ext)[0] + ext
return toplevel
def is_proxy_list(v, proxies):
if os.path.isfile(v):
with open(v, 'r') as _file:
for line in _file:
line = line.strip()
if re.match(r"((http|socks5):\/\/.)?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})", line) or \
re.match(r"((http|socks5):\/\/.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}:(\d{1,5})", line):
proxies.append({"http": line,
"https": line})
else:
print("%s ignored" % line)
if proxies:
return True
return False
def proxy_type(v):
""" Match IP:PORT or DOMAIN:PORT in a losse manner """
proxies = []
if re.match(r"((http|socks5):\/\/.)?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})", v):
proxies.append({"http": v,
"https": v})
return proxies
elif re.match(r"((http|socks5):\/\/.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}:(\d{1,5})", v):
proxies.append({"http": v,
"https": v})
return proxies
elif is_proxy_list(v, proxies):
return proxies
else:
raise argparse.ArgumentTypeError(
"Proxy should follow IP:PORT or DOMAIN:PORT format")
def luhn(purported):
# sum_of_digits (index * 2)
LUHN_ODD_LOOKUP = (0, 2, 4, 6, 8, 1, 3, 5, 7, 9)
if not isinstance(purported, str):
purported = str(purported)
try:
evens = sum(int(p) for p in purported[-1::-2])
odds = sum(LUHN_ODD_LOOKUP[int(p)] for p in purported[-2::-2])
return (evens + odds) % 10 == 0
except ValueError: # Raised if an int conversion fails
return False
def is_good_proxy(pip):
try:
requests.get('http://example.com', proxies=pip, timeout=3)
except requests.exceptions.ConnectTimeout as e:
return False
except Exception as detail:
return False
return True
|
s0md3v/Photon | core/utils.py | timer | python | def timer(diff, processed):
# Changes seconds into minutes and seconds
minutes, seconds = divmod(diff, 60)
try:
# Finds average time taken by requests
time_per_request = diff / float(len(processed))
except ZeroDivisionError:
time_per_request = 0
return minutes, seconds, time_per_request | Return the passed time. | train | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/core/utils.py#L87-L96 | null | import requests
import math
import os.path
import re
import argparse
import tld
from core.colors import info
from core.config import VERBOSE, BAD_TYPES
from urllib.parse import urlparse
def regxy(pattern, response, supress_regex, custom):
"""Extract a string based on regex pattern supplied by user."""
try:
matches = re.findall(r'%s' % pattern, response)
for match in matches:
verb('Custom regex', match)
custom.add(match)
except:
supress_regex = True
def is_link(url, processed, files):
"""
Determine whether or not a link should be crawled
A url should not be crawled if it
- Is a file
- Has already been crawled
Args:
url: str Url to be processed
processed: list[str] List of urls that have already been crawled
Returns:
bool If `url` should be crawled
"""
if url not in processed:
is_file = url.endswith(BAD_TYPES)
if is_file:
files.add(url)
return False
return True
return False
def remove_regex(urls, regex):
"""
Parse a list for non-matches to a regex.
Args:
urls: iterable of urls
regex: string regex to be parsed for
Returns:
list of strings not matching regex
"""
if not regex:
return urls
# To avoid iterating over the characters of a string
if not isinstance(urls, (list, set, tuple)):
urls = [urls]
try:
non_matching_urls = [url for url in urls if not re.search(regex, url)]
except TypeError:
return []
return non_matching_urls
def writer(datasets, dataset_names, output_dir):
"""Write the results."""
for dataset, dataset_name in zip(datasets, dataset_names):
if dataset:
filepath = output_dir + '/' + dataset_name + '.txt'
with open(filepath, 'w+') as out_file:
joined = '\n'.join(dataset)
out_file.write(str(joined.encode('utf-8').decode('utf-8')))
out_file.write('\n')
def entropy(string):
"""Calculate the entropy of a string."""
entropy = 0
for number in range(256):
result = float(string.encode('utf-8').count(
chr(number))) / len(string.encode('utf-8'))
if result != 0:
entropy = entropy - result * math.log(result, 2)
return entropy
def xml_parser(response):
"""Extract links from .xml files."""
# Regex for extracting URLs
return re.findall(r'<loc>(.*?)</loc>', response)
def verb(kind, string):
"""Enable verbose output."""
if VERBOSE:
print('%s %s: %s' % (info, kind, string))
def extract_headers(headers):
"""This function extracts valid headers from interactive input."""
sorted_headers = {}
matches = re.findall(r'(.*):\s(.*)', headers)
for match in matches:
header = match[0]
value = match[1]
try:
if value[-1] == ',':
value = value[:-1]
sorted_headers[header] = value
except IndexError:
pass
return sorted_headers
def top_level(url, fix_protocol=True):
"""Extract the top level domain from an URL."""
ext = tld.get_tld(url, fix_protocol=fix_protocol)
toplevel = '.'.join(urlparse(url).netloc.split('.')[-2:]).split(
ext)[0] + ext
return toplevel
def is_proxy_list(v, proxies):
if os.path.isfile(v):
with open(v, 'r') as _file:
for line in _file:
line = line.strip()
if re.match(r"((http|socks5):\/\/.)?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})", line) or \
re.match(r"((http|socks5):\/\/.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}:(\d{1,5})", line):
proxies.append({"http": line,
"https": line})
else:
print("%s ignored" % line)
if proxies:
return True
return False
def proxy_type(v):
""" Match IP:PORT or DOMAIN:PORT in a losse manner """
proxies = []
if re.match(r"((http|socks5):\/\/.)?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})", v):
proxies.append({"http": v,
"https": v})
return proxies
elif re.match(r"((http|socks5):\/\/.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}:(\d{1,5})", v):
proxies.append({"http": v,
"https": v})
return proxies
elif is_proxy_list(v, proxies):
return proxies
else:
raise argparse.ArgumentTypeError(
"Proxy should follow IP:PORT or DOMAIN:PORT format")
def luhn(purported):
# sum_of_digits (index * 2)
LUHN_ODD_LOOKUP = (0, 2, 4, 6, 8, 1, 3, 5, 7, 9)
if not isinstance(purported, str):
purported = str(purported)
try:
evens = sum(int(p) for p in purported[-1::-2])
odds = sum(LUHN_ODD_LOOKUP[int(p)] for p in purported[-2::-2])
return (evens + odds) % 10 == 0
except ValueError: # Raised if an int conversion fails
return False
def is_good_proxy(pip):
try:
requests.get('http://example.com', proxies=pip, timeout=3)
except requests.exceptions.ConnectTimeout as e:
return False
except Exception as detail:
return False
return True
|
s0md3v/Photon | core/utils.py | entropy | python | def entropy(string):
entropy = 0
for number in range(256):
result = float(string.encode('utf-8').count(
chr(number))) / len(string.encode('utf-8'))
if result != 0:
entropy = entropy - result * math.log(result, 2)
return entropy | Calculate the entropy of a string. | train | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/core/utils.py#L99-L107 | null | import requests
import math
import os.path
import re
import argparse
import tld
from core.colors import info
from core.config import VERBOSE, BAD_TYPES
from urllib.parse import urlparse
def regxy(pattern, response, supress_regex, custom):
"""Extract a string based on regex pattern supplied by user."""
try:
matches = re.findall(r'%s' % pattern, response)
for match in matches:
verb('Custom regex', match)
custom.add(match)
except:
supress_regex = True
def is_link(url, processed, files):
"""
Determine whether or not a link should be crawled
A url should not be crawled if it
- Is a file
- Has already been crawled
Args:
url: str Url to be processed
processed: list[str] List of urls that have already been crawled
Returns:
bool If `url` should be crawled
"""
if url not in processed:
is_file = url.endswith(BAD_TYPES)
if is_file:
files.add(url)
return False
return True
return False
def remove_regex(urls, regex):
"""
Parse a list for non-matches to a regex.
Args:
urls: iterable of urls
regex: string regex to be parsed for
Returns:
list of strings not matching regex
"""
if not regex:
return urls
# To avoid iterating over the characters of a string
if not isinstance(urls, (list, set, tuple)):
urls = [urls]
try:
non_matching_urls = [url for url in urls if not re.search(regex, url)]
except TypeError:
return []
return non_matching_urls
def writer(datasets, dataset_names, output_dir):
"""Write the results."""
for dataset, dataset_name in zip(datasets, dataset_names):
if dataset:
filepath = output_dir + '/' + dataset_name + '.txt'
with open(filepath, 'w+') as out_file:
joined = '\n'.join(dataset)
out_file.write(str(joined.encode('utf-8').decode('utf-8')))
out_file.write('\n')
def timer(diff, processed):
"""Return the passed time."""
# Changes seconds into minutes and seconds
minutes, seconds = divmod(diff, 60)
try:
# Finds average time taken by requests
time_per_request = diff / float(len(processed))
except ZeroDivisionError:
time_per_request = 0
return minutes, seconds, time_per_request
def xml_parser(response):
"""Extract links from .xml files."""
# Regex for extracting URLs
return re.findall(r'<loc>(.*?)</loc>', response)
def verb(kind, string):
"""Enable verbose output."""
if VERBOSE:
print('%s %s: %s' % (info, kind, string))
def extract_headers(headers):
"""This function extracts valid headers from interactive input."""
sorted_headers = {}
matches = re.findall(r'(.*):\s(.*)', headers)
for match in matches:
header = match[0]
value = match[1]
try:
if value[-1] == ',':
value = value[:-1]
sorted_headers[header] = value
except IndexError:
pass
return sorted_headers
def top_level(url, fix_protocol=True):
"""Extract the top level domain from an URL."""
ext = tld.get_tld(url, fix_protocol=fix_protocol)
toplevel = '.'.join(urlparse(url).netloc.split('.')[-2:]).split(
ext)[0] + ext
return toplevel
def is_proxy_list(v, proxies):
if os.path.isfile(v):
with open(v, 'r') as _file:
for line in _file:
line = line.strip()
if re.match(r"((http|socks5):\/\/.)?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})", line) or \
re.match(r"((http|socks5):\/\/.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}:(\d{1,5})", line):
proxies.append({"http": line,
"https": line})
else:
print("%s ignored" % line)
if proxies:
return True
return False
def proxy_type(v):
""" Match IP:PORT or DOMAIN:PORT in a losse manner """
proxies = []
if re.match(r"((http|socks5):\/\/.)?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})", v):
proxies.append({"http": v,
"https": v})
return proxies
elif re.match(r"((http|socks5):\/\/.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}:(\d{1,5})", v):
proxies.append({"http": v,
"https": v})
return proxies
elif is_proxy_list(v, proxies):
return proxies
else:
raise argparse.ArgumentTypeError(
"Proxy should follow IP:PORT or DOMAIN:PORT format")
def luhn(purported):
# sum_of_digits (index * 2)
LUHN_ODD_LOOKUP = (0, 2, 4, 6, 8, 1, 3, 5, 7, 9)
if not isinstance(purported, str):
purported = str(purported)
try:
evens = sum(int(p) for p in purported[-1::-2])
odds = sum(LUHN_ODD_LOOKUP[int(p)] for p in purported[-2::-2])
return (evens + odds) % 10 == 0
except ValueError: # Raised if an int conversion fails
return False
def is_good_proxy(pip):
try:
requests.get('http://example.com', proxies=pip, timeout=3)
except requests.exceptions.ConnectTimeout as e:
return False
except Exception as detail:
return False
return True
|
s0md3v/Photon | core/utils.py | extract_headers | python | def extract_headers(headers):
sorted_headers = {}
matches = re.findall(r'(.*):\s(.*)', headers)
for match in matches:
header = match[0]
value = match[1]
try:
if value[-1] == ',':
value = value[:-1]
sorted_headers[header] = value
except IndexError:
pass
return sorted_headers | This function extracts valid headers from interactive input. | train | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/core/utils.py#L122-L135 | null | import requests
import math
import os.path
import re
import argparse
import tld
from core.colors import info
from core.config import VERBOSE, BAD_TYPES
from urllib.parse import urlparse
def regxy(pattern, response, supress_regex, custom):
"""Extract a string based on regex pattern supplied by user."""
try:
matches = re.findall(r'%s' % pattern, response)
for match in matches:
verb('Custom regex', match)
custom.add(match)
except:
supress_regex = True
def is_link(url, processed, files):
"""
Determine whether or not a link should be crawled
A url should not be crawled if it
- Is a file
- Has already been crawled
Args:
url: str Url to be processed
processed: list[str] List of urls that have already been crawled
Returns:
bool If `url` should be crawled
"""
if url not in processed:
is_file = url.endswith(BAD_TYPES)
if is_file:
files.add(url)
return False
return True
return False
def remove_regex(urls, regex):
"""
Parse a list for non-matches to a regex.
Args:
urls: iterable of urls
regex: string regex to be parsed for
Returns:
list of strings not matching regex
"""
if not regex:
return urls
# To avoid iterating over the characters of a string
if not isinstance(urls, (list, set, tuple)):
urls = [urls]
try:
non_matching_urls = [url for url in urls if not re.search(regex, url)]
except TypeError:
return []
return non_matching_urls
def writer(datasets, dataset_names, output_dir):
"""Write the results."""
for dataset, dataset_name in zip(datasets, dataset_names):
if dataset:
filepath = output_dir + '/' + dataset_name + '.txt'
with open(filepath, 'w+') as out_file:
joined = '\n'.join(dataset)
out_file.write(str(joined.encode('utf-8').decode('utf-8')))
out_file.write('\n')
def timer(diff, processed):
"""Return the passed time."""
# Changes seconds into minutes and seconds
minutes, seconds = divmod(diff, 60)
try:
# Finds average time taken by requests
time_per_request = diff / float(len(processed))
except ZeroDivisionError:
time_per_request = 0
return minutes, seconds, time_per_request
def entropy(string):
"""Calculate the entropy of a string."""
entropy = 0
for number in range(256):
result = float(string.encode('utf-8').count(
chr(number))) / len(string.encode('utf-8'))
if result != 0:
entropy = entropy - result * math.log(result, 2)
return entropy
def xml_parser(response):
"""Extract links from .xml files."""
# Regex for extracting URLs
return re.findall(r'<loc>(.*?)</loc>', response)
def verb(kind, string):
"""Enable verbose output."""
if VERBOSE:
print('%s %s: %s' % (info, kind, string))
def top_level(url, fix_protocol=True):
"""Extract the top level domain from an URL."""
ext = tld.get_tld(url, fix_protocol=fix_protocol)
toplevel = '.'.join(urlparse(url).netloc.split('.')[-2:]).split(
ext)[0] + ext
return toplevel
def is_proxy_list(v, proxies):
if os.path.isfile(v):
with open(v, 'r') as _file:
for line in _file:
line = line.strip()
if re.match(r"((http|socks5):\/\/.)?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})", line) or \
re.match(r"((http|socks5):\/\/.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}:(\d{1,5})", line):
proxies.append({"http": line,
"https": line})
else:
print("%s ignored" % line)
if proxies:
return True
return False
def proxy_type(v):
""" Match IP:PORT or DOMAIN:PORT in a losse manner """
proxies = []
if re.match(r"((http|socks5):\/\/.)?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})", v):
proxies.append({"http": v,
"https": v})
return proxies
elif re.match(r"((http|socks5):\/\/.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}:(\d{1,5})", v):
proxies.append({"http": v,
"https": v})
return proxies
elif is_proxy_list(v, proxies):
return proxies
else:
raise argparse.ArgumentTypeError(
"Proxy should follow IP:PORT or DOMAIN:PORT format")
def luhn(purported):
# sum_of_digits (index * 2)
LUHN_ODD_LOOKUP = (0, 2, 4, 6, 8, 1, 3, 5, 7, 9)
if not isinstance(purported, str):
purported = str(purported)
try:
evens = sum(int(p) for p in purported[-1::-2])
odds = sum(LUHN_ODD_LOOKUP[int(p)] for p in purported[-2::-2])
return (evens + odds) % 10 == 0
except ValueError: # Raised if an int conversion fails
return False
def is_good_proxy(pip):
try:
requests.get('http://example.com', proxies=pip, timeout=3)
except requests.exceptions.ConnectTimeout as e:
return False
except Exception as detail:
return False
return True
|
s0md3v/Photon | core/utils.py | top_level | python | def top_level(url, fix_protocol=True):
ext = tld.get_tld(url, fix_protocol=fix_protocol)
toplevel = '.'.join(urlparse(url).netloc.split('.')[-2:]).split(
ext)[0] + ext
return toplevel | Extract the top level domain from an URL. | train | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/core/utils.py#L138-L143 | null | import requests
import math
import os.path
import re
import argparse
import tld
from core.colors import info
from core.config import VERBOSE, BAD_TYPES
from urllib.parse import urlparse
def regxy(pattern, response, supress_regex, custom):
"""Extract a string based on regex pattern supplied by user."""
try:
matches = re.findall(r'%s' % pattern, response)
for match in matches:
verb('Custom regex', match)
custom.add(match)
except:
supress_regex = True
def is_link(url, processed, files):
"""
Determine whether or not a link should be crawled
A url should not be crawled if it
- Is a file
- Has already been crawled
Args:
url: str Url to be processed
processed: list[str] List of urls that have already been crawled
Returns:
bool If `url` should be crawled
"""
if url not in processed:
is_file = url.endswith(BAD_TYPES)
if is_file:
files.add(url)
return False
return True
return False
def remove_regex(urls, regex):
"""
Parse a list for non-matches to a regex.
Args:
urls: iterable of urls
regex: string regex to be parsed for
Returns:
list of strings not matching regex
"""
if not regex:
return urls
# To avoid iterating over the characters of a string
if not isinstance(urls, (list, set, tuple)):
urls = [urls]
try:
non_matching_urls = [url for url in urls if not re.search(regex, url)]
except TypeError:
return []
return non_matching_urls
def writer(datasets, dataset_names, output_dir):
"""Write the results."""
for dataset, dataset_name in zip(datasets, dataset_names):
if dataset:
filepath = output_dir + '/' + dataset_name + '.txt'
with open(filepath, 'w+') as out_file:
joined = '\n'.join(dataset)
out_file.write(str(joined.encode('utf-8').decode('utf-8')))
out_file.write('\n')
def timer(diff, processed):
"""Return the passed time."""
# Changes seconds into minutes and seconds
minutes, seconds = divmod(diff, 60)
try:
# Finds average time taken by requests
time_per_request = diff / float(len(processed))
except ZeroDivisionError:
time_per_request = 0
return minutes, seconds, time_per_request
def entropy(string):
"""Calculate the entropy of a string."""
entropy = 0
for number in range(256):
result = float(string.encode('utf-8').count(
chr(number))) / len(string.encode('utf-8'))
if result != 0:
entropy = entropy - result * math.log(result, 2)
return entropy
def xml_parser(response):
"""Extract links from .xml files."""
# Regex for extracting URLs
return re.findall(r'<loc>(.*?)</loc>', response)
def verb(kind, string):
"""Enable verbose output."""
if VERBOSE:
print('%s %s: %s' % (info, kind, string))
def extract_headers(headers):
"""This function extracts valid headers from interactive input."""
sorted_headers = {}
matches = re.findall(r'(.*):\s(.*)', headers)
for match in matches:
header = match[0]
value = match[1]
try:
if value[-1] == ',':
value = value[:-1]
sorted_headers[header] = value
except IndexError:
pass
return sorted_headers
def is_proxy_list(v, proxies):
if os.path.isfile(v):
with open(v, 'r') as _file:
for line in _file:
line = line.strip()
if re.match(r"((http|socks5):\/\/.)?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})", line) or \
re.match(r"((http|socks5):\/\/.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}:(\d{1,5})", line):
proxies.append({"http": line,
"https": line})
else:
print("%s ignored" % line)
if proxies:
return True
return False
def proxy_type(v):
""" Match IP:PORT or DOMAIN:PORT in a losse manner """
proxies = []
if re.match(r"((http|socks5):\/\/.)?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})", v):
proxies.append({"http": v,
"https": v})
return proxies
elif re.match(r"((http|socks5):\/\/.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}:(\d{1,5})", v):
proxies.append({"http": v,
"https": v})
return proxies
elif is_proxy_list(v, proxies):
return proxies
else:
raise argparse.ArgumentTypeError(
"Proxy should follow IP:PORT or DOMAIN:PORT format")
def luhn(purported):
# sum_of_digits (index * 2)
LUHN_ODD_LOOKUP = (0, 2, 4, 6, 8, 1, 3, 5, 7, 9)
if not isinstance(purported, str):
purported = str(purported)
try:
evens = sum(int(p) for p in purported[-1::-2])
odds = sum(LUHN_ODD_LOOKUP[int(p)] for p in purported[-2::-2])
return (evens + odds) % 10 == 0
except ValueError: # Raised if an int conversion fails
return False
def is_good_proxy(pip):
try:
requests.get('http://example.com', proxies=pip, timeout=3)
except requests.exceptions.ConnectTimeout as e:
return False
except Exception as detail:
return False
return True
|
s0md3v/Photon | core/utils.py | proxy_type | python | def proxy_type(v):
proxies = []
if re.match(r"((http|socks5):\/\/.)?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})", v):
proxies.append({"http": v,
"https": v})
return proxies
elif re.match(r"((http|socks5):\/\/.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}:(\d{1,5})", v):
proxies.append({"http": v,
"https": v})
return proxies
elif is_proxy_list(v, proxies):
return proxies
else:
raise argparse.ArgumentTypeError(
"Proxy should follow IP:PORT or DOMAIN:PORT format") | Match IP:PORT or DOMAIN:PORT in a losse manner | train | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/core/utils.py#L162-L177 | null | import requests
import math
import os.path
import re
import argparse
import tld
from core.colors import info
from core.config import VERBOSE, BAD_TYPES
from urllib.parse import urlparse
def regxy(pattern, response, supress_regex, custom):
"""Extract a string based on regex pattern supplied by user."""
try:
matches = re.findall(r'%s' % pattern, response)
for match in matches:
verb('Custom regex', match)
custom.add(match)
except:
supress_regex = True
def is_link(url, processed, files):
"""
Determine whether or not a link should be crawled
A url should not be crawled if it
- Is a file
- Has already been crawled
Args:
url: str Url to be processed
processed: list[str] List of urls that have already been crawled
Returns:
bool If `url` should be crawled
"""
if url not in processed:
is_file = url.endswith(BAD_TYPES)
if is_file:
files.add(url)
return False
return True
return False
def remove_regex(urls, regex):
"""
Parse a list for non-matches to a regex.
Args:
urls: iterable of urls
regex: string regex to be parsed for
Returns:
list of strings not matching regex
"""
if not regex:
return urls
# To avoid iterating over the characters of a string
if not isinstance(urls, (list, set, tuple)):
urls = [urls]
try:
non_matching_urls = [url for url in urls if not re.search(regex, url)]
except TypeError:
return []
return non_matching_urls
def writer(datasets, dataset_names, output_dir):
"""Write the results."""
for dataset, dataset_name in zip(datasets, dataset_names):
if dataset:
filepath = output_dir + '/' + dataset_name + '.txt'
with open(filepath, 'w+') as out_file:
joined = '\n'.join(dataset)
out_file.write(str(joined.encode('utf-8').decode('utf-8')))
out_file.write('\n')
def timer(diff, processed):
"""Return the passed time."""
# Changes seconds into minutes and seconds
minutes, seconds = divmod(diff, 60)
try:
# Finds average time taken by requests
time_per_request = diff / float(len(processed))
except ZeroDivisionError:
time_per_request = 0
return minutes, seconds, time_per_request
def entropy(string):
"""Calculate the entropy of a string."""
entropy = 0
for number in range(256):
result = float(string.encode('utf-8').count(
chr(number))) / len(string.encode('utf-8'))
if result != 0:
entropy = entropy - result * math.log(result, 2)
return entropy
def xml_parser(response):
"""Extract links from .xml files."""
# Regex for extracting URLs
return re.findall(r'<loc>(.*?)</loc>', response)
def verb(kind, string):
"""Enable verbose output."""
if VERBOSE:
print('%s %s: %s' % (info, kind, string))
def extract_headers(headers):
"""This function extracts valid headers from interactive input."""
sorted_headers = {}
matches = re.findall(r'(.*):\s(.*)', headers)
for match in matches:
header = match[0]
value = match[1]
try:
if value[-1] == ',':
value = value[:-1]
sorted_headers[header] = value
except IndexError:
pass
return sorted_headers
def top_level(url, fix_protocol=True):
"""Extract the top level domain from an URL."""
ext = tld.get_tld(url, fix_protocol=fix_protocol)
toplevel = '.'.join(urlparse(url).netloc.split('.')[-2:]).split(
ext)[0] + ext
return toplevel
def is_proxy_list(v, proxies):
if os.path.isfile(v):
with open(v, 'r') as _file:
for line in _file:
line = line.strip()
if re.match(r"((http|socks5):\/\/.)?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})", line) or \
re.match(r"((http|socks5):\/\/.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}:(\d{1,5})", line):
proxies.append({"http": line,
"https": line})
else:
print("%s ignored" % line)
if proxies:
return True
return False
def luhn(purported):
# sum_of_digits (index * 2)
LUHN_ODD_LOOKUP = (0, 2, 4, 6, 8, 1, 3, 5, 7, 9)
if not isinstance(purported, str):
purported = str(purported)
try:
evens = sum(int(p) for p in purported[-1::-2])
odds = sum(LUHN_ODD_LOOKUP[int(p)] for p in purported[-2::-2])
return (evens + odds) % 10 == 0
except ValueError: # Raised if an int conversion fails
return False
def is_good_proxy(pip):
try:
requests.get('http://example.com', proxies=pip, timeout=3)
except requests.exceptions.ConnectTimeout as e:
return False
except Exception as detail:
return False
return True
|
s0md3v/Photon | plugins/dnsdumpster.py | dnsdumpster | python | def dnsdumpster(domain, output_dir):
response = requests.Session().get('https://dnsdumpster.com/').text
csrf_token = re.search(
r"name='csrfmiddlewaretoken' value='(.*?)'", response).group(1)
cookies = {'csrftoken': csrf_token}
headers = {'Referer': 'https://dnsdumpster.com/'}
data = {'csrfmiddlewaretoken': csrf_token, 'targetip': domain}
response = requests.Session().post(
'https://dnsdumpster.com/', cookies=cookies, data=data, headers=headers)
image = requests.get('https://dnsdumpster.com/static/map/%s.png' % domain)
if image.status_code == 200:
with open('%s/%s.png' % (output_dir, domain), 'wb') as f:
f.write(image.content) | Query dnsdumpster.com. | train | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/plugins/dnsdumpster.py#L7-L22 | null | """Support for dnsdumpster.com."""
import re
import requests
|
s0md3v/Photon | core/prompt.py | prompt | python | def prompt(default=None):
editor = 'nano'
with tempfile.NamedTemporaryFile(mode='r+') as tmpfile:
if default:
tmpfile.write(default)
tmpfile.flush()
child_pid = os.fork()
is_child = child_pid == 0
if is_child:
os.execvp(editor, [editor, tmpfile.name])
else:
os.waitpid(child_pid, 0)
tmpfile.seek(0)
return tmpfile.read().strip() | Present the user a prompt. | train | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/core/prompt.py#L6-L22 | null | """Support for an input prompt."""
import os
import tempfile
|
jaseg/python-mpv | mpv.py | _mpv_coax_proptype | python | def _mpv_coax_proptype(value, proptype=str):
if type(value) is bytes:
return value;
elif type(value) is bool:
return b'yes' if value else b'no'
elif proptype in (str, int, float):
return str(proptype(value)).encode('utf-8')
else:
raise TypeError('Cannot coax value of type {} into property type {}'.format(type(value), proptype)) | Intelligently coax the given python value into something that can be understood as a proptype property. | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L400-L409 | null | # -*- coding: utf-8 -*-
# vim: ts=4 sw=4 et
#
# Python MPV library module
# Copyright (C) 2017 Sebastian Götte <code@jaseg.net>
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
# Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along with this program. If not, see
# <http://www.gnu.org/licenses/>.
#
from ctypes import *
import ctypes.util
import threading
import os
import sys
from warnings import warn
from functools import partial, wraps
import collections
import re
import traceback
if os.name == 'nt':
backend = CDLL('mpv-1.dll')
fs_enc = 'utf-8'
else:
import locale
lc, enc = locale.getlocale(locale.LC_NUMERIC)
# libmpv requires LC_NUMERIC to be set to "C". Since messing with global variables everyone else relies upon is
# still better than segfaulting, we are setting LC_NUMERIC to "C".
locale.setlocale(locale.LC_NUMERIC, 'C')
sofile = ctypes.util.find_library('mpv')
if sofile is None:
raise OSError("Cannot find libmpv in the usual places. Depending on your distro, you may try installing an "
"mpv-devel or mpv-libs package. If you have libmpv around but this script can't find it, maybe consult "
"the documentation for ctypes.util.find_library which this script uses to look up the library "
"filename.")
backend = CDLL(sofile)
fs_enc = sys.getfilesystemencoding()
class MpvHandle(c_void_p):
pass
class MpvOpenGLCbContext(c_void_p):
pass
class PropertyUnavailableError(AttributeError):
pass
class ErrorCode(object):
"""For documentation on these, see mpv's libmpv/client.h."""
SUCCESS = 0
EVENT_QUEUE_FULL = -1
NOMEM = -2
UNINITIALIZED = -3
INVALID_PARAMETER = -4
OPTION_NOT_FOUND = -5
OPTION_FORMAT = -6
OPTION_ERROR = -7
PROPERTY_NOT_FOUND = -8
PROPERTY_FORMAT = -9
PROPERTY_UNAVAILABLE = -10
PROPERTY_ERROR = -11
COMMAND = -12
EXCEPTION_DICT = {
0: None,
-1: lambda *a: MemoryError('mpv event queue full', *a),
-2: lambda *a: MemoryError('mpv cannot allocate memory', *a),
-3: lambda *a: ValueError('Uninitialized mpv handle used', *a),
-4: lambda *a: ValueError('Invalid value for mpv parameter', *a),
-5: lambda *a: AttributeError('mpv option does not exist', *a),
-6: lambda *a: TypeError('Tried to set mpv option using wrong format', *a),
-7: lambda *a: ValueError('Invalid value for mpv option', *a),
-8: lambda *a: AttributeError('mpv property does not exist', *a),
# Currently (mpv 0.18.1) there is a bug causing a PROPERTY_FORMAT error to be returned instead of
# INVALID_PARAMETER when setting a property-mapped option to an invalid value.
-9: lambda *a: TypeError('Tried to get/set mpv property using wrong format, or passed invalid value', *a),
-10: lambda *a: PropertyUnavailableError('mpv property is not available', *a),
-11: lambda *a: RuntimeError('Generic error getting or setting mpv property', *a),
-12: lambda *a: SystemError('Error running mpv command', *a) }
@staticmethod
def default_error_handler(ec, *args):
return ValueError(_mpv_error_string(ec).decode('utf-8'), ec, *args)
@classmethod
def raise_for_ec(kls, ec, func, *args):
ec = 0 if ec > 0 else ec
ex = kls.EXCEPTION_DICT.get(ec , kls.default_error_handler)
if ex:
raise ex(ec, *args)
class MpvFormat(c_int):
NONE = 0
STRING = 1
OSD_STRING = 2
FLAG = 3
INT64 = 4
DOUBLE = 5
NODE = 6
NODE_ARRAY = 7
NODE_MAP = 8
BYTE_ARRAY = 9
def __eq__(self, other):
return self is other or self.value == other or self.value == int(other)
def __repr__(self):
return ['NONE', 'STRING', 'OSD_STRING', 'FLAG', 'INT64', 'DOUBLE', 'NODE', 'NODE_ARRAY', 'NODE_MAP',
'BYTE_ARRAY'][self.value]
def __hash__(self):
return self.value
class MpvEventID(c_int):
NONE = 0
SHUTDOWN = 1
LOG_MESSAGE = 2
GET_PROPERTY_REPLY = 3
SET_PROPERTY_REPLY = 4
COMMAND_REPLY = 5
START_FILE = 6
END_FILE = 7
FILE_LOADED = 8
TRACKS_CHANGED = 9
TRACK_SWITCHED = 10
IDLE = 11
PAUSE = 12
UNPAUSE = 13
TICK = 14
SCRIPT_INPUT_DISPATCH = 15
CLIENT_MESSAGE = 16
VIDEO_RECONFIG = 17
AUDIO_RECONFIG = 18
METADATA_UPDATE = 19
SEEK = 20
PLAYBACK_RESTART = 21
PROPERTY_CHANGE = 22
CHAPTER_CHANGE = 23
ANY = ( SHUTDOWN, LOG_MESSAGE, GET_PROPERTY_REPLY, SET_PROPERTY_REPLY, COMMAND_REPLY, START_FILE, END_FILE,
FILE_LOADED, TRACKS_CHANGED, TRACK_SWITCHED, IDLE, PAUSE, UNPAUSE, TICK, SCRIPT_INPUT_DISPATCH,
CLIENT_MESSAGE, VIDEO_RECONFIG, AUDIO_RECONFIG, METADATA_UPDATE, SEEK, PLAYBACK_RESTART, PROPERTY_CHANGE,
CHAPTER_CHANGE )
def __repr__(self):
return ['NONE', 'SHUTDOWN', 'LOG_MESSAGE', 'GET_PROPERTY_REPLY', 'SET_PROPERTY_REPLY', 'COMMAND_REPLY',
'START_FILE', 'END_FILE', 'FILE_LOADED', 'TRACKS_CHANGED', 'TRACK_SWITCHED', 'IDLE', 'PAUSE', 'UNPAUSE',
'TICK', 'SCRIPT_INPUT_DISPATCH', 'CLIENT_MESSAGE', 'VIDEO_RECONFIG', 'AUDIO_RECONFIG',
'METADATA_UPDATE', 'SEEK', 'PLAYBACK_RESTART', 'PROPERTY_CHANGE', 'CHAPTER_CHANGE'][self.value]
@classmethod
def from_str(kls, s):
return getattr(kls, s.upper().replace('-', '_'))
identity_decoder = lambda b: b
strict_decoder = lambda b: b.decode('utf-8')
def lazy_decoder(b):
try:
return b.decode('utf-8')
except UnicodeDecodeError:
return b
class MpvNodeList(Structure):
def array_value(self, decoder=identity_decoder):
return [ self.values[i].node_value(decoder) for i in range(self.num) ]
def dict_value(self, decoder=identity_decoder):
return { self.keys[i].decode('utf-8'):
self.values[i].node_value(decoder) for i in range(self.num) }
class MpvByteArray(Structure):
_fields_ = [('data', c_void_p),
('size', c_size_t)]
def bytes_value(self):
return cast(self.data, POINTER(c_char))[:self.size]
class MpvNode(Structure):
def node_value(self, decoder=identity_decoder):
return MpvNode.node_cast_value(self.val, self.format.value, decoder)
@staticmethod
def node_cast_value(v, fmt=MpvFormat.NODE, decoder=identity_decoder):
if fmt == MpvFormat.NONE:
return None
elif fmt == MpvFormat.STRING:
return decoder(v.string)
elif fmt == MpvFormat.OSD_STRING:
return v.string.decode('utf-8')
elif fmt == MpvFormat.FLAG:
return bool(v.flag)
elif fmt == MpvFormat.INT64:
return v.int64
elif fmt == MpvFormat.DOUBLE:
return v.double
else:
if not v.node: # Check for null pointer
return None
if fmt == MpvFormat.NODE:
return v.node.contents.node_value(decoder)
elif fmt == MpvFormat.NODE_ARRAY:
return v.list.contents.array_value(decoder)
elif fmt == MpvFormat.NODE_MAP:
return v.map.contents.dict_value(decoder)
elif fmt == MpvFormat.BYTE_ARRAY:
return v.byte_array.contents.bytes_value()
else:
raise TypeError('Unknown MPV node format {}. Please submit a bug report.'.format(fmt))
class MpvNodeUnion(Union):
_fields_ = [('string', c_char_p),
('flag', c_int),
('int64', c_int64),
('double', c_double),
('node', POINTER(MpvNode)),
('list', POINTER(MpvNodeList)),
('map', POINTER(MpvNodeList)),
('byte_array', POINTER(MpvByteArray))]
MpvNode._fields_ = [('val', MpvNodeUnion),
('format', MpvFormat)]
MpvNodeList._fields_ = [('num', c_int),
('values', POINTER(MpvNode)),
('keys', POINTER(c_char_p))]
class MpvSubApi(c_int):
MPV_SUB_API_OPENGL_CB = 1
class MpvEvent(Structure):
_fields_ = [('event_id', MpvEventID),
('error', c_int),
('reply_userdata', c_ulonglong),
('data', c_void_p)]
def as_dict(self, decoder=identity_decoder):
dtype = {MpvEventID.END_FILE: MpvEventEndFile,
MpvEventID.PROPERTY_CHANGE: MpvEventProperty,
MpvEventID.GET_PROPERTY_REPLY: MpvEventProperty,
MpvEventID.LOG_MESSAGE: MpvEventLogMessage,
MpvEventID.SCRIPT_INPUT_DISPATCH: MpvEventScriptInputDispatch,
MpvEventID.CLIENT_MESSAGE: MpvEventClientMessage
}.get(self.event_id.value, None)
return {'event_id': self.event_id.value,
'error': self.error,
'reply_userdata': self.reply_userdata,
'event': cast(self.data, POINTER(dtype)).contents.as_dict(decoder=decoder) if dtype else None}
class MpvEventProperty(Structure):
_fields_ = [('name', c_char_p),
('format', MpvFormat),
('data', MpvNodeUnion)]
def as_dict(self, decoder=identity_decoder):
value = MpvNode.node_cast_value(self.data, self.format.value, decoder)
return {'name': self.name.decode('utf-8'),
'format': self.format,
'data': self.data,
'value': value}
class MpvEventLogMessage(Structure):
_fields_ = [('prefix', c_char_p),
('level', c_char_p),
('text', c_char_p)]
def as_dict(self, decoder=identity_decoder):
return { 'prefix': self.prefix.decode('utf-8'),
'level': self.level.decode('utf-8'),
'text': decoder(self.text).rstrip() }
class MpvEventEndFile(c_int):
EOF_OR_INIT_FAILURE = 0
RESTARTED = 1
ABORTED = 2
QUIT = 3
def as_dict(self, decoder=identity_decoder):
return {'reason': self.value}
class MpvEventScriptInputDispatch(Structure):
_fields_ = [('arg0', c_int),
('type', c_char_p)]
def as_dict(self, decoder=identity_decoder):
pass # TODO
class MpvEventClientMessage(Structure):
_fields_ = [('num_args', c_int),
('args', POINTER(c_char_p))]
def as_dict(self, decoder=identity_decoder):
return { 'args': [ self.args[i].decode('utf-8') for i in range(self.num_args) ] }
WakeupCallback = CFUNCTYPE(None, c_void_p)
OpenGlCbUpdateFn = CFUNCTYPE(None, c_void_p)
OpenGlCbGetProcAddrFn = CFUNCTYPE(c_void_p, c_void_p, c_char_p)
def _handle_func(name, args, restype, errcheck, ctx=MpvHandle):
func = getattr(backend, name)
func.argtypes = [ctx] + args if ctx else args
if restype is not None:
func.restype = restype
if errcheck is not None:
func.errcheck = errcheck
globals()['_'+name] = func
def bytes_free_errcheck(res, func, *args):
notnull_errcheck(res, func, *args)
rv = cast(res, c_void_p).value
_mpv_free(res)
return rv
def notnull_errcheck(res, func, *args):
if res is None:
raise RuntimeError('Underspecified error in MPV when calling {} with args {!r}: NULL pointer returned.'\
'Please consult your local debugger.'.format(func.__name__, args))
return res
ec_errcheck = ErrorCode.raise_for_ec
def _handle_gl_func(name, args=[], restype=None):
_handle_func(name, args, restype, errcheck=None, ctx=MpvOpenGLCbContext)
backend.mpv_client_api_version.restype = c_ulong
def _mpv_client_api_version():
ver = backend.mpv_client_api_version()
return ver>>16, ver&0xFFFF
backend.mpv_free.argtypes = [c_void_p]
_mpv_free = backend.mpv_free
backend.mpv_free_node_contents.argtypes = [c_void_p]
_mpv_free_node_contents = backend.mpv_free_node_contents
backend.mpv_create.restype = MpvHandle
_mpv_create = backend.mpv_create
_handle_func('mpv_create_client', [c_char_p], MpvHandle, notnull_errcheck)
_handle_func('mpv_client_name', [], c_char_p, errcheck=None)
_handle_func('mpv_initialize', [], c_int, ec_errcheck)
_handle_func('mpv_detach_destroy', [], None, errcheck=None)
_handle_func('mpv_terminate_destroy', [], None, errcheck=None)
_handle_func('mpv_load_config_file', [c_char_p], c_int, ec_errcheck)
_handle_func('mpv_get_time_us', [], c_ulonglong, errcheck=None)
_handle_func('mpv_set_option', [c_char_p, MpvFormat, c_void_p], c_int, ec_errcheck)
_handle_func('mpv_set_option_string', [c_char_p, c_char_p], c_int, ec_errcheck)
_handle_func('mpv_command', [POINTER(c_char_p)], c_int, ec_errcheck)
_handle_func('mpv_command_string', [c_char_p, c_char_p], c_int, ec_errcheck)
_handle_func('mpv_command_async', [c_ulonglong, POINTER(c_char_p)], c_int, ec_errcheck)
_handle_func('mpv_command_node', [POINTER(MpvNode), POINTER(MpvNode)], c_int, ec_errcheck)
_handle_func('mpv_command_async', [c_ulonglong, POINTER(MpvNode)], c_int, ec_errcheck)
_handle_func('mpv_set_property', [c_char_p, MpvFormat, c_void_p], c_int, ec_errcheck)
_handle_func('mpv_set_property_string', [c_char_p, c_char_p], c_int, ec_errcheck)
_handle_func('mpv_set_property_async', [c_ulonglong, c_char_p, MpvFormat,c_void_p],c_int, ec_errcheck)
_handle_func('mpv_get_property', [c_char_p, MpvFormat, c_void_p], c_int, ec_errcheck)
_handle_func('mpv_get_property_string', [c_char_p], c_void_p, bytes_free_errcheck)
_handle_func('mpv_get_property_osd_string', [c_char_p], c_void_p, bytes_free_errcheck)
_handle_func('mpv_get_property_async', [c_ulonglong, c_char_p, MpvFormat], c_int, ec_errcheck)
_handle_func('mpv_observe_property', [c_ulonglong, c_char_p, MpvFormat], c_int, ec_errcheck)
_handle_func('mpv_unobserve_property', [c_ulonglong], c_int, ec_errcheck)
_handle_func('mpv_event_name', [c_int], c_char_p, errcheck=None, ctx=None)
_handle_func('mpv_error_string', [c_int], c_char_p, errcheck=None, ctx=None)
_handle_func('mpv_request_event', [MpvEventID, c_int], c_int, ec_errcheck)
_handle_func('mpv_request_log_messages', [c_char_p], c_int, ec_errcheck)
_handle_func('mpv_wait_event', [c_double], POINTER(MpvEvent), errcheck=None)
_handle_func('mpv_wakeup', [], None, errcheck=None)
_handle_func('mpv_set_wakeup_callback', [WakeupCallback, c_void_p], None, errcheck=None)
_handle_func('mpv_get_wakeup_pipe', [], c_int, errcheck=None)
_handle_func('mpv_get_sub_api', [MpvSubApi], c_void_p, notnull_errcheck)
_handle_gl_func('mpv_opengl_cb_set_update_callback', [OpenGlCbUpdateFn, c_void_p])
_handle_gl_func('mpv_opengl_cb_init_gl', [c_char_p, OpenGlCbGetProcAddrFn, c_void_p], c_int)
_handle_gl_func('mpv_opengl_cb_draw', [c_int, c_int, c_int], c_int)
_handle_gl_func('mpv_opengl_cb_render', [c_int, c_int], c_int)
_handle_gl_func('mpv_opengl_cb_report_flip', [c_ulonglong], c_int)
_handle_gl_func('mpv_opengl_cb_uninit_gl', [], c_int)
def _make_node_str_list(l):
"""Take a list of python objects and make a MPV string node array from it.
As an example, the python list ``l = [ "foo", 23, false ]`` will result in the following MPV node object::
struct mpv_node {
.format = MPV_NODE_ARRAY,
.u.list = *(struct mpv_node_array){
.num = len(l),
.keys = NULL,
.values = struct mpv_node[len(l)] {
{ .format = MPV_NODE_STRING, .u.string = l[0] },
{ .format = MPV_NODE_STRING, .u.string = l[1] },
...
}
}
}
"""
char_ps = [ c_char_p(_mpv_coax_proptype(e, str)) for e in l ]
node_list = MpvNodeList(
num=len(l),
keys=None,
values=( MpvNode * len(l))( *[ MpvNode(
format=MpvFormat.STRING,
val=MpvNodeUnion(string=p))
for p in char_ps ]))
node = MpvNode(
format=MpvFormat.NODE_ARRAY,
val=MpvNodeUnion(list=pointer(node_list)))
return char_ps, node_list, node, cast(pointer(node), c_void_p)
def _event_generator(handle):
while True:
event = _mpv_wait_event(handle, -1).contents
if event.event_id.value == MpvEventID.NONE:
raise StopIteration()
yield event
def _event_loop(event_handle, playback_cond, event_callbacks, message_handlers, property_handlers, log_handler):
for event in _event_generator(event_handle):
try:
devent = event.as_dict(decoder=lazy_decoder) # copy data from ctypes
eid = devent['event_id']
for callback in event_callbacks:
callback(devent)
if eid in (MpvEventID.SHUTDOWN, MpvEventID.END_FILE):
with playback_cond:
playback_cond.notify_all()
if eid == MpvEventID.PROPERTY_CHANGE:
pc = devent['event']
name, value, _fmt = pc['name'], pc['value'], pc['format']
for handler in property_handlers[name]:
handler(name, value)
if eid == MpvEventID.LOG_MESSAGE and log_handler is not None:
ev = devent['event']
log_handler(ev['level'], ev['prefix'], ev['text'])
if eid == MpvEventID.CLIENT_MESSAGE:
# {'event': {'args': ['key-binding', 'foo', 'u-', 'g']}, 'reply_userdata': 0, 'error': 0, 'event_id': 16}
target, *args = devent['event']['args']
if target in message_handlers:
message_handlers[target](*args)
if eid == MpvEventID.SHUTDOWN:
_mpv_detach_destroy(event_handle)
return
except Exception as e:
traceback.print_exc()
_py_to_mpv = lambda name: name.replace('_', '-')
_mpv_to_py = lambda name: name.replace('-', '_')
class _Proxy:
def __init__(self, mpv):
super().__setattr__('mpv', mpv)
class _PropertyProxy(_Proxy):
def __dir__(self):
return super().__dir__() + [ name.replace('-', '_') for name in self.mpv.property_list ]
class _FileLocalProxy(_Proxy):
def __getitem__(self, name):
return self.mpv.__getitem__(name, file_local=True)
def __setitem__(self, name, value):
return self.mpv.__setitem__(name, value, file_local=True)
def __iter__(self):
return iter(self.mpv)
class _OSDPropertyProxy(_PropertyProxy):
def __getattr__(self, name):
return self.mpv._get_property(_py_to_mpv(name), fmt=MpvFormat.OSD_STRING)
def __setattr__(self, _name, _value):
raise AttributeError('OSD properties are read-only. Please use the regular property API for writing.')
class _DecoderPropertyProxy(_PropertyProxy):
def __init__(self, mpv, decoder):
super().__init__(mpv)
super().__setattr__('_decoder', decoder)
def __getattr__(self, name):
return self.mpv._get_property(_py_to_mpv(name), decoder=self._decoder)
def __setattr__(self, name, value):
setattr(self.mpv, _py_to_mpv(name), value)
class MPV(object):
"""See man mpv(1) for the details of the implemented commands. All mpv properties can be accessed as
``my_mpv.some_property`` and all mpv options can be accessed as ``my_mpv['some-option']``.
By default, properties are returned as decoded ``str`` and an error is thrown if the value does not contain valid
utf-8. To get a decoded ``str`` if possibly but ``bytes`` instead of an error if not, use
``my_mpv.lazy.some_property``. To always get raw ``bytes``, use ``my_mpv.raw.some_property``. To access a
property's decoded OSD value, use ``my_mpv.osd.some_property``.
To get API information on an option, use ``my_mpv.option_info('option-name')``. To get API information on a
property, use ``my_mpv.properties['property-name']``. Take care to use mpv's dashed-names instead of the
underscore_names exposed on the python object.
To make your program not barf hard the first time its used on a weird file system **always** access properties
containing file names or file tags through ``MPV.raw``. """
def __init__(self, *extra_mpv_flags, log_handler=None, start_event_thread=True, loglevel=None, **extra_mpv_opts):
"""Create an MPV instance.
Extra arguments and extra keyword arguments will be passed to mpv as options.
"""
self.handle = _mpv_create()
self._event_thread = None
_mpv_set_option_string(self.handle, b'audio-display', b'no')
istr = lambda o: ('yes' if o else 'no') if type(o) is bool else str(o)
try:
for flag in extra_mpv_flags:
_mpv_set_option_string(self.handle, flag.encode('utf-8'), b'')
for k,v in extra_mpv_opts.items():
_mpv_set_option_string(self.handle, k.replace('_', '-').encode('utf-8'), istr(v).encode('utf-8'))
finally:
_mpv_initialize(self.handle)
self.osd = _OSDPropertyProxy(self)
self.file_local = _FileLocalProxy(self)
self.raw = _DecoderPropertyProxy(self, identity_decoder)
self.strict = _DecoderPropertyProxy(self, strict_decoder)
self.lazy = _DecoderPropertyProxy(self, lazy_decoder)
self._event_callbacks = []
self._property_handlers = collections.defaultdict(lambda: [])
self._message_handlers = {}
self._key_binding_handlers = {}
self._playback_cond = threading.Condition()
self._event_handle = _mpv_create_client(self.handle, b'py_event_handler')
self._loop = partial(_event_loop, self._event_handle, self._playback_cond, self._event_callbacks,
self._message_handlers, self._property_handlers, log_handler)
if loglevel is not None or log_handler is not None:
self.set_loglevel(loglevel or 'terminal-default')
if start_event_thread:
self._event_thread = threading.Thread(target=self._loop, name='MPVEventHandlerThread')
self._event_thread.setDaemon(True)
self._event_thread.start()
else:
self._event_thread = None
def wait_for_playback(self):
"""Waits until playback of the current title is paused or done."""
with self._playback_cond:
self._playback_cond.wait()
def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True):
"""Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for
properties such as ``idle_active`` indicating the player is done with regular playback and just idling around
"""
sema = threading.Semaphore(value=0)
def observer(name, val):
if cond(val):
sema.release()
self.observe_property(name, observer)
if not level_sensitive or not cond(getattr(self, name.replace('-', '_'))):
sema.acquire()
self.unobserve_property(name, observer)
def __del__(self):
if self.handle:
self.terminate()
def terminate(self):
"""Properly terminates this player instance. Preferably use this instead of relying on python's garbage
collector to cause this to be called from the object's destructor.
"""
self.handle, handle = None, self.handle
if threading.current_thread() is self._event_thread:
# Handle special case to allow event handle to be detached.
# This is necessary since otherwise the event thread would deadlock itself.
grim_reaper = threading.Thread(target=lambda: _mpv_terminate_destroy(handle))
grim_reaper.start()
else:
_mpv_terminate_destroy(handle)
if self._event_thread:
self._event_thread.join()
def set_loglevel(self, level):
"""Set MPV's log level. This adjusts which output will be sent to this object's log handlers. If you just want
mpv's regular terminal output, you don't need to adjust this but just need to pass a log handler to the MPV
constructur such as ``MPV(log_handler=print)``.
Valid log levels are "no", "fatal", "error", "warn", "info", "v" "debug" and "trace". For details see your mpv's
client.h header file.
"""
_mpv_request_log_messages(self._event_handle, level.encode('utf-8'))
def command(self, name, *args):
"""Execute a raw command."""
args = [name.encode('utf-8')] + [ (arg if type(arg) is bytes else str(arg).encode('utf-8'))
for arg in args if arg is not None ] + [None]
_mpv_command(self.handle, (c_char_p*len(args))(*args))
def node_command(self, name, *args, decoder=strict_decoder):
_1, _2, _3, pointer = _make_node_str_list([name, *args])
out = cast(create_string_buffer(sizeof(MpvNode)), POINTER(MpvNode))
ppointer = cast(pointer, POINTER(MpvNode))
_mpv_command_node(self.handle, ppointer, out)
rv = out.contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
def seek(self, amount, reference="relative", precision="default-precise"):
"""Mapped mpv seek command, see man mpv(1)."""
self.command('seek', amount, reference, precision)
def revert_seek(self):
"""Mapped mpv revert_seek command, see man mpv(1)."""
self.command('revert_seek');
def frame_step(self):
"""Mapped mpv frame_step command, see man mpv(1)."""
self.command('frame_step')
def frame_back_step(self):
"""Mapped mpv frame_back_step command, see man mpv(1)."""
self.command('frame_back_step')
def property_add(self, name, value=1):
"""Add the given value to the property's value. On overflow or underflow, clamp the property to the maximum. If
``value`` is omitted, assume ``1``.
"""
self.command('add', name, value)
def property_multiply(self, name, factor):
"""Multiply the value of a property with a numeric factor."""
self.command('multiply', name, factor)
def cycle(self, name, direction='up'):
"""Cycle the given property. ``up`` and ``down`` set the cycle direction. On overflow, set the property back to
the minimum, on underflow set it to the maximum. If ``up`` or ``down`` is omitted, assume ``up``.
"""
self.command('cycle', name, direction)
def screenshot(self, includes='subtitles', mode='single'):
"""Mapped mpv screenshot command, see man mpv(1)."""
self.command('screenshot', includes, mode)
def screenshot_to_file(self, filename, includes='subtitles'):
"""Mapped mpv screenshot_to_file command, see man mpv(1)."""
self.command('screenshot_to_file', filename.encode(fs_enc), includes)
def screenshot_raw(self, includes='subtitles'):
"""Mapped mpv screenshot_raw command, see man mpv(1). Returns a pillow Image object."""
from PIL import Image
res = self.node_command('screenshot-raw', includes)
if res['format'] != 'bgr0':
raise ValueError('Screenshot in unknown format "{}". Currently, only bgr0 is supported.'
.format(res['format']))
img = Image.frombytes('RGBA', (res['w'], res['h']), res['data'])
b,g,r,a = img.split()
return Image.merge('RGB', (r,g,b))
def playlist_next(self, mode='weak'):
"""Mapped mpv playlist_next command, see man mpv(1)."""
self.command('playlist_next', mode)
def playlist_prev(self, mode='weak'):
"""Mapped mpv playlist_prev command, see man mpv(1)."""
self.command('playlist_prev', mode)
@staticmethod
def _encode_options(options):
return ','.join('{}={}'.format(str(key), str(val)) for key, val in options.items())
def loadfile(self, filename, mode='replace', **options):
"""Mapped mpv loadfile command, see man mpv(1)."""
self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode_options(options))
def loadlist(self, playlist, mode='replace'):
"""Mapped mpv loadlist command, see man mpv(1)."""
self.command('loadlist', playlist.encode(fs_enc), mode)
def playlist_clear(self):
"""Mapped mpv playlist_clear command, see man mpv(1)."""
self.command('playlist_clear')
def playlist_remove(self, index='current'):
"""Mapped mpv playlist_remove command, see man mpv(1)."""
self.command('playlist_remove', index)
def playlist_move(self, index1, index2):
"""Mapped mpv playlist_move command, see man mpv(1)."""
self.command('playlist_move', index1, index2)
def run(self, command, *args):
"""Mapped mpv run command, see man mpv(1)."""
self.command('run', command, *args)
def quit(self, code=None):
"""Mapped mpv quit command, see man mpv(1)."""
self.command('quit', code)
def quit_watch_later(self, code=None):
"""Mapped mpv quit_watch_later command, see man mpv(1)."""
self.command('quit_watch_later', code)
def sub_add(self, filename):
"""Mapped mpv sub_add command, see man mpv(1)."""
self.command('sub_add', filename.encode(fs_enc))
def sub_remove(self, sub_id=None):
"""Mapped mpv sub_remove command, see man mpv(1)."""
self.command('sub_remove', sub_id)
def sub_reload(self, sub_id=None):
"""Mapped mpv sub_reload command, see man mpv(1)."""
self.command('sub_reload', sub_id)
def sub_step(self, skip):
"""Mapped mpv sub_step command, see man mpv(1)."""
self.command('sub_step', skip)
def sub_seek(self, skip):
"""Mapped mpv sub_seek command, see man mpv(1)."""
self.command('sub_seek', skip)
def toggle_osd(self):
"""Mapped mpv osd command, see man mpv(1)."""
self.command('osd')
def show_text(self, string, duration='-1', level=None):
"""Mapped mpv show_text command, see man mpv(1)."""
self.command('show_text', string, duration, level)
def show_progress(self):
"""Mapped mpv show_progress command, see man mpv(1)."""
self.command('show_progress')
def discnav(self, command):
"""Mapped mpv discnav command, see man mpv(1)."""
self.command('discnav', command)
def write_watch_later_config(self):
"""Mapped mpv write_watch_later_config command, see man mpv(1)."""
self.command('write_watch_later_config')
def overlay_add(self, overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride):
"""Mapped mpv overlay_add command, see man mpv(1)."""
self.command('overlay_add', overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride)
def overlay_remove(self, overlay_id):
"""Mapped mpv overlay_remove command, see man mpv(1)."""
self.command('overlay_remove', overlay_id)
def script_message(self, *args):
"""Mapped mpv script_message command, see man mpv(1)."""
self.command('script_message', *args)
def script_message_to(self, target, *args):
"""Mapped mpv script_message_to command, see man mpv(1)."""
self.command('script_message_to', target, *args)
def observe_property(self, name, handler):
"""Register an observer on the named property. An observer is a function that is called with the new property
value every time the property's value is changed. The basic function signature is ``fun(property_name,
new_value)`` with new_value being the decoded property value as a python object. This function can be used as a
function decorator if no handler is given.
To unregister the observer, call either of ``mpv.unobserve_property(name, handler)``,
``mpv.unobserve_all_properties(handler)`` or the handler's ``unregister_mpv_properties`` attribute::
@player.observe_property('volume')
def my_handler(new_volume, *):
print("It's loud!", volume)
my_handler.unregister_mpv_properties()
"""
self._property_handlers[name].append(handler)
_mpv_observe_property(self._event_handle, hash(name)&0xffffffffffffffff, name.encode('utf-8'), MpvFormat.NODE)
def property_observer(self, name):
"""Function decorator to register a property observer. See ``MPV.observe_property`` for details."""
def wrapper(fun):
self.observe_property(name, fun)
fun.unobserve_mpv_properties = lambda: self.unobserve_property(name, fun)
return fun
return wrapper
def unobserve_property(self, name, handler):
"""Unregister a property observer. This requires both the observed property's name and the handler function that
was originally registered as one handler could be registered for several properties. To unregister a handler
from *all* observed properties see ``unobserve_all_properties``.
"""
self._property_handlers[name].remove(handler)
if not self._property_handlers[name]:
_mpv_unobserve_property(self._event_handle, hash(name)&0xffffffffffffffff)
def unobserve_all_properties(self, handler):
"""Unregister a property observer from *all* observed properties."""
for name in self._property_handlers:
self.unobserve_property(name, handler)
def register_message_handler(self, target, handler=None):
"""Register a mpv script message handler. This can be used to communicate with embedded lua scripts. Pass the
script message target name this handler should be listening to and the handler function.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
self._register_message_handler_internal(target, handler)
def _register_message_handler_internal(self, target, handler):
self._message_handlers[target] = handler
def unregister_message_handler(self, target_or_handler):
"""Unregister a mpv script message handler for the given script message target name.
You can also call the ``unregister_mpv_messages`` function attribute set on the handler function when it is
registered.
"""
if isinstance(target_or_handler, str):
del self._message_handlers[target_or_handler]
else:
for key, val in self._message_handlers.items():
if val == target_or_handler:
del self._message_handlers[key]
def message_handler(self, target):
"""Decorator to register a mpv script message handler.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
def register(handler):
self._register_message_handler_internal(target, handler)
handler.unregister_mpv_messages = lambda: self.unregister_message_handler(handler)
return handler
return register
def register_event_callback(self, callback):
"""Register a blanket event callback receiving all event types.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
self._event_callbacks.append(callback)
def unregister_event_callback(self, callback):
"""Unregiser an event callback."""
self._event_callbacks.remove(callback)
def event_callback(self, *event_types):
"""Function decorator to register a blanket event callback for the given event types. Event types can be given
as str (e.g. 'start-file'), integer or MpvEventID object.
WARNING: Due to the way this is filtering events, this decorator cannot be chained with itself.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
def register(callback):
types = [MpvEventID.from_str(t) if isinstance(t, str) else t for t in event_types] or MpvEventID.ANY
@wraps(callback)
def wrapper(event, *args, **kwargs):
if event['event_id'] in types:
callback(event, *args, **kwargs)
self._event_callbacks.append(wrapper)
wrapper.unregister_mpv_events = partial(self.unregister_event_callback, wrapper)
return wrapper
return register
@staticmethod
def _binding_name(callback_or_cmd):
return 'py_kb_{:016x}'.format(hash(callback_or_cmd)&0xffffffffffffffff)
def on_key_press(self, keydef, mode='force'):
"""Function decorator to register a simplified key binding. The callback is called whenever the key given is
*pressed*.
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.on_key_press('Q')
def binding():
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
The BIG FAT WARNING regarding untrusted keydefs from the key_binding method applies here as well.
"""
def register(fun):
@self.key_binding(keydef, mode)
@wraps(fun)
def wrapper(state='p-', name=None):
if state[0] in ('d', 'p'):
fun()
return wrapper
return register
def key_binding(self, keydef, mode='force'):
"""Function decorator to register a low-level key binding.
The callback function signature is ``fun(key_state, key_name)`` where ``key_state`` is either ``'U'`` for "key
up" or ``'D'`` for "key down".
The keydef format is: ``[Shift+][Ctrl+][Alt+][Meta+]<key>`` where ``<key>`` is either the literal character the
key produces (ASCII or Unicode character), or a symbolic name (as printed by ``mpv --input-keylist``).
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.key_binding('Q')
def binding(state, name):
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
BIG FAT WARNING: mpv's key binding mechanism is pretty powerful. This means, you essentially get arbitrary code
exectution through key bindings. This interface makes some limited effort to sanitize the keydef given in the
first parameter, but YOU SHOULD NOT RELY ON THIS IN FOR SECURITY. If your input comes from config files, this is
completely fine--but, if you are about to pass untrusted input into this parameter, better double-check whether
this is secure in your case.
"""
def register(fun):
fun.mpv_key_bindings = getattr(fun, 'mpv_key_bindings', []) + [keydef]
def unregister_all():
for keydef in fun.mpv_key_bindings:
self.unregister_key_binding(keydef)
fun.unregister_mpv_key_bindings = unregister_all
self.register_key_binding(keydef, fun, mode)
return fun
return register
def register_key_binding(self, keydef, callback_or_cmd, mode='force'):
"""Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python
callback function. See ``MPV.key_binding`` for details.
"""
if not re.match(r'(Shift+)?(Ctrl+)?(Alt+)?(Meta+)?(.|\w+)', keydef):
raise ValueError('Invalid keydef. Expected format: [Shift+][Ctrl+][Alt+][Meta+]<key>\n'
'<key> is either the literal character the key produces (ASCII or Unicode character), or a '
'symbolic name (as printed by --input-keylist')
binding_name = MPV._binding_name(keydef)
if callable(callback_or_cmd):
self._key_binding_handlers[binding_name] = callback_or_cmd
self.register_message_handler('key-binding', self._handle_key_binding_message)
self.command('define-section',
binding_name, '{} script-binding py_event_handler/{}'.format(keydef, binding_name), mode)
elif isinstance(callback_or_cmd, str):
self.command('define-section', binding_name, '{} {}'.format(keydef, callback_or_cmd), mode)
else:
raise TypeError('register_key_binding expects either an str with an mpv command or a python callable.')
self.command('enable-section', binding_name, 'allow-hide-cursor+allow-vo-dragging')
def _handle_key_binding_message(self, binding_name, key_state, key_name=None):
self._key_binding_handlers[binding_name](key_state, key_name)
def unregister_key_binding(self, keydef):
"""Unregister a key binding by keydef."""
binding_name = MPV._binding_name(keydef)
self.command('disable-section', binding_name)
self.command('define-section', binding_name, '')
if binding_name in self._key_binding_handlers:
del self._key_binding_handlers[binding_name]
if not self._key_binding_handlers:
self.unregister_message_handler('key-binding')
# Convenience functions
def play(self, filename):
"""Play a path or URL (requires ``ytdl`` option to be set)."""
self.loadfile(filename)
@property
def playlist_filenames(self):
"""Return all playlist item file names/URLs as a list of strs."""
return [element['filename'] for element in self.playlist]
def playlist_append(self, filename, **options):
"""Append a path or URL to the playlist. This does not start playing the file automatically. To do that, use
``MPV.loadfile(filename, 'append-play')``."""
self.loadfile(filename, 'append', **options)
# Property accessors
def _get_property(self, name, decoder=strict_decoder, fmt=MpvFormat.NODE):
out = create_string_buffer(sizeof(MpvNode))
try:
cval = _mpv_get_property(self.handle, name.encode('utf-8'), fmt, out)
if fmt is MpvFormat.OSD_STRING:
return cast(out, POINTER(c_char_p)).contents.value.decode('utf-8')
elif fmt is MpvFormat.NODE:
rv = cast(out, POINTER(MpvNode)).contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
else:
raise TypeError('_get_property only supports NODE and OSD_STRING formats.')
except PropertyUnavailableError as ex:
return None
def _set_property(self, name, value):
ename = name.encode('utf-8')
if isinstance(value, (list, set, dict)):
_1, _2, _3, pointer = _make_node_str_list(value)
_mpv_set_property(self.handle, ename, MpvFormat.NODE, pointer)
else:
_mpv_set_property_string(self.handle, ename, _mpv_coax_proptype(value))
def __getattr__(self, name):
return self._get_property(_py_to_mpv(name), lazy_decoder)
def __setattr__(self, name, value):
try:
if name != 'handle' and not name.startswith('_'):
self._set_property(_py_to_mpv(name), value)
else:
super().__setattr__(name, value)
except AttributeError:
super().__setattr__(name, value)
def __dir__(self):
return super().__dir__() + [ name.replace('-', '_') for name in self.property_list ]
@property
def properties(self):
return { name: self.option_info(name) for name in self.property_list }
# Dict-like option access
def __getitem__(self, name, file_local=False):
"""Get an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._get_property(prefix+name, lazy_decoder)
def __setitem__(self, name, value, file_local=False):
"""Set an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._set_property(prefix+name, value)
def __iter__(self):
"""Iterate over all option names."""
return iter(self.options)
def option_info(self, name):
"""Get information on the given option."""
try:
return self._get_property('option-info/'+name)
except AttributeError:
return None
|
jaseg/python-mpv | mpv.py | _make_node_str_list | python | def _make_node_str_list(l):
char_ps = [ c_char_p(_mpv_coax_proptype(e, str)) for e in l ]
node_list = MpvNodeList(
num=len(l),
keys=None,
values=( MpvNode * len(l))( *[ MpvNode(
format=MpvFormat.STRING,
val=MpvNodeUnion(string=p))
for p in char_ps ]))
node = MpvNode(
format=MpvFormat.NODE_ARRAY,
val=MpvNodeUnion(list=pointer(node_list)))
return char_ps, node_list, node, cast(pointer(node), c_void_p) | Take a list of python objects and make a MPV string node array from it.
As an example, the python list ``l = [ "foo", 23, false ]`` will result in the following MPV node object::
struct mpv_node {
.format = MPV_NODE_ARRAY,
.u.list = *(struct mpv_node_array){
.num = len(l),
.keys = NULL,
.values = struct mpv_node[len(l)] {
{ .format = MPV_NODE_STRING, .u.string = l[0] },
{ .format = MPV_NODE_STRING, .u.string = l[1] },
...
}
}
} | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L411-L440 | null | # -*- coding: utf-8 -*-
# vim: ts=4 sw=4 et
#
# Python MPV library module
# Copyright (C) 2017 Sebastian Götte <code@jaseg.net>
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
# Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along with this program. If not, see
# <http://www.gnu.org/licenses/>.
#
from ctypes import *
import ctypes.util
import threading
import os
import sys
from warnings import warn
from functools import partial, wraps
import collections
import re
import traceback
if os.name == 'nt':
backend = CDLL('mpv-1.dll')
fs_enc = 'utf-8'
else:
import locale
lc, enc = locale.getlocale(locale.LC_NUMERIC)
# libmpv requires LC_NUMERIC to be set to "C". Since messing with global variables everyone else relies upon is
# still better than segfaulting, we are setting LC_NUMERIC to "C".
locale.setlocale(locale.LC_NUMERIC, 'C')
sofile = ctypes.util.find_library('mpv')
if sofile is None:
raise OSError("Cannot find libmpv in the usual places. Depending on your distro, you may try installing an "
"mpv-devel or mpv-libs package. If you have libmpv around but this script can't find it, maybe consult "
"the documentation for ctypes.util.find_library which this script uses to look up the library "
"filename.")
backend = CDLL(sofile)
fs_enc = sys.getfilesystemencoding()
class MpvHandle(c_void_p):
pass
class MpvOpenGLCbContext(c_void_p):
pass
class PropertyUnavailableError(AttributeError):
pass
class ErrorCode(object):
"""For documentation on these, see mpv's libmpv/client.h."""
SUCCESS = 0
EVENT_QUEUE_FULL = -1
NOMEM = -2
UNINITIALIZED = -3
INVALID_PARAMETER = -4
OPTION_NOT_FOUND = -5
OPTION_FORMAT = -6
OPTION_ERROR = -7
PROPERTY_NOT_FOUND = -8
PROPERTY_FORMAT = -9
PROPERTY_UNAVAILABLE = -10
PROPERTY_ERROR = -11
COMMAND = -12
EXCEPTION_DICT = {
0: None,
-1: lambda *a: MemoryError('mpv event queue full', *a),
-2: lambda *a: MemoryError('mpv cannot allocate memory', *a),
-3: lambda *a: ValueError('Uninitialized mpv handle used', *a),
-4: lambda *a: ValueError('Invalid value for mpv parameter', *a),
-5: lambda *a: AttributeError('mpv option does not exist', *a),
-6: lambda *a: TypeError('Tried to set mpv option using wrong format', *a),
-7: lambda *a: ValueError('Invalid value for mpv option', *a),
-8: lambda *a: AttributeError('mpv property does not exist', *a),
# Currently (mpv 0.18.1) there is a bug causing a PROPERTY_FORMAT error to be returned instead of
# INVALID_PARAMETER when setting a property-mapped option to an invalid value.
-9: lambda *a: TypeError('Tried to get/set mpv property using wrong format, or passed invalid value', *a),
-10: lambda *a: PropertyUnavailableError('mpv property is not available', *a),
-11: lambda *a: RuntimeError('Generic error getting or setting mpv property', *a),
-12: lambda *a: SystemError('Error running mpv command', *a) }
@staticmethod
def default_error_handler(ec, *args):
return ValueError(_mpv_error_string(ec).decode('utf-8'), ec, *args)
@classmethod
def raise_for_ec(kls, ec, func, *args):
ec = 0 if ec > 0 else ec
ex = kls.EXCEPTION_DICT.get(ec , kls.default_error_handler)
if ex:
raise ex(ec, *args)
class MpvFormat(c_int):
NONE = 0
STRING = 1
OSD_STRING = 2
FLAG = 3
INT64 = 4
DOUBLE = 5
NODE = 6
NODE_ARRAY = 7
NODE_MAP = 8
BYTE_ARRAY = 9
def __eq__(self, other):
return self is other or self.value == other or self.value == int(other)
def __repr__(self):
return ['NONE', 'STRING', 'OSD_STRING', 'FLAG', 'INT64', 'DOUBLE', 'NODE', 'NODE_ARRAY', 'NODE_MAP',
'BYTE_ARRAY'][self.value]
def __hash__(self):
return self.value
class MpvEventID(c_int):
NONE = 0
SHUTDOWN = 1
LOG_MESSAGE = 2
GET_PROPERTY_REPLY = 3
SET_PROPERTY_REPLY = 4
COMMAND_REPLY = 5
START_FILE = 6
END_FILE = 7
FILE_LOADED = 8
TRACKS_CHANGED = 9
TRACK_SWITCHED = 10
IDLE = 11
PAUSE = 12
UNPAUSE = 13
TICK = 14
SCRIPT_INPUT_DISPATCH = 15
CLIENT_MESSAGE = 16
VIDEO_RECONFIG = 17
AUDIO_RECONFIG = 18
METADATA_UPDATE = 19
SEEK = 20
PLAYBACK_RESTART = 21
PROPERTY_CHANGE = 22
CHAPTER_CHANGE = 23
ANY = ( SHUTDOWN, LOG_MESSAGE, GET_PROPERTY_REPLY, SET_PROPERTY_REPLY, COMMAND_REPLY, START_FILE, END_FILE,
FILE_LOADED, TRACKS_CHANGED, TRACK_SWITCHED, IDLE, PAUSE, UNPAUSE, TICK, SCRIPT_INPUT_DISPATCH,
CLIENT_MESSAGE, VIDEO_RECONFIG, AUDIO_RECONFIG, METADATA_UPDATE, SEEK, PLAYBACK_RESTART, PROPERTY_CHANGE,
CHAPTER_CHANGE )
def __repr__(self):
return ['NONE', 'SHUTDOWN', 'LOG_MESSAGE', 'GET_PROPERTY_REPLY', 'SET_PROPERTY_REPLY', 'COMMAND_REPLY',
'START_FILE', 'END_FILE', 'FILE_LOADED', 'TRACKS_CHANGED', 'TRACK_SWITCHED', 'IDLE', 'PAUSE', 'UNPAUSE',
'TICK', 'SCRIPT_INPUT_DISPATCH', 'CLIENT_MESSAGE', 'VIDEO_RECONFIG', 'AUDIO_RECONFIG',
'METADATA_UPDATE', 'SEEK', 'PLAYBACK_RESTART', 'PROPERTY_CHANGE', 'CHAPTER_CHANGE'][self.value]
@classmethod
def from_str(kls, s):
return getattr(kls, s.upper().replace('-', '_'))
identity_decoder = lambda b: b
strict_decoder = lambda b: b.decode('utf-8')
def lazy_decoder(b):
try:
return b.decode('utf-8')
except UnicodeDecodeError:
return b
class MpvNodeList(Structure):
def array_value(self, decoder=identity_decoder):
return [ self.values[i].node_value(decoder) for i in range(self.num) ]
def dict_value(self, decoder=identity_decoder):
return { self.keys[i].decode('utf-8'):
self.values[i].node_value(decoder) for i in range(self.num) }
class MpvByteArray(Structure):
_fields_ = [('data', c_void_p),
('size', c_size_t)]
def bytes_value(self):
return cast(self.data, POINTER(c_char))[:self.size]
class MpvNode(Structure):
def node_value(self, decoder=identity_decoder):
return MpvNode.node_cast_value(self.val, self.format.value, decoder)
@staticmethod
def node_cast_value(v, fmt=MpvFormat.NODE, decoder=identity_decoder):
if fmt == MpvFormat.NONE:
return None
elif fmt == MpvFormat.STRING:
return decoder(v.string)
elif fmt == MpvFormat.OSD_STRING:
return v.string.decode('utf-8')
elif fmt == MpvFormat.FLAG:
return bool(v.flag)
elif fmt == MpvFormat.INT64:
return v.int64
elif fmt == MpvFormat.DOUBLE:
return v.double
else:
if not v.node: # Check for null pointer
return None
if fmt == MpvFormat.NODE:
return v.node.contents.node_value(decoder)
elif fmt == MpvFormat.NODE_ARRAY:
return v.list.contents.array_value(decoder)
elif fmt == MpvFormat.NODE_MAP:
return v.map.contents.dict_value(decoder)
elif fmt == MpvFormat.BYTE_ARRAY:
return v.byte_array.contents.bytes_value()
else:
raise TypeError('Unknown MPV node format {}. Please submit a bug report.'.format(fmt))
class MpvNodeUnion(Union):
_fields_ = [('string', c_char_p),
('flag', c_int),
('int64', c_int64),
('double', c_double),
('node', POINTER(MpvNode)),
('list', POINTER(MpvNodeList)),
('map', POINTER(MpvNodeList)),
('byte_array', POINTER(MpvByteArray))]
MpvNode._fields_ = [('val', MpvNodeUnion),
('format', MpvFormat)]
MpvNodeList._fields_ = [('num', c_int),
('values', POINTER(MpvNode)),
('keys', POINTER(c_char_p))]
class MpvSubApi(c_int):
MPV_SUB_API_OPENGL_CB = 1
class MpvEvent(Structure):
_fields_ = [('event_id', MpvEventID),
('error', c_int),
('reply_userdata', c_ulonglong),
('data', c_void_p)]
def as_dict(self, decoder=identity_decoder):
dtype = {MpvEventID.END_FILE: MpvEventEndFile,
MpvEventID.PROPERTY_CHANGE: MpvEventProperty,
MpvEventID.GET_PROPERTY_REPLY: MpvEventProperty,
MpvEventID.LOG_MESSAGE: MpvEventLogMessage,
MpvEventID.SCRIPT_INPUT_DISPATCH: MpvEventScriptInputDispatch,
MpvEventID.CLIENT_MESSAGE: MpvEventClientMessage
}.get(self.event_id.value, None)
return {'event_id': self.event_id.value,
'error': self.error,
'reply_userdata': self.reply_userdata,
'event': cast(self.data, POINTER(dtype)).contents.as_dict(decoder=decoder) if dtype else None}
class MpvEventProperty(Structure):
_fields_ = [('name', c_char_p),
('format', MpvFormat),
('data', MpvNodeUnion)]
def as_dict(self, decoder=identity_decoder):
value = MpvNode.node_cast_value(self.data, self.format.value, decoder)
return {'name': self.name.decode('utf-8'),
'format': self.format,
'data': self.data,
'value': value}
class MpvEventLogMessage(Structure):
_fields_ = [('prefix', c_char_p),
('level', c_char_p),
('text', c_char_p)]
def as_dict(self, decoder=identity_decoder):
return { 'prefix': self.prefix.decode('utf-8'),
'level': self.level.decode('utf-8'),
'text': decoder(self.text).rstrip() }
class MpvEventEndFile(c_int):
EOF_OR_INIT_FAILURE = 0
RESTARTED = 1
ABORTED = 2
QUIT = 3
def as_dict(self, decoder=identity_decoder):
return {'reason': self.value}
class MpvEventScriptInputDispatch(Structure):
_fields_ = [('arg0', c_int),
('type', c_char_p)]
def as_dict(self, decoder=identity_decoder):
pass # TODO
class MpvEventClientMessage(Structure):
_fields_ = [('num_args', c_int),
('args', POINTER(c_char_p))]
def as_dict(self, decoder=identity_decoder):
return { 'args': [ self.args[i].decode('utf-8') for i in range(self.num_args) ] }
WakeupCallback = CFUNCTYPE(None, c_void_p)
OpenGlCbUpdateFn = CFUNCTYPE(None, c_void_p)
OpenGlCbGetProcAddrFn = CFUNCTYPE(c_void_p, c_void_p, c_char_p)
def _handle_func(name, args, restype, errcheck, ctx=MpvHandle):
func = getattr(backend, name)
func.argtypes = [ctx] + args if ctx else args
if restype is not None:
func.restype = restype
if errcheck is not None:
func.errcheck = errcheck
globals()['_'+name] = func
def bytes_free_errcheck(res, func, *args):
notnull_errcheck(res, func, *args)
rv = cast(res, c_void_p).value
_mpv_free(res)
return rv
def notnull_errcheck(res, func, *args):
if res is None:
raise RuntimeError('Underspecified error in MPV when calling {} with args {!r}: NULL pointer returned.'\
'Please consult your local debugger.'.format(func.__name__, args))
return res
ec_errcheck = ErrorCode.raise_for_ec
def _handle_gl_func(name, args=[], restype=None):
_handle_func(name, args, restype, errcheck=None, ctx=MpvOpenGLCbContext)
backend.mpv_client_api_version.restype = c_ulong
def _mpv_client_api_version():
ver = backend.mpv_client_api_version()
return ver>>16, ver&0xFFFF
backend.mpv_free.argtypes = [c_void_p]
_mpv_free = backend.mpv_free
backend.mpv_free_node_contents.argtypes = [c_void_p]
_mpv_free_node_contents = backend.mpv_free_node_contents
backend.mpv_create.restype = MpvHandle
_mpv_create = backend.mpv_create
_handle_func('mpv_create_client', [c_char_p], MpvHandle, notnull_errcheck)
_handle_func('mpv_client_name', [], c_char_p, errcheck=None)
_handle_func('mpv_initialize', [], c_int, ec_errcheck)
_handle_func('mpv_detach_destroy', [], None, errcheck=None)
_handle_func('mpv_terminate_destroy', [], None, errcheck=None)
_handle_func('mpv_load_config_file', [c_char_p], c_int, ec_errcheck)
_handle_func('mpv_get_time_us', [], c_ulonglong, errcheck=None)
_handle_func('mpv_set_option', [c_char_p, MpvFormat, c_void_p], c_int, ec_errcheck)
_handle_func('mpv_set_option_string', [c_char_p, c_char_p], c_int, ec_errcheck)
_handle_func('mpv_command', [POINTER(c_char_p)], c_int, ec_errcheck)
_handle_func('mpv_command_string', [c_char_p, c_char_p], c_int, ec_errcheck)
_handle_func('mpv_command_async', [c_ulonglong, POINTER(c_char_p)], c_int, ec_errcheck)
_handle_func('mpv_command_node', [POINTER(MpvNode), POINTER(MpvNode)], c_int, ec_errcheck)
_handle_func('mpv_command_async', [c_ulonglong, POINTER(MpvNode)], c_int, ec_errcheck)
_handle_func('mpv_set_property', [c_char_p, MpvFormat, c_void_p], c_int, ec_errcheck)
_handle_func('mpv_set_property_string', [c_char_p, c_char_p], c_int, ec_errcheck)
_handle_func('mpv_set_property_async', [c_ulonglong, c_char_p, MpvFormat,c_void_p],c_int, ec_errcheck)
_handle_func('mpv_get_property', [c_char_p, MpvFormat, c_void_p], c_int, ec_errcheck)
_handle_func('mpv_get_property_string', [c_char_p], c_void_p, bytes_free_errcheck)
_handle_func('mpv_get_property_osd_string', [c_char_p], c_void_p, bytes_free_errcheck)
_handle_func('mpv_get_property_async', [c_ulonglong, c_char_p, MpvFormat], c_int, ec_errcheck)
_handle_func('mpv_observe_property', [c_ulonglong, c_char_p, MpvFormat], c_int, ec_errcheck)
_handle_func('mpv_unobserve_property', [c_ulonglong], c_int, ec_errcheck)
_handle_func('mpv_event_name', [c_int], c_char_p, errcheck=None, ctx=None)
_handle_func('mpv_error_string', [c_int], c_char_p, errcheck=None, ctx=None)
_handle_func('mpv_request_event', [MpvEventID, c_int], c_int, ec_errcheck)
_handle_func('mpv_request_log_messages', [c_char_p], c_int, ec_errcheck)
_handle_func('mpv_wait_event', [c_double], POINTER(MpvEvent), errcheck=None)
_handle_func('mpv_wakeup', [], None, errcheck=None)
_handle_func('mpv_set_wakeup_callback', [WakeupCallback, c_void_p], None, errcheck=None)
_handle_func('mpv_get_wakeup_pipe', [], c_int, errcheck=None)
_handle_func('mpv_get_sub_api', [MpvSubApi], c_void_p, notnull_errcheck)
_handle_gl_func('mpv_opengl_cb_set_update_callback', [OpenGlCbUpdateFn, c_void_p])
_handle_gl_func('mpv_opengl_cb_init_gl', [c_char_p, OpenGlCbGetProcAddrFn, c_void_p], c_int)
_handle_gl_func('mpv_opengl_cb_draw', [c_int, c_int, c_int], c_int)
_handle_gl_func('mpv_opengl_cb_render', [c_int, c_int], c_int)
_handle_gl_func('mpv_opengl_cb_report_flip', [c_ulonglong], c_int)
_handle_gl_func('mpv_opengl_cb_uninit_gl', [], c_int)
def _mpv_coax_proptype(value, proptype=str):
"""Intelligently coax the given python value into something that can be understood as a proptype property."""
if type(value) is bytes:
return value;
elif type(value) is bool:
return b'yes' if value else b'no'
elif proptype in (str, int, float):
return str(proptype(value)).encode('utf-8')
else:
raise TypeError('Cannot coax value of type {} into property type {}'.format(type(value), proptype))
def _event_generator(handle):
while True:
event = _mpv_wait_event(handle, -1).contents
if event.event_id.value == MpvEventID.NONE:
raise StopIteration()
yield event
def _event_loop(event_handle, playback_cond, event_callbacks, message_handlers, property_handlers, log_handler):
for event in _event_generator(event_handle):
try:
devent = event.as_dict(decoder=lazy_decoder) # copy data from ctypes
eid = devent['event_id']
for callback in event_callbacks:
callback(devent)
if eid in (MpvEventID.SHUTDOWN, MpvEventID.END_FILE):
with playback_cond:
playback_cond.notify_all()
if eid == MpvEventID.PROPERTY_CHANGE:
pc = devent['event']
name, value, _fmt = pc['name'], pc['value'], pc['format']
for handler in property_handlers[name]:
handler(name, value)
if eid == MpvEventID.LOG_MESSAGE and log_handler is not None:
ev = devent['event']
log_handler(ev['level'], ev['prefix'], ev['text'])
if eid == MpvEventID.CLIENT_MESSAGE:
# {'event': {'args': ['key-binding', 'foo', 'u-', 'g']}, 'reply_userdata': 0, 'error': 0, 'event_id': 16}
target, *args = devent['event']['args']
if target in message_handlers:
message_handlers[target](*args)
if eid == MpvEventID.SHUTDOWN:
_mpv_detach_destroy(event_handle)
return
except Exception as e:
traceback.print_exc()
_py_to_mpv = lambda name: name.replace('_', '-')
_mpv_to_py = lambda name: name.replace('-', '_')
class _Proxy:
def __init__(self, mpv):
super().__setattr__('mpv', mpv)
class _PropertyProxy(_Proxy):
def __dir__(self):
return super().__dir__() + [ name.replace('-', '_') for name in self.mpv.property_list ]
class _FileLocalProxy(_Proxy):
def __getitem__(self, name):
return self.mpv.__getitem__(name, file_local=True)
def __setitem__(self, name, value):
return self.mpv.__setitem__(name, value, file_local=True)
def __iter__(self):
return iter(self.mpv)
class _OSDPropertyProxy(_PropertyProxy):
def __getattr__(self, name):
return self.mpv._get_property(_py_to_mpv(name), fmt=MpvFormat.OSD_STRING)
def __setattr__(self, _name, _value):
raise AttributeError('OSD properties are read-only. Please use the regular property API for writing.')
class _DecoderPropertyProxy(_PropertyProxy):
def __init__(self, mpv, decoder):
super().__init__(mpv)
super().__setattr__('_decoder', decoder)
def __getattr__(self, name):
return self.mpv._get_property(_py_to_mpv(name), decoder=self._decoder)
def __setattr__(self, name, value):
setattr(self.mpv, _py_to_mpv(name), value)
class MPV(object):
"""See man mpv(1) for the details of the implemented commands. All mpv properties can be accessed as
``my_mpv.some_property`` and all mpv options can be accessed as ``my_mpv['some-option']``.
By default, properties are returned as decoded ``str`` and an error is thrown if the value does not contain valid
utf-8. To get a decoded ``str`` if possibly but ``bytes`` instead of an error if not, use
``my_mpv.lazy.some_property``. To always get raw ``bytes``, use ``my_mpv.raw.some_property``. To access a
property's decoded OSD value, use ``my_mpv.osd.some_property``.
To get API information on an option, use ``my_mpv.option_info('option-name')``. To get API information on a
property, use ``my_mpv.properties['property-name']``. Take care to use mpv's dashed-names instead of the
underscore_names exposed on the python object.
To make your program not barf hard the first time its used on a weird file system **always** access properties
containing file names or file tags through ``MPV.raw``. """
def __init__(self, *extra_mpv_flags, log_handler=None, start_event_thread=True, loglevel=None, **extra_mpv_opts):
"""Create an MPV instance.
Extra arguments and extra keyword arguments will be passed to mpv as options.
"""
self.handle = _mpv_create()
self._event_thread = None
_mpv_set_option_string(self.handle, b'audio-display', b'no')
istr = lambda o: ('yes' if o else 'no') if type(o) is bool else str(o)
try:
for flag in extra_mpv_flags:
_mpv_set_option_string(self.handle, flag.encode('utf-8'), b'')
for k,v in extra_mpv_opts.items():
_mpv_set_option_string(self.handle, k.replace('_', '-').encode('utf-8'), istr(v).encode('utf-8'))
finally:
_mpv_initialize(self.handle)
self.osd = _OSDPropertyProxy(self)
self.file_local = _FileLocalProxy(self)
self.raw = _DecoderPropertyProxy(self, identity_decoder)
self.strict = _DecoderPropertyProxy(self, strict_decoder)
self.lazy = _DecoderPropertyProxy(self, lazy_decoder)
self._event_callbacks = []
self._property_handlers = collections.defaultdict(lambda: [])
self._message_handlers = {}
self._key_binding_handlers = {}
self._playback_cond = threading.Condition()
self._event_handle = _mpv_create_client(self.handle, b'py_event_handler')
self._loop = partial(_event_loop, self._event_handle, self._playback_cond, self._event_callbacks,
self._message_handlers, self._property_handlers, log_handler)
if loglevel is not None or log_handler is not None:
self.set_loglevel(loglevel or 'terminal-default')
if start_event_thread:
self._event_thread = threading.Thread(target=self._loop, name='MPVEventHandlerThread')
self._event_thread.setDaemon(True)
self._event_thread.start()
else:
self._event_thread = None
def wait_for_playback(self):
"""Waits until playback of the current title is paused or done."""
with self._playback_cond:
self._playback_cond.wait()
def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True):
"""Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for
properties such as ``idle_active`` indicating the player is done with regular playback and just idling around
"""
sema = threading.Semaphore(value=0)
def observer(name, val):
if cond(val):
sema.release()
self.observe_property(name, observer)
if not level_sensitive or not cond(getattr(self, name.replace('-', '_'))):
sema.acquire()
self.unobserve_property(name, observer)
def __del__(self):
if self.handle:
self.terminate()
def terminate(self):
"""Properly terminates this player instance. Preferably use this instead of relying on python's garbage
collector to cause this to be called from the object's destructor.
"""
self.handle, handle = None, self.handle
if threading.current_thread() is self._event_thread:
# Handle special case to allow event handle to be detached.
# This is necessary since otherwise the event thread would deadlock itself.
grim_reaper = threading.Thread(target=lambda: _mpv_terminate_destroy(handle))
grim_reaper.start()
else:
_mpv_terminate_destroy(handle)
if self._event_thread:
self._event_thread.join()
def set_loglevel(self, level):
"""Set MPV's log level. This adjusts which output will be sent to this object's log handlers. If you just want
mpv's regular terminal output, you don't need to adjust this but just need to pass a log handler to the MPV
constructur such as ``MPV(log_handler=print)``.
Valid log levels are "no", "fatal", "error", "warn", "info", "v" "debug" and "trace". For details see your mpv's
client.h header file.
"""
_mpv_request_log_messages(self._event_handle, level.encode('utf-8'))
def command(self, name, *args):
"""Execute a raw command."""
args = [name.encode('utf-8')] + [ (arg if type(arg) is bytes else str(arg).encode('utf-8'))
for arg in args if arg is not None ] + [None]
_mpv_command(self.handle, (c_char_p*len(args))(*args))
def node_command(self, name, *args, decoder=strict_decoder):
_1, _2, _3, pointer = _make_node_str_list([name, *args])
out = cast(create_string_buffer(sizeof(MpvNode)), POINTER(MpvNode))
ppointer = cast(pointer, POINTER(MpvNode))
_mpv_command_node(self.handle, ppointer, out)
rv = out.contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
def seek(self, amount, reference="relative", precision="default-precise"):
"""Mapped mpv seek command, see man mpv(1)."""
self.command('seek', amount, reference, precision)
def revert_seek(self):
"""Mapped mpv revert_seek command, see man mpv(1)."""
self.command('revert_seek');
def frame_step(self):
"""Mapped mpv frame_step command, see man mpv(1)."""
self.command('frame_step')
def frame_back_step(self):
"""Mapped mpv frame_back_step command, see man mpv(1)."""
self.command('frame_back_step')
def property_add(self, name, value=1):
"""Add the given value to the property's value. On overflow or underflow, clamp the property to the maximum. If
``value`` is omitted, assume ``1``.
"""
self.command('add', name, value)
def property_multiply(self, name, factor):
"""Multiply the value of a property with a numeric factor."""
self.command('multiply', name, factor)
def cycle(self, name, direction='up'):
"""Cycle the given property. ``up`` and ``down`` set the cycle direction. On overflow, set the property back to
the minimum, on underflow set it to the maximum. If ``up`` or ``down`` is omitted, assume ``up``.
"""
self.command('cycle', name, direction)
def screenshot(self, includes='subtitles', mode='single'):
"""Mapped mpv screenshot command, see man mpv(1)."""
self.command('screenshot', includes, mode)
def screenshot_to_file(self, filename, includes='subtitles'):
"""Mapped mpv screenshot_to_file command, see man mpv(1)."""
self.command('screenshot_to_file', filename.encode(fs_enc), includes)
def screenshot_raw(self, includes='subtitles'):
"""Mapped mpv screenshot_raw command, see man mpv(1). Returns a pillow Image object."""
from PIL import Image
res = self.node_command('screenshot-raw', includes)
if res['format'] != 'bgr0':
raise ValueError('Screenshot in unknown format "{}". Currently, only bgr0 is supported.'
.format(res['format']))
img = Image.frombytes('RGBA', (res['w'], res['h']), res['data'])
b,g,r,a = img.split()
return Image.merge('RGB', (r,g,b))
def playlist_next(self, mode='weak'):
"""Mapped mpv playlist_next command, see man mpv(1)."""
self.command('playlist_next', mode)
def playlist_prev(self, mode='weak'):
"""Mapped mpv playlist_prev command, see man mpv(1)."""
self.command('playlist_prev', mode)
@staticmethod
def _encode_options(options):
return ','.join('{}={}'.format(str(key), str(val)) for key, val in options.items())
def loadfile(self, filename, mode='replace', **options):
"""Mapped mpv loadfile command, see man mpv(1)."""
self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode_options(options))
def loadlist(self, playlist, mode='replace'):
"""Mapped mpv loadlist command, see man mpv(1)."""
self.command('loadlist', playlist.encode(fs_enc), mode)
def playlist_clear(self):
"""Mapped mpv playlist_clear command, see man mpv(1)."""
self.command('playlist_clear')
def playlist_remove(self, index='current'):
"""Mapped mpv playlist_remove command, see man mpv(1)."""
self.command('playlist_remove', index)
def playlist_move(self, index1, index2):
"""Mapped mpv playlist_move command, see man mpv(1)."""
self.command('playlist_move', index1, index2)
def run(self, command, *args):
"""Mapped mpv run command, see man mpv(1)."""
self.command('run', command, *args)
def quit(self, code=None):
"""Mapped mpv quit command, see man mpv(1)."""
self.command('quit', code)
def quit_watch_later(self, code=None):
"""Mapped mpv quit_watch_later command, see man mpv(1)."""
self.command('quit_watch_later', code)
def sub_add(self, filename):
"""Mapped mpv sub_add command, see man mpv(1)."""
self.command('sub_add', filename.encode(fs_enc))
def sub_remove(self, sub_id=None):
"""Mapped mpv sub_remove command, see man mpv(1)."""
self.command('sub_remove', sub_id)
def sub_reload(self, sub_id=None):
"""Mapped mpv sub_reload command, see man mpv(1)."""
self.command('sub_reload', sub_id)
def sub_step(self, skip):
"""Mapped mpv sub_step command, see man mpv(1)."""
self.command('sub_step', skip)
def sub_seek(self, skip):
"""Mapped mpv sub_seek command, see man mpv(1)."""
self.command('sub_seek', skip)
def toggle_osd(self):
"""Mapped mpv osd command, see man mpv(1)."""
self.command('osd')
def show_text(self, string, duration='-1', level=None):
"""Mapped mpv show_text command, see man mpv(1)."""
self.command('show_text', string, duration, level)
def show_progress(self):
"""Mapped mpv show_progress command, see man mpv(1)."""
self.command('show_progress')
def discnav(self, command):
"""Mapped mpv discnav command, see man mpv(1)."""
self.command('discnav', command)
def write_watch_later_config(self):
"""Mapped mpv write_watch_later_config command, see man mpv(1)."""
self.command('write_watch_later_config')
def overlay_add(self, overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride):
"""Mapped mpv overlay_add command, see man mpv(1)."""
self.command('overlay_add', overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride)
def overlay_remove(self, overlay_id):
"""Mapped mpv overlay_remove command, see man mpv(1)."""
self.command('overlay_remove', overlay_id)
def script_message(self, *args):
"""Mapped mpv script_message command, see man mpv(1)."""
self.command('script_message', *args)
def script_message_to(self, target, *args):
"""Mapped mpv script_message_to command, see man mpv(1)."""
self.command('script_message_to', target, *args)
def observe_property(self, name, handler):
"""Register an observer on the named property. An observer is a function that is called with the new property
value every time the property's value is changed. The basic function signature is ``fun(property_name,
new_value)`` with new_value being the decoded property value as a python object. This function can be used as a
function decorator if no handler is given.
To unregister the observer, call either of ``mpv.unobserve_property(name, handler)``,
``mpv.unobserve_all_properties(handler)`` or the handler's ``unregister_mpv_properties`` attribute::
@player.observe_property('volume')
def my_handler(new_volume, *):
print("It's loud!", volume)
my_handler.unregister_mpv_properties()
"""
self._property_handlers[name].append(handler)
_mpv_observe_property(self._event_handle, hash(name)&0xffffffffffffffff, name.encode('utf-8'), MpvFormat.NODE)
def property_observer(self, name):
"""Function decorator to register a property observer. See ``MPV.observe_property`` for details."""
def wrapper(fun):
self.observe_property(name, fun)
fun.unobserve_mpv_properties = lambda: self.unobserve_property(name, fun)
return fun
return wrapper
def unobserve_property(self, name, handler):
"""Unregister a property observer. This requires both the observed property's name and the handler function that
was originally registered as one handler could be registered for several properties. To unregister a handler
from *all* observed properties see ``unobserve_all_properties``.
"""
self._property_handlers[name].remove(handler)
if not self._property_handlers[name]:
_mpv_unobserve_property(self._event_handle, hash(name)&0xffffffffffffffff)
def unobserve_all_properties(self, handler):
"""Unregister a property observer from *all* observed properties."""
for name in self._property_handlers:
self.unobserve_property(name, handler)
def register_message_handler(self, target, handler=None):
"""Register a mpv script message handler. This can be used to communicate with embedded lua scripts. Pass the
script message target name this handler should be listening to and the handler function.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
self._register_message_handler_internal(target, handler)
def _register_message_handler_internal(self, target, handler):
self._message_handlers[target] = handler
def unregister_message_handler(self, target_or_handler):
"""Unregister a mpv script message handler for the given script message target name.
You can also call the ``unregister_mpv_messages`` function attribute set on the handler function when it is
registered.
"""
if isinstance(target_or_handler, str):
del self._message_handlers[target_or_handler]
else:
for key, val in self._message_handlers.items():
if val == target_or_handler:
del self._message_handlers[key]
def message_handler(self, target):
"""Decorator to register a mpv script message handler.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
def register(handler):
self._register_message_handler_internal(target, handler)
handler.unregister_mpv_messages = lambda: self.unregister_message_handler(handler)
return handler
return register
def register_event_callback(self, callback):
"""Register a blanket event callback receiving all event types.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
self._event_callbacks.append(callback)
def unregister_event_callback(self, callback):
"""Unregiser an event callback."""
self._event_callbacks.remove(callback)
def event_callback(self, *event_types):
"""Function decorator to register a blanket event callback for the given event types. Event types can be given
as str (e.g. 'start-file'), integer or MpvEventID object.
WARNING: Due to the way this is filtering events, this decorator cannot be chained with itself.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
def register(callback):
types = [MpvEventID.from_str(t) if isinstance(t, str) else t for t in event_types] or MpvEventID.ANY
@wraps(callback)
def wrapper(event, *args, **kwargs):
if event['event_id'] in types:
callback(event, *args, **kwargs)
self._event_callbacks.append(wrapper)
wrapper.unregister_mpv_events = partial(self.unregister_event_callback, wrapper)
return wrapper
return register
@staticmethod
def _binding_name(callback_or_cmd):
return 'py_kb_{:016x}'.format(hash(callback_or_cmd)&0xffffffffffffffff)
def on_key_press(self, keydef, mode='force'):
"""Function decorator to register a simplified key binding. The callback is called whenever the key given is
*pressed*.
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.on_key_press('Q')
def binding():
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
The BIG FAT WARNING regarding untrusted keydefs from the key_binding method applies here as well.
"""
def register(fun):
@self.key_binding(keydef, mode)
@wraps(fun)
def wrapper(state='p-', name=None):
if state[0] in ('d', 'p'):
fun()
return wrapper
return register
def key_binding(self, keydef, mode='force'):
"""Function decorator to register a low-level key binding.
The callback function signature is ``fun(key_state, key_name)`` where ``key_state`` is either ``'U'`` for "key
up" or ``'D'`` for "key down".
The keydef format is: ``[Shift+][Ctrl+][Alt+][Meta+]<key>`` where ``<key>`` is either the literal character the
key produces (ASCII or Unicode character), or a symbolic name (as printed by ``mpv --input-keylist``).
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.key_binding('Q')
def binding(state, name):
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
BIG FAT WARNING: mpv's key binding mechanism is pretty powerful. This means, you essentially get arbitrary code
exectution through key bindings. This interface makes some limited effort to sanitize the keydef given in the
first parameter, but YOU SHOULD NOT RELY ON THIS IN FOR SECURITY. If your input comes from config files, this is
completely fine--but, if you are about to pass untrusted input into this parameter, better double-check whether
this is secure in your case.
"""
def register(fun):
fun.mpv_key_bindings = getattr(fun, 'mpv_key_bindings', []) + [keydef]
def unregister_all():
for keydef in fun.mpv_key_bindings:
self.unregister_key_binding(keydef)
fun.unregister_mpv_key_bindings = unregister_all
self.register_key_binding(keydef, fun, mode)
return fun
return register
def register_key_binding(self, keydef, callback_or_cmd, mode='force'):
"""Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python
callback function. See ``MPV.key_binding`` for details.
"""
if not re.match(r'(Shift+)?(Ctrl+)?(Alt+)?(Meta+)?(.|\w+)', keydef):
raise ValueError('Invalid keydef. Expected format: [Shift+][Ctrl+][Alt+][Meta+]<key>\n'
'<key> is either the literal character the key produces (ASCII or Unicode character), or a '
'symbolic name (as printed by --input-keylist')
binding_name = MPV._binding_name(keydef)
if callable(callback_or_cmd):
self._key_binding_handlers[binding_name] = callback_or_cmd
self.register_message_handler('key-binding', self._handle_key_binding_message)
self.command('define-section',
binding_name, '{} script-binding py_event_handler/{}'.format(keydef, binding_name), mode)
elif isinstance(callback_or_cmd, str):
self.command('define-section', binding_name, '{} {}'.format(keydef, callback_or_cmd), mode)
else:
raise TypeError('register_key_binding expects either an str with an mpv command or a python callable.')
self.command('enable-section', binding_name, 'allow-hide-cursor+allow-vo-dragging')
def _handle_key_binding_message(self, binding_name, key_state, key_name=None):
self._key_binding_handlers[binding_name](key_state, key_name)
def unregister_key_binding(self, keydef):
"""Unregister a key binding by keydef."""
binding_name = MPV._binding_name(keydef)
self.command('disable-section', binding_name)
self.command('define-section', binding_name, '')
if binding_name in self._key_binding_handlers:
del self._key_binding_handlers[binding_name]
if not self._key_binding_handlers:
self.unregister_message_handler('key-binding')
# Convenience functions
def play(self, filename):
"""Play a path or URL (requires ``ytdl`` option to be set)."""
self.loadfile(filename)
@property
def playlist_filenames(self):
"""Return all playlist item file names/URLs as a list of strs."""
return [element['filename'] for element in self.playlist]
def playlist_append(self, filename, **options):
"""Append a path or URL to the playlist. This does not start playing the file automatically. To do that, use
``MPV.loadfile(filename, 'append-play')``."""
self.loadfile(filename, 'append', **options)
# Property accessors
def _get_property(self, name, decoder=strict_decoder, fmt=MpvFormat.NODE):
out = create_string_buffer(sizeof(MpvNode))
try:
cval = _mpv_get_property(self.handle, name.encode('utf-8'), fmt, out)
if fmt is MpvFormat.OSD_STRING:
return cast(out, POINTER(c_char_p)).contents.value.decode('utf-8')
elif fmt is MpvFormat.NODE:
rv = cast(out, POINTER(MpvNode)).contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
else:
raise TypeError('_get_property only supports NODE and OSD_STRING formats.')
except PropertyUnavailableError as ex:
return None
def _set_property(self, name, value):
ename = name.encode('utf-8')
if isinstance(value, (list, set, dict)):
_1, _2, _3, pointer = _make_node_str_list(value)
_mpv_set_property(self.handle, ename, MpvFormat.NODE, pointer)
else:
_mpv_set_property_string(self.handle, ename, _mpv_coax_proptype(value))
def __getattr__(self, name):
return self._get_property(_py_to_mpv(name), lazy_decoder)
def __setattr__(self, name, value):
try:
if name != 'handle' and not name.startswith('_'):
self._set_property(_py_to_mpv(name), value)
else:
super().__setattr__(name, value)
except AttributeError:
super().__setattr__(name, value)
def __dir__(self):
return super().__dir__() + [ name.replace('-', '_') for name in self.property_list ]
@property
def properties(self):
return { name: self.option_info(name) for name in self.property_list }
# Dict-like option access
def __getitem__(self, name, file_local=False):
"""Get an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._get_property(prefix+name, lazy_decoder)
def __setitem__(self, name, value, file_local=False):
"""Set an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._set_property(prefix+name, value)
def __iter__(self):
"""Iterate over all option names."""
return iter(self.options)
def option_info(self, name):
"""Get information on the given option."""
try:
return self._get_property('option-info/'+name)
except AttributeError:
return None
|
jaseg/python-mpv | mpv.py | MPV.wait_for_property | python | def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True):
sema = threading.Semaphore(value=0)
def observer(name, val):
if cond(val):
sema.release()
self.observe_property(name, observer)
if not level_sensitive or not cond(getattr(self, name.replace('-', '_'))):
sema.acquire()
self.unobserve_property(name, observer) | Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for
properties such as ``idle_active`` indicating the player is done with regular playback and just idling around | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L582-L593 | [
"def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True):\n"
] | class MPV(object):
"""See man mpv(1) for the details of the implemented commands. All mpv properties can be accessed as
``my_mpv.some_property`` and all mpv options can be accessed as ``my_mpv['some-option']``.
By default, properties are returned as decoded ``str`` and an error is thrown if the value does not contain valid
utf-8. To get a decoded ``str`` if possibly but ``bytes`` instead of an error if not, use
``my_mpv.lazy.some_property``. To always get raw ``bytes``, use ``my_mpv.raw.some_property``. To access a
property's decoded OSD value, use ``my_mpv.osd.some_property``.
To get API information on an option, use ``my_mpv.option_info('option-name')``. To get API information on a
property, use ``my_mpv.properties['property-name']``. Take care to use mpv's dashed-names instead of the
underscore_names exposed on the python object.
To make your program not barf hard the first time its used on a weird file system **always** access properties
containing file names or file tags through ``MPV.raw``. """
def __init__(self, *extra_mpv_flags, log_handler=None, start_event_thread=True, loglevel=None, **extra_mpv_opts):
"""Create an MPV instance.
Extra arguments and extra keyword arguments will be passed to mpv as options.
"""
self.handle = _mpv_create()
self._event_thread = None
_mpv_set_option_string(self.handle, b'audio-display', b'no')
istr = lambda o: ('yes' if o else 'no') if type(o) is bool else str(o)
try:
for flag in extra_mpv_flags:
_mpv_set_option_string(self.handle, flag.encode('utf-8'), b'')
for k,v in extra_mpv_opts.items():
_mpv_set_option_string(self.handle, k.replace('_', '-').encode('utf-8'), istr(v).encode('utf-8'))
finally:
_mpv_initialize(self.handle)
self.osd = _OSDPropertyProxy(self)
self.file_local = _FileLocalProxy(self)
self.raw = _DecoderPropertyProxy(self, identity_decoder)
self.strict = _DecoderPropertyProxy(self, strict_decoder)
self.lazy = _DecoderPropertyProxy(self, lazy_decoder)
self._event_callbacks = []
self._property_handlers = collections.defaultdict(lambda: [])
self._message_handlers = {}
self._key_binding_handlers = {}
self._playback_cond = threading.Condition()
self._event_handle = _mpv_create_client(self.handle, b'py_event_handler')
self._loop = partial(_event_loop, self._event_handle, self._playback_cond, self._event_callbacks,
self._message_handlers, self._property_handlers, log_handler)
if loglevel is not None or log_handler is not None:
self.set_loglevel(loglevel or 'terminal-default')
if start_event_thread:
self._event_thread = threading.Thread(target=self._loop, name='MPVEventHandlerThread')
self._event_thread.setDaemon(True)
self._event_thread.start()
else:
self._event_thread = None
def wait_for_playback(self):
"""Waits until playback of the current title is paused or done."""
with self._playback_cond:
self._playback_cond.wait()
def __del__(self):
if self.handle:
self.terminate()
def terminate(self):
"""Properly terminates this player instance. Preferably use this instead of relying on python's garbage
collector to cause this to be called from the object's destructor.
"""
self.handle, handle = None, self.handle
if threading.current_thread() is self._event_thread:
# Handle special case to allow event handle to be detached.
# This is necessary since otherwise the event thread would deadlock itself.
grim_reaper = threading.Thread(target=lambda: _mpv_terminate_destroy(handle))
grim_reaper.start()
else:
_mpv_terminate_destroy(handle)
if self._event_thread:
self._event_thread.join()
def set_loglevel(self, level):
"""Set MPV's log level. This adjusts which output will be sent to this object's log handlers. If you just want
mpv's regular terminal output, you don't need to adjust this but just need to pass a log handler to the MPV
constructur such as ``MPV(log_handler=print)``.
Valid log levels are "no", "fatal", "error", "warn", "info", "v" "debug" and "trace". For details see your mpv's
client.h header file.
"""
_mpv_request_log_messages(self._event_handle, level.encode('utf-8'))
def command(self, name, *args):
"""Execute a raw command."""
args = [name.encode('utf-8')] + [ (arg if type(arg) is bytes else str(arg).encode('utf-8'))
for arg in args if arg is not None ] + [None]
_mpv_command(self.handle, (c_char_p*len(args))(*args))
def node_command(self, name, *args, decoder=strict_decoder):
_1, _2, _3, pointer = _make_node_str_list([name, *args])
out = cast(create_string_buffer(sizeof(MpvNode)), POINTER(MpvNode))
ppointer = cast(pointer, POINTER(MpvNode))
_mpv_command_node(self.handle, ppointer, out)
rv = out.contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
def seek(self, amount, reference="relative", precision="default-precise"):
"""Mapped mpv seek command, see man mpv(1)."""
self.command('seek', amount, reference, precision)
def revert_seek(self):
"""Mapped mpv revert_seek command, see man mpv(1)."""
self.command('revert_seek');
def frame_step(self):
"""Mapped mpv frame_step command, see man mpv(1)."""
self.command('frame_step')
def frame_back_step(self):
"""Mapped mpv frame_back_step command, see man mpv(1)."""
self.command('frame_back_step')
def property_add(self, name, value=1):
"""Add the given value to the property's value. On overflow or underflow, clamp the property to the maximum. If
``value`` is omitted, assume ``1``.
"""
self.command('add', name, value)
def property_multiply(self, name, factor):
"""Multiply the value of a property with a numeric factor."""
self.command('multiply', name, factor)
def cycle(self, name, direction='up'):
"""Cycle the given property. ``up`` and ``down`` set the cycle direction. On overflow, set the property back to
the minimum, on underflow set it to the maximum. If ``up`` or ``down`` is omitted, assume ``up``.
"""
self.command('cycle', name, direction)
def screenshot(self, includes='subtitles', mode='single'):
"""Mapped mpv screenshot command, see man mpv(1)."""
self.command('screenshot', includes, mode)
def screenshot_to_file(self, filename, includes='subtitles'):
"""Mapped mpv screenshot_to_file command, see man mpv(1)."""
self.command('screenshot_to_file', filename.encode(fs_enc), includes)
def screenshot_raw(self, includes='subtitles'):
"""Mapped mpv screenshot_raw command, see man mpv(1). Returns a pillow Image object."""
from PIL import Image
res = self.node_command('screenshot-raw', includes)
if res['format'] != 'bgr0':
raise ValueError('Screenshot in unknown format "{}". Currently, only bgr0 is supported.'
.format(res['format']))
img = Image.frombytes('RGBA', (res['w'], res['h']), res['data'])
b,g,r,a = img.split()
return Image.merge('RGB', (r,g,b))
def playlist_next(self, mode='weak'):
"""Mapped mpv playlist_next command, see man mpv(1)."""
self.command('playlist_next', mode)
def playlist_prev(self, mode='weak'):
"""Mapped mpv playlist_prev command, see man mpv(1)."""
self.command('playlist_prev', mode)
@staticmethod
def _encode_options(options):
return ','.join('{}={}'.format(str(key), str(val)) for key, val in options.items())
def loadfile(self, filename, mode='replace', **options):
"""Mapped mpv loadfile command, see man mpv(1)."""
self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode_options(options))
def loadlist(self, playlist, mode='replace'):
"""Mapped mpv loadlist command, see man mpv(1)."""
self.command('loadlist', playlist.encode(fs_enc), mode)
def playlist_clear(self):
"""Mapped mpv playlist_clear command, see man mpv(1)."""
self.command('playlist_clear')
def playlist_remove(self, index='current'):
"""Mapped mpv playlist_remove command, see man mpv(1)."""
self.command('playlist_remove', index)
def playlist_move(self, index1, index2):
"""Mapped mpv playlist_move command, see man mpv(1)."""
self.command('playlist_move', index1, index2)
def run(self, command, *args):
"""Mapped mpv run command, see man mpv(1)."""
self.command('run', command, *args)
def quit(self, code=None):
"""Mapped mpv quit command, see man mpv(1)."""
self.command('quit', code)
def quit_watch_later(self, code=None):
"""Mapped mpv quit_watch_later command, see man mpv(1)."""
self.command('quit_watch_later', code)
def sub_add(self, filename):
"""Mapped mpv sub_add command, see man mpv(1)."""
self.command('sub_add', filename.encode(fs_enc))
def sub_remove(self, sub_id=None):
"""Mapped mpv sub_remove command, see man mpv(1)."""
self.command('sub_remove', sub_id)
def sub_reload(self, sub_id=None):
"""Mapped mpv sub_reload command, see man mpv(1)."""
self.command('sub_reload', sub_id)
def sub_step(self, skip):
"""Mapped mpv sub_step command, see man mpv(1)."""
self.command('sub_step', skip)
def sub_seek(self, skip):
"""Mapped mpv sub_seek command, see man mpv(1)."""
self.command('sub_seek', skip)
def toggle_osd(self):
"""Mapped mpv osd command, see man mpv(1)."""
self.command('osd')
def show_text(self, string, duration='-1', level=None):
"""Mapped mpv show_text command, see man mpv(1)."""
self.command('show_text', string, duration, level)
def show_progress(self):
"""Mapped mpv show_progress command, see man mpv(1)."""
self.command('show_progress')
def discnav(self, command):
"""Mapped mpv discnav command, see man mpv(1)."""
self.command('discnav', command)
def write_watch_later_config(self):
"""Mapped mpv write_watch_later_config command, see man mpv(1)."""
self.command('write_watch_later_config')
def overlay_add(self, overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride):
"""Mapped mpv overlay_add command, see man mpv(1)."""
self.command('overlay_add', overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride)
def overlay_remove(self, overlay_id):
"""Mapped mpv overlay_remove command, see man mpv(1)."""
self.command('overlay_remove', overlay_id)
def script_message(self, *args):
"""Mapped mpv script_message command, see man mpv(1)."""
self.command('script_message', *args)
def script_message_to(self, target, *args):
"""Mapped mpv script_message_to command, see man mpv(1)."""
self.command('script_message_to', target, *args)
def observe_property(self, name, handler):
"""Register an observer on the named property. An observer is a function that is called with the new property
value every time the property's value is changed. The basic function signature is ``fun(property_name,
new_value)`` with new_value being the decoded property value as a python object. This function can be used as a
function decorator if no handler is given.
To unregister the observer, call either of ``mpv.unobserve_property(name, handler)``,
``mpv.unobserve_all_properties(handler)`` or the handler's ``unregister_mpv_properties`` attribute::
@player.observe_property('volume')
def my_handler(new_volume, *):
print("It's loud!", volume)
my_handler.unregister_mpv_properties()
"""
self._property_handlers[name].append(handler)
_mpv_observe_property(self._event_handle, hash(name)&0xffffffffffffffff, name.encode('utf-8'), MpvFormat.NODE)
def property_observer(self, name):
"""Function decorator to register a property observer. See ``MPV.observe_property`` for details."""
def wrapper(fun):
self.observe_property(name, fun)
fun.unobserve_mpv_properties = lambda: self.unobserve_property(name, fun)
return fun
return wrapper
def unobserve_property(self, name, handler):
"""Unregister a property observer. This requires both the observed property's name and the handler function that
was originally registered as one handler could be registered for several properties. To unregister a handler
from *all* observed properties see ``unobserve_all_properties``.
"""
self._property_handlers[name].remove(handler)
if not self._property_handlers[name]:
_mpv_unobserve_property(self._event_handle, hash(name)&0xffffffffffffffff)
def unobserve_all_properties(self, handler):
"""Unregister a property observer from *all* observed properties."""
for name in self._property_handlers:
self.unobserve_property(name, handler)
def register_message_handler(self, target, handler=None):
"""Register a mpv script message handler. This can be used to communicate with embedded lua scripts. Pass the
script message target name this handler should be listening to and the handler function.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
self._register_message_handler_internal(target, handler)
def _register_message_handler_internal(self, target, handler):
self._message_handlers[target] = handler
def unregister_message_handler(self, target_or_handler):
"""Unregister a mpv script message handler for the given script message target name.
You can also call the ``unregister_mpv_messages`` function attribute set on the handler function when it is
registered.
"""
if isinstance(target_or_handler, str):
del self._message_handlers[target_or_handler]
else:
for key, val in self._message_handlers.items():
if val == target_or_handler:
del self._message_handlers[key]
def message_handler(self, target):
"""Decorator to register a mpv script message handler.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
def register(handler):
self._register_message_handler_internal(target, handler)
handler.unregister_mpv_messages = lambda: self.unregister_message_handler(handler)
return handler
return register
def register_event_callback(self, callback):
"""Register a blanket event callback receiving all event types.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
self._event_callbacks.append(callback)
def unregister_event_callback(self, callback):
"""Unregiser an event callback."""
self._event_callbacks.remove(callback)
def event_callback(self, *event_types):
"""Function decorator to register a blanket event callback for the given event types. Event types can be given
as str (e.g. 'start-file'), integer or MpvEventID object.
WARNING: Due to the way this is filtering events, this decorator cannot be chained with itself.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
def register(callback):
types = [MpvEventID.from_str(t) if isinstance(t, str) else t for t in event_types] or MpvEventID.ANY
@wraps(callback)
def wrapper(event, *args, **kwargs):
if event['event_id'] in types:
callback(event, *args, **kwargs)
self._event_callbacks.append(wrapper)
wrapper.unregister_mpv_events = partial(self.unregister_event_callback, wrapper)
return wrapper
return register
@staticmethod
def _binding_name(callback_or_cmd):
return 'py_kb_{:016x}'.format(hash(callback_or_cmd)&0xffffffffffffffff)
def on_key_press(self, keydef, mode='force'):
"""Function decorator to register a simplified key binding. The callback is called whenever the key given is
*pressed*.
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.on_key_press('Q')
def binding():
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
The BIG FAT WARNING regarding untrusted keydefs from the key_binding method applies here as well.
"""
def register(fun):
@self.key_binding(keydef, mode)
@wraps(fun)
def wrapper(state='p-', name=None):
if state[0] in ('d', 'p'):
fun()
return wrapper
return register
def key_binding(self, keydef, mode='force'):
"""Function decorator to register a low-level key binding.
The callback function signature is ``fun(key_state, key_name)`` where ``key_state`` is either ``'U'`` for "key
up" or ``'D'`` for "key down".
The keydef format is: ``[Shift+][Ctrl+][Alt+][Meta+]<key>`` where ``<key>`` is either the literal character the
key produces (ASCII or Unicode character), or a symbolic name (as printed by ``mpv --input-keylist``).
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.key_binding('Q')
def binding(state, name):
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
BIG FAT WARNING: mpv's key binding mechanism is pretty powerful. This means, you essentially get arbitrary code
exectution through key bindings. This interface makes some limited effort to sanitize the keydef given in the
first parameter, but YOU SHOULD NOT RELY ON THIS IN FOR SECURITY. If your input comes from config files, this is
completely fine--but, if you are about to pass untrusted input into this parameter, better double-check whether
this is secure in your case.
"""
def register(fun):
fun.mpv_key_bindings = getattr(fun, 'mpv_key_bindings', []) + [keydef]
def unregister_all():
for keydef in fun.mpv_key_bindings:
self.unregister_key_binding(keydef)
fun.unregister_mpv_key_bindings = unregister_all
self.register_key_binding(keydef, fun, mode)
return fun
return register
def register_key_binding(self, keydef, callback_or_cmd, mode='force'):
"""Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python
callback function. See ``MPV.key_binding`` for details.
"""
if not re.match(r'(Shift+)?(Ctrl+)?(Alt+)?(Meta+)?(.|\w+)', keydef):
raise ValueError('Invalid keydef. Expected format: [Shift+][Ctrl+][Alt+][Meta+]<key>\n'
'<key> is either the literal character the key produces (ASCII or Unicode character), or a '
'symbolic name (as printed by --input-keylist')
binding_name = MPV._binding_name(keydef)
if callable(callback_or_cmd):
self._key_binding_handlers[binding_name] = callback_or_cmd
self.register_message_handler('key-binding', self._handle_key_binding_message)
self.command('define-section',
binding_name, '{} script-binding py_event_handler/{}'.format(keydef, binding_name), mode)
elif isinstance(callback_or_cmd, str):
self.command('define-section', binding_name, '{} {}'.format(keydef, callback_or_cmd), mode)
else:
raise TypeError('register_key_binding expects either an str with an mpv command or a python callable.')
self.command('enable-section', binding_name, 'allow-hide-cursor+allow-vo-dragging')
def _handle_key_binding_message(self, binding_name, key_state, key_name=None):
self._key_binding_handlers[binding_name](key_state, key_name)
def unregister_key_binding(self, keydef):
"""Unregister a key binding by keydef."""
binding_name = MPV._binding_name(keydef)
self.command('disable-section', binding_name)
self.command('define-section', binding_name, '')
if binding_name in self._key_binding_handlers:
del self._key_binding_handlers[binding_name]
if not self._key_binding_handlers:
self.unregister_message_handler('key-binding')
# Convenience functions
def play(self, filename):
"""Play a path or URL (requires ``ytdl`` option to be set)."""
self.loadfile(filename)
@property
def playlist_filenames(self):
"""Return all playlist item file names/URLs as a list of strs."""
return [element['filename'] for element in self.playlist]
def playlist_append(self, filename, **options):
"""Append a path or URL to the playlist. This does not start playing the file automatically. To do that, use
``MPV.loadfile(filename, 'append-play')``."""
self.loadfile(filename, 'append', **options)
# Property accessors
def _get_property(self, name, decoder=strict_decoder, fmt=MpvFormat.NODE):
out = create_string_buffer(sizeof(MpvNode))
try:
cval = _mpv_get_property(self.handle, name.encode('utf-8'), fmt, out)
if fmt is MpvFormat.OSD_STRING:
return cast(out, POINTER(c_char_p)).contents.value.decode('utf-8')
elif fmt is MpvFormat.NODE:
rv = cast(out, POINTER(MpvNode)).contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
else:
raise TypeError('_get_property only supports NODE and OSD_STRING formats.')
except PropertyUnavailableError as ex:
return None
def _set_property(self, name, value):
ename = name.encode('utf-8')
if isinstance(value, (list, set, dict)):
_1, _2, _3, pointer = _make_node_str_list(value)
_mpv_set_property(self.handle, ename, MpvFormat.NODE, pointer)
else:
_mpv_set_property_string(self.handle, ename, _mpv_coax_proptype(value))
def __getattr__(self, name):
return self._get_property(_py_to_mpv(name), lazy_decoder)
def __setattr__(self, name, value):
try:
if name != 'handle' and not name.startswith('_'):
self._set_property(_py_to_mpv(name), value)
else:
super().__setattr__(name, value)
except AttributeError:
super().__setattr__(name, value)
def __dir__(self):
return super().__dir__() + [ name.replace('-', '_') for name in self.property_list ]
@property
def properties(self):
return { name: self.option_info(name) for name in self.property_list }
# Dict-like option access
def __getitem__(self, name, file_local=False):
"""Get an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._get_property(prefix+name, lazy_decoder)
def __setitem__(self, name, value, file_local=False):
"""Set an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._set_property(prefix+name, value)
def __iter__(self):
"""Iterate over all option names."""
return iter(self.options)
def option_info(self, name):
"""Get information on the given option."""
try:
return self._get_property('option-info/'+name)
except AttributeError:
return None
|
jaseg/python-mpv | mpv.py | MPV.terminate | python | def terminate(self):
self.handle, handle = None, self.handle
if threading.current_thread() is self._event_thread:
# Handle special case to allow event handle to be detached.
# This is necessary since otherwise the event thread would deadlock itself.
grim_reaper = threading.Thread(target=lambda: _mpv_terminate_destroy(handle))
grim_reaper.start()
else:
_mpv_terminate_destroy(handle)
if self._event_thread:
self._event_thread.join() | Properly terminates this player instance. Preferably use this instead of relying on python's garbage
collector to cause this to be called from the object's destructor. | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L599-L612 | null | class MPV(object):
"""See man mpv(1) for the details of the implemented commands. All mpv properties can be accessed as
``my_mpv.some_property`` and all mpv options can be accessed as ``my_mpv['some-option']``.
By default, properties are returned as decoded ``str`` and an error is thrown if the value does not contain valid
utf-8. To get a decoded ``str`` if possibly but ``bytes`` instead of an error if not, use
``my_mpv.lazy.some_property``. To always get raw ``bytes``, use ``my_mpv.raw.some_property``. To access a
property's decoded OSD value, use ``my_mpv.osd.some_property``.
To get API information on an option, use ``my_mpv.option_info('option-name')``. To get API information on a
property, use ``my_mpv.properties['property-name']``. Take care to use mpv's dashed-names instead of the
underscore_names exposed on the python object.
To make your program not barf hard the first time its used on a weird file system **always** access properties
containing file names or file tags through ``MPV.raw``. """
def __init__(self, *extra_mpv_flags, log_handler=None, start_event_thread=True, loglevel=None, **extra_mpv_opts):
"""Create an MPV instance.
Extra arguments and extra keyword arguments will be passed to mpv as options.
"""
self.handle = _mpv_create()
self._event_thread = None
_mpv_set_option_string(self.handle, b'audio-display', b'no')
istr = lambda o: ('yes' if o else 'no') if type(o) is bool else str(o)
try:
for flag in extra_mpv_flags:
_mpv_set_option_string(self.handle, flag.encode('utf-8'), b'')
for k,v in extra_mpv_opts.items():
_mpv_set_option_string(self.handle, k.replace('_', '-').encode('utf-8'), istr(v).encode('utf-8'))
finally:
_mpv_initialize(self.handle)
self.osd = _OSDPropertyProxy(self)
self.file_local = _FileLocalProxy(self)
self.raw = _DecoderPropertyProxy(self, identity_decoder)
self.strict = _DecoderPropertyProxy(self, strict_decoder)
self.lazy = _DecoderPropertyProxy(self, lazy_decoder)
self._event_callbacks = []
self._property_handlers = collections.defaultdict(lambda: [])
self._message_handlers = {}
self._key_binding_handlers = {}
self._playback_cond = threading.Condition()
self._event_handle = _mpv_create_client(self.handle, b'py_event_handler')
self._loop = partial(_event_loop, self._event_handle, self._playback_cond, self._event_callbacks,
self._message_handlers, self._property_handlers, log_handler)
if loglevel is not None or log_handler is not None:
self.set_loglevel(loglevel or 'terminal-default')
if start_event_thread:
self._event_thread = threading.Thread(target=self._loop, name='MPVEventHandlerThread')
self._event_thread.setDaemon(True)
self._event_thread.start()
else:
self._event_thread = None
def wait_for_playback(self):
"""Waits until playback of the current title is paused or done."""
with self._playback_cond:
self._playback_cond.wait()
def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True):
"""Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for
properties such as ``idle_active`` indicating the player is done with regular playback and just idling around
"""
sema = threading.Semaphore(value=0)
def observer(name, val):
if cond(val):
sema.release()
self.observe_property(name, observer)
if not level_sensitive or not cond(getattr(self, name.replace('-', '_'))):
sema.acquire()
self.unobserve_property(name, observer)
def __del__(self):
if self.handle:
self.terminate()
def set_loglevel(self, level):
"""Set MPV's log level. This adjusts which output will be sent to this object's log handlers. If you just want
mpv's regular terminal output, you don't need to adjust this but just need to pass a log handler to the MPV
constructur such as ``MPV(log_handler=print)``.
Valid log levels are "no", "fatal", "error", "warn", "info", "v" "debug" and "trace". For details see your mpv's
client.h header file.
"""
_mpv_request_log_messages(self._event_handle, level.encode('utf-8'))
def command(self, name, *args):
"""Execute a raw command."""
args = [name.encode('utf-8')] + [ (arg if type(arg) is bytes else str(arg).encode('utf-8'))
for arg in args if arg is not None ] + [None]
_mpv_command(self.handle, (c_char_p*len(args))(*args))
def node_command(self, name, *args, decoder=strict_decoder):
_1, _2, _3, pointer = _make_node_str_list([name, *args])
out = cast(create_string_buffer(sizeof(MpvNode)), POINTER(MpvNode))
ppointer = cast(pointer, POINTER(MpvNode))
_mpv_command_node(self.handle, ppointer, out)
rv = out.contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
def seek(self, amount, reference="relative", precision="default-precise"):
"""Mapped mpv seek command, see man mpv(1)."""
self.command('seek', amount, reference, precision)
def revert_seek(self):
"""Mapped mpv revert_seek command, see man mpv(1)."""
self.command('revert_seek');
def frame_step(self):
"""Mapped mpv frame_step command, see man mpv(1)."""
self.command('frame_step')
def frame_back_step(self):
"""Mapped mpv frame_back_step command, see man mpv(1)."""
self.command('frame_back_step')
def property_add(self, name, value=1):
"""Add the given value to the property's value. On overflow or underflow, clamp the property to the maximum. If
``value`` is omitted, assume ``1``.
"""
self.command('add', name, value)
def property_multiply(self, name, factor):
"""Multiply the value of a property with a numeric factor."""
self.command('multiply', name, factor)
def cycle(self, name, direction='up'):
"""Cycle the given property. ``up`` and ``down`` set the cycle direction. On overflow, set the property back to
the minimum, on underflow set it to the maximum. If ``up`` or ``down`` is omitted, assume ``up``.
"""
self.command('cycle', name, direction)
def screenshot(self, includes='subtitles', mode='single'):
"""Mapped mpv screenshot command, see man mpv(1)."""
self.command('screenshot', includes, mode)
def screenshot_to_file(self, filename, includes='subtitles'):
"""Mapped mpv screenshot_to_file command, see man mpv(1)."""
self.command('screenshot_to_file', filename.encode(fs_enc), includes)
def screenshot_raw(self, includes='subtitles'):
"""Mapped mpv screenshot_raw command, see man mpv(1). Returns a pillow Image object."""
from PIL import Image
res = self.node_command('screenshot-raw', includes)
if res['format'] != 'bgr0':
raise ValueError('Screenshot in unknown format "{}". Currently, only bgr0 is supported.'
.format(res['format']))
img = Image.frombytes('RGBA', (res['w'], res['h']), res['data'])
b,g,r,a = img.split()
return Image.merge('RGB', (r,g,b))
def playlist_next(self, mode='weak'):
"""Mapped mpv playlist_next command, see man mpv(1)."""
self.command('playlist_next', mode)
def playlist_prev(self, mode='weak'):
"""Mapped mpv playlist_prev command, see man mpv(1)."""
self.command('playlist_prev', mode)
@staticmethod
def _encode_options(options):
return ','.join('{}={}'.format(str(key), str(val)) for key, val in options.items())
def loadfile(self, filename, mode='replace', **options):
"""Mapped mpv loadfile command, see man mpv(1)."""
self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode_options(options))
def loadlist(self, playlist, mode='replace'):
"""Mapped mpv loadlist command, see man mpv(1)."""
self.command('loadlist', playlist.encode(fs_enc), mode)
def playlist_clear(self):
"""Mapped mpv playlist_clear command, see man mpv(1)."""
self.command('playlist_clear')
def playlist_remove(self, index='current'):
"""Mapped mpv playlist_remove command, see man mpv(1)."""
self.command('playlist_remove', index)
def playlist_move(self, index1, index2):
"""Mapped mpv playlist_move command, see man mpv(1)."""
self.command('playlist_move', index1, index2)
def run(self, command, *args):
"""Mapped mpv run command, see man mpv(1)."""
self.command('run', command, *args)
def quit(self, code=None):
"""Mapped mpv quit command, see man mpv(1)."""
self.command('quit', code)
def quit_watch_later(self, code=None):
"""Mapped mpv quit_watch_later command, see man mpv(1)."""
self.command('quit_watch_later', code)
def sub_add(self, filename):
"""Mapped mpv sub_add command, see man mpv(1)."""
self.command('sub_add', filename.encode(fs_enc))
def sub_remove(self, sub_id=None):
"""Mapped mpv sub_remove command, see man mpv(1)."""
self.command('sub_remove', sub_id)
def sub_reload(self, sub_id=None):
"""Mapped mpv sub_reload command, see man mpv(1)."""
self.command('sub_reload', sub_id)
def sub_step(self, skip):
"""Mapped mpv sub_step command, see man mpv(1)."""
self.command('sub_step', skip)
def sub_seek(self, skip):
"""Mapped mpv sub_seek command, see man mpv(1)."""
self.command('sub_seek', skip)
def toggle_osd(self):
"""Mapped mpv osd command, see man mpv(1)."""
self.command('osd')
def show_text(self, string, duration='-1', level=None):
"""Mapped mpv show_text command, see man mpv(1)."""
self.command('show_text', string, duration, level)
def show_progress(self):
"""Mapped mpv show_progress command, see man mpv(1)."""
self.command('show_progress')
def discnav(self, command):
"""Mapped mpv discnav command, see man mpv(1)."""
self.command('discnav', command)
def write_watch_later_config(self):
"""Mapped mpv write_watch_later_config command, see man mpv(1)."""
self.command('write_watch_later_config')
def overlay_add(self, overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride):
"""Mapped mpv overlay_add command, see man mpv(1)."""
self.command('overlay_add', overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride)
def overlay_remove(self, overlay_id):
"""Mapped mpv overlay_remove command, see man mpv(1)."""
self.command('overlay_remove', overlay_id)
def script_message(self, *args):
"""Mapped mpv script_message command, see man mpv(1)."""
self.command('script_message', *args)
def script_message_to(self, target, *args):
"""Mapped mpv script_message_to command, see man mpv(1)."""
self.command('script_message_to', target, *args)
def observe_property(self, name, handler):
"""Register an observer on the named property. An observer is a function that is called with the new property
value every time the property's value is changed. The basic function signature is ``fun(property_name,
new_value)`` with new_value being the decoded property value as a python object. This function can be used as a
function decorator if no handler is given.
To unregister the observer, call either of ``mpv.unobserve_property(name, handler)``,
``mpv.unobserve_all_properties(handler)`` or the handler's ``unregister_mpv_properties`` attribute::
@player.observe_property('volume')
def my_handler(new_volume, *):
print("It's loud!", volume)
my_handler.unregister_mpv_properties()
"""
self._property_handlers[name].append(handler)
_mpv_observe_property(self._event_handle, hash(name)&0xffffffffffffffff, name.encode('utf-8'), MpvFormat.NODE)
def property_observer(self, name):
"""Function decorator to register a property observer. See ``MPV.observe_property`` for details."""
def wrapper(fun):
self.observe_property(name, fun)
fun.unobserve_mpv_properties = lambda: self.unobserve_property(name, fun)
return fun
return wrapper
def unobserve_property(self, name, handler):
"""Unregister a property observer. This requires both the observed property's name and the handler function that
was originally registered as one handler could be registered for several properties. To unregister a handler
from *all* observed properties see ``unobserve_all_properties``.
"""
self._property_handlers[name].remove(handler)
if not self._property_handlers[name]:
_mpv_unobserve_property(self._event_handle, hash(name)&0xffffffffffffffff)
def unobserve_all_properties(self, handler):
"""Unregister a property observer from *all* observed properties."""
for name in self._property_handlers:
self.unobserve_property(name, handler)
def register_message_handler(self, target, handler=None):
"""Register a mpv script message handler. This can be used to communicate with embedded lua scripts. Pass the
script message target name this handler should be listening to and the handler function.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
self._register_message_handler_internal(target, handler)
def _register_message_handler_internal(self, target, handler):
self._message_handlers[target] = handler
def unregister_message_handler(self, target_or_handler):
"""Unregister a mpv script message handler for the given script message target name.
You can also call the ``unregister_mpv_messages`` function attribute set on the handler function when it is
registered.
"""
if isinstance(target_or_handler, str):
del self._message_handlers[target_or_handler]
else:
for key, val in self._message_handlers.items():
if val == target_or_handler:
del self._message_handlers[key]
def message_handler(self, target):
"""Decorator to register a mpv script message handler.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
def register(handler):
self._register_message_handler_internal(target, handler)
handler.unregister_mpv_messages = lambda: self.unregister_message_handler(handler)
return handler
return register
def register_event_callback(self, callback):
"""Register a blanket event callback receiving all event types.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
self._event_callbacks.append(callback)
def unregister_event_callback(self, callback):
"""Unregiser an event callback."""
self._event_callbacks.remove(callback)
def event_callback(self, *event_types):
"""Function decorator to register a blanket event callback for the given event types. Event types can be given
as str (e.g. 'start-file'), integer or MpvEventID object.
WARNING: Due to the way this is filtering events, this decorator cannot be chained with itself.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
def register(callback):
types = [MpvEventID.from_str(t) if isinstance(t, str) else t for t in event_types] or MpvEventID.ANY
@wraps(callback)
def wrapper(event, *args, **kwargs):
if event['event_id'] in types:
callback(event, *args, **kwargs)
self._event_callbacks.append(wrapper)
wrapper.unregister_mpv_events = partial(self.unregister_event_callback, wrapper)
return wrapper
return register
@staticmethod
def _binding_name(callback_or_cmd):
return 'py_kb_{:016x}'.format(hash(callback_or_cmd)&0xffffffffffffffff)
def on_key_press(self, keydef, mode='force'):
"""Function decorator to register a simplified key binding. The callback is called whenever the key given is
*pressed*.
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.on_key_press('Q')
def binding():
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
The BIG FAT WARNING regarding untrusted keydefs from the key_binding method applies here as well.
"""
def register(fun):
@self.key_binding(keydef, mode)
@wraps(fun)
def wrapper(state='p-', name=None):
if state[0] in ('d', 'p'):
fun()
return wrapper
return register
def key_binding(self, keydef, mode='force'):
"""Function decorator to register a low-level key binding.
The callback function signature is ``fun(key_state, key_name)`` where ``key_state`` is either ``'U'`` for "key
up" or ``'D'`` for "key down".
The keydef format is: ``[Shift+][Ctrl+][Alt+][Meta+]<key>`` where ``<key>`` is either the literal character the
key produces (ASCII or Unicode character), or a symbolic name (as printed by ``mpv --input-keylist``).
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.key_binding('Q')
def binding(state, name):
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
BIG FAT WARNING: mpv's key binding mechanism is pretty powerful. This means, you essentially get arbitrary code
exectution through key bindings. This interface makes some limited effort to sanitize the keydef given in the
first parameter, but YOU SHOULD NOT RELY ON THIS IN FOR SECURITY. If your input comes from config files, this is
completely fine--but, if you are about to pass untrusted input into this parameter, better double-check whether
this is secure in your case.
"""
def register(fun):
fun.mpv_key_bindings = getattr(fun, 'mpv_key_bindings', []) + [keydef]
def unregister_all():
for keydef in fun.mpv_key_bindings:
self.unregister_key_binding(keydef)
fun.unregister_mpv_key_bindings = unregister_all
self.register_key_binding(keydef, fun, mode)
return fun
return register
def register_key_binding(self, keydef, callback_or_cmd, mode='force'):
"""Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python
callback function. See ``MPV.key_binding`` for details.
"""
if not re.match(r'(Shift+)?(Ctrl+)?(Alt+)?(Meta+)?(.|\w+)', keydef):
raise ValueError('Invalid keydef. Expected format: [Shift+][Ctrl+][Alt+][Meta+]<key>\n'
'<key> is either the literal character the key produces (ASCII or Unicode character), or a '
'symbolic name (as printed by --input-keylist')
binding_name = MPV._binding_name(keydef)
if callable(callback_or_cmd):
self._key_binding_handlers[binding_name] = callback_or_cmd
self.register_message_handler('key-binding', self._handle_key_binding_message)
self.command('define-section',
binding_name, '{} script-binding py_event_handler/{}'.format(keydef, binding_name), mode)
elif isinstance(callback_or_cmd, str):
self.command('define-section', binding_name, '{} {}'.format(keydef, callback_or_cmd), mode)
else:
raise TypeError('register_key_binding expects either an str with an mpv command or a python callable.')
self.command('enable-section', binding_name, 'allow-hide-cursor+allow-vo-dragging')
def _handle_key_binding_message(self, binding_name, key_state, key_name=None):
self._key_binding_handlers[binding_name](key_state, key_name)
def unregister_key_binding(self, keydef):
"""Unregister a key binding by keydef."""
binding_name = MPV._binding_name(keydef)
self.command('disable-section', binding_name)
self.command('define-section', binding_name, '')
if binding_name in self._key_binding_handlers:
del self._key_binding_handlers[binding_name]
if not self._key_binding_handlers:
self.unregister_message_handler('key-binding')
# Convenience functions
def play(self, filename):
"""Play a path or URL (requires ``ytdl`` option to be set)."""
self.loadfile(filename)
@property
def playlist_filenames(self):
"""Return all playlist item file names/URLs as a list of strs."""
return [element['filename'] for element in self.playlist]
def playlist_append(self, filename, **options):
"""Append a path or URL to the playlist. This does not start playing the file automatically. To do that, use
``MPV.loadfile(filename, 'append-play')``."""
self.loadfile(filename, 'append', **options)
# Property accessors
def _get_property(self, name, decoder=strict_decoder, fmt=MpvFormat.NODE):
out = create_string_buffer(sizeof(MpvNode))
try:
cval = _mpv_get_property(self.handle, name.encode('utf-8'), fmt, out)
if fmt is MpvFormat.OSD_STRING:
return cast(out, POINTER(c_char_p)).contents.value.decode('utf-8')
elif fmt is MpvFormat.NODE:
rv = cast(out, POINTER(MpvNode)).contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
else:
raise TypeError('_get_property only supports NODE and OSD_STRING formats.')
except PropertyUnavailableError as ex:
return None
def _set_property(self, name, value):
ename = name.encode('utf-8')
if isinstance(value, (list, set, dict)):
_1, _2, _3, pointer = _make_node_str_list(value)
_mpv_set_property(self.handle, ename, MpvFormat.NODE, pointer)
else:
_mpv_set_property_string(self.handle, ename, _mpv_coax_proptype(value))
def __getattr__(self, name):
return self._get_property(_py_to_mpv(name), lazy_decoder)
def __setattr__(self, name, value):
try:
if name != 'handle' and not name.startswith('_'):
self._set_property(_py_to_mpv(name), value)
else:
super().__setattr__(name, value)
except AttributeError:
super().__setattr__(name, value)
def __dir__(self):
return super().__dir__() + [ name.replace('-', '_') for name in self.property_list ]
@property
def properties(self):
return { name: self.option_info(name) for name in self.property_list }
# Dict-like option access
def __getitem__(self, name, file_local=False):
"""Get an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._get_property(prefix+name, lazy_decoder)
def __setitem__(self, name, value, file_local=False):
"""Set an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._set_property(prefix+name, value)
def __iter__(self):
"""Iterate over all option names."""
return iter(self.options)
def option_info(self, name):
"""Get information on the given option."""
try:
return self._get_property('option-info/'+name)
except AttributeError:
return None
|
jaseg/python-mpv | mpv.py | MPV.command | python | def command(self, name, *args):
args = [name.encode('utf-8')] + [ (arg if type(arg) is bytes else str(arg).encode('utf-8'))
for arg in args if arg is not None ] + [None]
_mpv_command(self.handle, (c_char_p*len(args))(*args)) | Execute a raw command. | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L624-L628 | null | class MPV(object):
"""See man mpv(1) for the details of the implemented commands. All mpv properties can be accessed as
``my_mpv.some_property`` and all mpv options can be accessed as ``my_mpv['some-option']``.
By default, properties are returned as decoded ``str`` and an error is thrown if the value does not contain valid
utf-8. To get a decoded ``str`` if possibly but ``bytes`` instead of an error if not, use
``my_mpv.lazy.some_property``. To always get raw ``bytes``, use ``my_mpv.raw.some_property``. To access a
property's decoded OSD value, use ``my_mpv.osd.some_property``.
To get API information on an option, use ``my_mpv.option_info('option-name')``. To get API information on a
property, use ``my_mpv.properties['property-name']``. Take care to use mpv's dashed-names instead of the
underscore_names exposed on the python object.
To make your program not barf hard the first time its used on a weird file system **always** access properties
containing file names or file tags through ``MPV.raw``. """
def __init__(self, *extra_mpv_flags, log_handler=None, start_event_thread=True, loglevel=None, **extra_mpv_opts):
"""Create an MPV instance.
Extra arguments and extra keyword arguments will be passed to mpv as options.
"""
self.handle = _mpv_create()
self._event_thread = None
_mpv_set_option_string(self.handle, b'audio-display', b'no')
istr = lambda o: ('yes' if o else 'no') if type(o) is bool else str(o)
try:
for flag in extra_mpv_flags:
_mpv_set_option_string(self.handle, flag.encode('utf-8'), b'')
for k,v in extra_mpv_opts.items():
_mpv_set_option_string(self.handle, k.replace('_', '-').encode('utf-8'), istr(v).encode('utf-8'))
finally:
_mpv_initialize(self.handle)
self.osd = _OSDPropertyProxy(self)
self.file_local = _FileLocalProxy(self)
self.raw = _DecoderPropertyProxy(self, identity_decoder)
self.strict = _DecoderPropertyProxy(self, strict_decoder)
self.lazy = _DecoderPropertyProxy(self, lazy_decoder)
self._event_callbacks = []
self._property_handlers = collections.defaultdict(lambda: [])
self._message_handlers = {}
self._key_binding_handlers = {}
self._playback_cond = threading.Condition()
self._event_handle = _mpv_create_client(self.handle, b'py_event_handler')
self._loop = partial(_event_loop, self._event_handle, self._playback_cond, self._event_callbacks,
self._message_handlers, self._property_handlers, log_handler)
if loglevel is not None or log_handler is not None:
self.set_loglevel(loglevel or 'terminal-default')
if start_event_thread:
self._event_thread = threading.Thread(target=self._loop, name='MPVEventHandlerThread')
self._event_thread.setDaemon(True)
self._event_thread.start()
else:
self._event_thread = None
def wait_for_playback(self):
"""Waits until playback of the current title is paused or done."""
with self._playback_cond:
self._playback_cond.wait()
def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True):
"""Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for
properties such as ``idle_active`` indicating the player is done with regular playback and just idling around
"""
sema = threading.Semaphore(value=0)
def observer(name, val):
if cond(val):
sema.release()
self.observe_property(name, observer)
if not level_sensitive or not cond(getattr(self, name.replace('-', '_'))):
sema.acquire()
self.unobserve_property(name, observer)
def __del__(self):
if self.handle:
self.terminate()
def terminate(self):
"""Properly terminates this player instance. Preferably use this instead of relying on python's garbage
collector to cause this to be called from the object's destructor.
"""
self.handle, handle = None, self.handle
if threading.current_thread() is self._event_thread:
# Handle special case to allow event handle to be detached.
# This is necessary since otherwise the event thread would deadlock itself.
grim_reaper = threading.Thread(target=lambda: _mpv_terminate_destroy(handle))
grim_reaper.start()
else:
_mpv_terminate_destroy(handle)
if self._event_thread:
self._event_thread.join()
def set_loglevel(self, level):
"""Set MPV's log level. This adjusts which output will be sent to this object's log handlers. If you just want
mpv's regular terminal output, you don't need to adjust this but just need to pass a log handler to the MPV
constructur such as ``MPV(log_handler=print)``.
Valid log levels are "no", "fatal", "error", "warn", "info", "v" "debug" and "trace". For details see your mpv's
client.h header file.
"""
_mpv_request_log_messages(self._event_handle, level.encode('utf-8'))
def node_command(self, name, *args, decoder=strict_decoder):
_1, _2, _3, pointer = _make_node_str_list([name, *args])
out = cast(create_string_buffer(sizeof(MpvNode)), POINTER(MpvNode))
ppointer = cast(pointer, POINTER(MpvNode))
_mpv_command_node(self.handle, ppointer, out)
rv = out.contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
def seek(self, amount, reference="relative", precision="default-precise"):
"""Mapped mpv seek command, see man mpv(1)."""
self.command('seek', amount, reference, precision)
def revert_seek(self):
"""Mapped mpv revert_seek command, see man mpv(1)."""
self.command('revert_seek');
def frame_step(self):
"""Mapped mpv frame_step command, see man mpv(1)."""
self.command('frame_step')
def frame_back_step(self):
"""Mapped mpv frame_back_step command, see man mpv(1)."""
self.command('frame_back_step')
def property_add(self, name, value=1):
"""Add the given value to the property's value. On overflow or underflow, clamp the property to the maximum. If
``value`` is omitted, assume ``1``.
"""
self.command('add', name, value)
def property_multiply(self, name, factor):
"""Multiply the value of a property with a numeric factor."""
self.command('multiply', name, factor)
def cycle(self, name, direction='up'):
"""Cycle the given property. ``up`` and ``down`` set the cycle direction. On overflow, set the property back to
the minimum, on underflow set it to the maximum. If ``up`` or ``down`` is omitted, assume ``up``.
"""
self.command('cycle', name, direction)
def screenshot(self, includes='subtitles', mode='single'):
"""Mapped mpv screenshot command, see man mpv(1)."""
self.command('screenshot', includes, mode)
def screenshot_to_file(self, filename, includes='subtitles'):
"""Mapped mpv screenshot_to_file command, see man mpv(1)."""
self.command('screenshot_to_file', filename.encode(fs_enc), includes)
def screenshot_raw(self, includes='subtitles'):
"""Mapped mpv screenshot_raw command, see man mpv(1). Returns a pillow Image object."""
from PIL import Image
res = self.node_command('screenshot-raw', includes)
if res['format'] != 'bgr0':
raise ValueError('Screenshot in unknown format "{}". Currently, only bgr0 is supported.'
.format(res['format']))
img = Image.frombytes('RGBA', (res['w'], res['h']), res['data'])
b,g,r,a = img.split()
return Image.merge('RGB', (r,g,b))
def playlist_next(self, mode='weak'):
"""Mapped mpv playlist_next command, see man mpv(1)."""
self.command('playlist_next', mode)
def playlist_prev(self, mode='weak'):
"""Mapped mpv playlist_prev command, see man mpv(1)."""
self.command('playlist_prev', mode)
@staticmethod
def _encode_options(options):
return ','.join('{}={}'.format(str(key), str(val)) for key, val in options.items())
def loadfile(self, filename, mode='replace', **options):
"""Mapped mpv loadfile command, see man mpv(1)."""
self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode_options(options))
def loadlist(self, playlist, mode='replace'):
"""Mapped mpv loadlist command, see man mpv(1)."""
self.command('loadlist', playlist.encode(fs_enc), mode)
def playlist_clear(self):
"""Mapped mpv playlist_clear command, see man mpv(1)."""
self.command('playlist_clear')
def playlist_remove(self, index='current'):
"""Mapped mpv playlist_remove command, see man mpv(1)."""
self.command('playlist_remove', index)
def playlist_move(self, index1, index2):
"""Mapped mpv playlist_move command, see man mpv(1)."""
self.command('playlist_move', index1, index2)
def run(self, command, *args):
"""Mapped mpv run command, see man mpv(1)."""
self.command('run', command, *args)
def quit(self, code=None):
"""Mapped mpv quit command, see man mpv(1)."""
self.command('quit', code)
def quit_watch_later(self, code=None):
"""Mapped mpv quit_watch_later command, see man mpv(1)."""
self.command('quit_watch_later', code)
def sub_add(self, filename):
"""Mapped mpv sub_add command, see man mpv(1)."""
self.command('sub_add', filename.encode(fs_enc))
def sub_remove(self, sub_id=None):
"""Mapped mpv sub_remove command, see man mpv(1)."""
self.command('sub_remove', sub_id)
def sub_reload(self, sub_id=None):
"""Mapped mpv sub_reload command, see man mpv(1)."""
self.command('sub_reload', sub_id)
def sub_step(self, skip):
"""Mapped mpv sub_step command, see man mpv(1)."""
self.command('sub_step', skip)
def sub_seek(self, skip):
"""Mapped mpv sub_seek command, see man mpv(1)."""
self.command('sub_seek', skip)
def toggle_osd(self):
"""Mapped mpv osd command, see man mpv(1)."""
self.command('osd')
def show_text(self, string, duration='-1', level=None):
"""Mapped mpv show_text command, see man mpv(1)."""
self.command('show_text', string, duration, level)
def show_progress(self):
"""Mapped mpv show_progress command, see man mpv(1)."""
self.command('show_progress')
def discnav(self, command):
"""Mapped mpv discnav command, see man mpv(1)."""
self.command('discnav', command)
def write_watch_later_config(self):
"""Mapped mpv write_watch_later_config command, see man mpv(1)."""
self.command('write_watch_later_config')
def overlay_add(self, overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride):
"""Mapped mpv overlay_add command, see man mpv(1)."""
self.command('overlay_add', overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride)
def overlay_remove(self, overlay_id):
"""Mapped mpv overlay_remove command, see man mpv(1)."""
self.command('overlay_remove', overlay_id)
def script_message(self, *args):
"""Mapped mpv script_message command, see man mpv(1)."""
self.command('script_message', *args)
def script_message_to(self, target, *args):
"""Mapped mpv script_message_to command, see man mpv(1)."""
self.command('script_message_to', target, *args)
def observe_property(self, name, handler):
"""Register an observer on the named property. An observer is a function that is called with the new property
value every time the property's value is changed. The basic function signature is ``fun(property_name,
new_value)`` with new_value being the decoded property value as a python object. This function can be used as a
function decorator if no handler is given.
To unregister the observer, call either of ``mpv.unobserve_property(name, handler)``,
``mpv.unobserve_all_properties(handler)`` or the handler's ``unregister_mpv_properties`` attribute::
@player.observe_property('volume')
def my_handler(new_volume, *):
print("It's loud!", volume)
my_handler.unregister_mpv_properties()
"""
self._property_handlers[name].append(handler)
_mpv_observe_property(self._event_handle, hash(name)&0xffffffffffffffff, name.encode('utf-8'), MpvFormat.NODE)
def property_observer(self, name):
"""Function decorator to register a property observer. See ``MPV.observe_property`` for details."""
def wrapper(fun):
self.observe_property(name, fun)
fun.unobserve_mpv_properties = lambda: self.unobserve_property(name, fun)
return fun
return wrapper
def unobserve_property(self, name, handler):
"""Unregister a property observer. This requires both the observed property's name and the handler function that
was originally registered as one handler could be registered for several properties. To unregister a handler
from *all* observed properties see ``unobserve_all_properties``.
"""
self._property_handlers[name].remove(handler)
if not self._property_handlers[name]:
_mpv_unobserve_property(self._event_handle, hash(name)&0xffffffffffffffff)
def unobserve_all_properties(self, handler):
"""Unregister a property observer from *all* observed properties."""
for name in self._property_handlers:
self.unobserve_property(name, handler)
def register_message_handler(self, target, handler=None):
"""Register a mpv script message handler. This can be used to communicate with embedded lua scripts. Pass the
script message target name this handler should be listening to and the handler function.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
self._register_message_handler_internal(target, handler)
def _register_message_handler_internal(self, target, handler):
self._message_handlers[target] = handler
def unregister_message_handler(self, target_or_handler):
"""Unregister a mpv script message handler for the given script message target name.
You can also call the ``unregister_mpv_messages`` function attribute set on the handler function when it is
registered.
"""
if isinstance(target_or_handler, str):
del self._message_handlers[target_or_handler]
else:
for key, val in self._message_handlers.items():
if val == target_or_handler:
del self._message_handlers[key]
def message_handler(self, target):
"""Decorator to register a mpv script message handler.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
def register(handler):
self._register_message_handler_internal(target, handler)
handler.unregister_mpv_messages = lambda: self.unregister_message_handler(handler)
return handler
return register
def register_event_callback(self, callback):
"""Register a blanket event callback receiving all event types.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
self._event_callbacks.append(callback)
def unregister_event_callback(self, callback):
"""Unregiser an event callback."""
self._event_callbacks.remove(callback)
def event_callback(self, *event_types):
"""Function decorator to register a blanket event callback for the given event types. Event types can be given
as str (e.g. 'start-file'), integer or MpvEventID object.
WARNING: Due to the way this is filtering events, this decorator cannot be chained with itself.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
def register(callback):
types = [MpvEventID.from_str(t) if isinstance(t, str) else t for t in event_types] or MpvEventID.ANY
@wraps(callback)
def wrapper(event, *args, **kwargs):
if event['event_id'] in types:
callback(event, *args, **kwargs)
self._event_callbacks.append(wrapper)
wrapper.unregister_mpv_events = partial(self.unregister_event_callback, wrapper)
return wrapper
return register
@staticmethod
def _binding_name(callback_or_cmd):
return 'py_kb_{:016x}'.format(hash(callback_or_cmd)&0xffffffffffffffff)
def on_key_press(self, keydef, mode='force'):
"""Function decorator to register a simplified key binding. The callback is called whenever the key given is
*pressed*.
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.on_key_press('Q')
def binding():
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
The BIG FAT WARNING regarding untrusted keydefs from the key_binding method applies here as well.
"""
def register(fun):
@self.key_binding(keydef, mode)
@wraps(fun)
def wrapper(state='p-', name=None):
if state[0] in ('d', 'p'):
fun()
return wrapper
return register
def key_binding(self, keydef, mode='force'):
"""Function decorator to register a low-level key binding.
The callback function signature is ``fun(key_state, key_name)`` where ``key_state`` is either ``'U'`` for "key
up" or ``'D'`` for "key down".
The keydef format is: ``[Shift+][Ctrl+][Alt+][Meta+]<key>`` where ``<key>`` is either the literal character the
key produces (ASCII or Unicode character), or a symbolic name (as printed by ``mpv --input-keylist``).
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.key_binding('Q')
def binding(state, name):
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
BIG FAT WARNING: mpv's key binding mechanism is pretty powerful. This means, you essentially get arbitrary code
exectution through key bindings. This interface makes some limited effort to sanitize the keydef given in the
first parameter, but YOU SHOULD NOT RELY ON THIS IN FOR SECURITY. If your input comes from config files, this is
completely fine--but, if you are about to pass untrusted input into this parameter, better double-check whether
this is secure in your case.
"""
def register(fun):
fun.mpv_key_bindings = getattr(fun, 'mpv_key_bindings', []) + [keydef]
def unregister_all():
for keydef in fun.mpv_key_bindings:
self.unregister_key_binding(keydef)
fun.unregister_mpv_key_bindings = unregister_all
self.register_key_binding(keydef, fun, mode)
return fun
return register
def register_key_binding(self, keydef, callback_or_cmd, mode='force'):
"""Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python
callback function. See ``MPV.key_binding`` for details.
"""
if not re.match(r'(Shift+)?(Ctrl+)?(Alt+)?(Meta+)?(.|\w+)', keydef):
raise ValueError('Invalid keydef. Expected format: [Shift+][Ctrl+][Alt+][Meta+]<key>\n'
'<key> is either the literal character the key produces (ASCII or Unicode character), or a '
'symbolic name (as printed by --input-keylist')
binding_name = MPV._binding_name(keydef)
if callable(callback_or_cmd):
self._key_binding_handlers[binding_name] = callback_or_cmd
self.register_message_handler('key-binding', self._handle_key_binding_message)
self.command('define-section',
binding_name, '{} script-binding py_event_handler/{}'.format(keydef, binding_name), mode)
elif isinstance(callback_or_cmd, str):
self.command('define-section', binding_name, '{} {}'.format(keydef, callback_or_cmd), mode)
else:
raise TypeError('register_key_binding expects either an str with an mpv command or a python callable.')
self.command('enable-section', binding_name, 'allow-hide-cursor+allow-vo-dragging')
def _handle_key_binding_message(self, binding_name, key_state, key_name=None):
self._key_binding_handlers[binding_name](key_state, key_name)
def unregister_key_binding(self, keydef):
"""Unregister a key binding by keydef."""
binding_name = MPV._binding_name(keydef)
self.command('disable-section', binding_name)
self.command('define-section', binding_name, '')
if binding_name in self._key_binding_handlers:
del self._key_binding_handlers[binding_name]
if not self._key_binding_handlers:
self.unregister_message_handler('key-binding')
# Convenience functions
def play(self, filename):
"""Play a path or URL (requires ``ytdl`` option to be set)."""
self.loadfile(filename)
@property
def playlist_filenames(self):
"""Return all playlist item file names/URLs as a list of strs."""
return [element['filename'] for element in self.playlist]
def playlist_append(self, filename, **options):
"""Append a path or URL to the playlist. This does not start playing the file automatically. To do that, use
``MPV.loadfile(filename, 'append-play')``."""
self.loadfile(filename, 'append', **options)
# Property accessors
def _get_property(self, name, decoder=strict_decoder, fmt=MpvFormat.NODE):
out = create_string_buffer(sizeof(MpvNode))
try:
cval = _mpv_get_property(self.handle, name.encode('utf-8'), fmt, out)
if fmt is MpvFormat.OSD_STRING:
return cast(out, POINTER(c_char_p)).contents.value.decode('utf-8')
elif fmt is MpvFormat.NODE:
rv = cast(out, POINTER(MpvNode)).contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
else:
raise TypeError('_get_property only supports NODE and OSD_STRING formats.')
except PropertyUnavailableError as ex:
return None
def _set_property(self, name, value):
ename = name.encode('utf-8')
if isinstance(value, (list, set, dict)):
_1, _2, _3, pointer = _make_node_str_list(value)
_mpv_set_property(self.handle, ename, MpvFormat.NODE, pointer)
else:
_mpv_set_property_string(self.handle, ename, _mpv_coax_proptype(value))
def __getattr__(self, name):
return self._get_property(_py_to_mpv(name), lazy_decoder)
def __setattr__(self, name, value):
try:
if name != 'handle' and not name.startswith('_'):
self._set_property(_py_to_mpv(name), value)
else:
super().__setattr__(name, value)
except AttributeError:
super().__setattr__(name, value)
def __dir__(self):
return super().__dir__() + [ name.replace('-', '_') for name in self.property_list ]
@property
def properties(self):
return { name: self.option_info(name) for name in self.property_list }
# Dict-like option access
def __getitem__(self, name, file_local=False):
"""Get an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._get_property(prefix+name, lazy_decoder)
def __setitem__(self, name, value, file_local=False):
"""Set an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._set_property(prefix+name, value)
def __iter__(self):
"""Iterate over all option names."""
return iter(self.options)
def option_info(self, name):
"""Get information on the given option."""
try:
return self._get_property('option-info/'+name)
except AttributeError:
return None
|
jaseg/python-mpv | mpv.py | MPV.seek | python | def seek(self, amount, reference="relative", precision="default-precise"):
self.command('seek', amount, reference, precision) | Mapped mpv seek command, see man mpv(1). | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L639-L641 | null | class MPV(object):
"""See man mpv(1) for the details of the implemented commands. All mpv properties can be accessed as
``my_mpv.some_property`` and all mpv options can be accessed as ``my_mpv['some-option']``.
By default, properties are returned as decoded ``str`` and an error is thrown if the value does not contain valid
utf-8. To get a decoded ``str`` if possibly but ``bytes`` instead of an error if not, use
``my_mpv.lazy.some_property``. To always get raw ``bytes``, use ``my_mpv.raw.some_property``. To access a
property's decoded OSD value, use ``my_mpv.osd.some_property``.
To get API information on an option, use ``my_mpv.option_info('option-name')``. To get API information on a
property, use ``my_mpv.properties['property-name']``. Take care to use mpv's dashed-names instead of the
underscore_names exposed on the python object.
To make your program not barf hard the first time its used on a weird file system **always** access properties
containing file names or file tags through ``MPV.raw``. """
def __init__(self, *extra_mpv_flags, log_handler=None, start_event_thread=True, loglevel=None, **extra_mpv_opts):
"""Create an MPV instance.
Extra arguments and extra keyword arguments will be passed to mpv as options.
"""
self.handle = _mpv_create()
self._event_thread = None
_mpv_set_option_string(self.handle, b'audio-display', b'no')
istr = lambda o: ('yes' if o else 'no') if type(o) is bool else str(o)
try:
for flag in extra_mpv_flags:
_mpv_set_option_string(self.handle, flag.encode('utf-8'), b'')
for k,v in extra_mpv_opts.items():
_mpv_set_option_string(self.handle, k.replace('_', '-').encode('utf-8'), istr(v).encode('utf-8'))
finally:
_mpv_initialize(self.handle)
self.osd = _OSDPropertyProxy(self)
self.file_local = _FileLocalProxy(self)
self.raw = _DecoderPropertyProxy(self, identity_decoder)
self.strict = _DecoderPropertyProxy(self, strict_decoder)
self.lazy = _DecoderPropertyProxy(self, lazy_decoder)
self._event_callbacks = []
self._property_handlers = collections.defaultdict(lambda: [])
self._message_handlers = {}
self._key_binding_handlers = {}
self._playback_cond = threading.Condition()
self._event_handle = _mpv_create_client(self.handle, b'py_event_handler')
self._loop = partial(_event_loop, self._event_handle, self._playback_cond, self._event_callbacks,
self._message_handlers, self._property_handlers, log_handler)
if loglevel is not None or log_handler is not None:
self.set_loglevel(loglevel or 'terminal-default')
if start_event_thread:
self._event_thread = threading.Thread(target=self._loop, name='MPVEventHandlerThread')
self._event_thread.setDaemon(True)
self._event_thread.start()
else:
self._event_thread = None
def wait_for_playback(self):
"""Waits until playback of the current title is paused or done."""
with self._playback_cond:
self._playback_cond.wait()
def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True):
"""Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for
properties such as ``idle_active`` indicating the player is done with regular playback and just idling around
"""
sema = threading.Semaphore(value=0)
def observer(name, val):
if cond(val):
sema.release()
self.observe_property(name, observer)
if not level_sensitive or not cond(getattr(self, name.replace('-', '_'))):
sema.acquire()
self.unobserve_property(name, observer)
def __del__(self):
if self.handle:
self.terminate()
def terminate(self):
"""Properly terminates this player instance. Preferably use this instead of relying on python's garbage
collector to cause this to be called from the object's destructor.
"""
self.handle, handle = None, self.handle
if threading.current_thread() is self._event_thread:
# Handle special case to allow event handle to be detached.
# This is necessary since otherwise the event thread would deadlock itself.
grim_reaper = threading.Thread(target=lambda: _mpv_terminate_destroy(handle))
grim_reaper.start()
else:
_mpv_terminate_destroy(handle)
if self._event_thread:
self._event_thread.join()
def set_loglevel(self, level):
"""Set MPV's log level. This adjusts which output will be sent to this object's log handlers. If you just want
mpv's regular terminal output, you don't need to adjust this but just need to pass a log handler to the MPV
constructur such as ``MPV(log_handler=print)``.
Valid log levels are "no", "fatal", "error", "warn", "info", "v" "debug" and "trace". For details see your mpv's
client.h header file.
"""
_mpv_request_log_messages(self._event_handle, level.encode('utf-8'))
def command(self, name, *args):
"""Execute a raw command."""
args = [name.encode('utf-8')] + [ (arg if type(arg) is bytes else str(arg).encode('utf-8'))
for arg in args if arg is not None ] + [None]
_mpv_command(self.handle, (c_char_p*len(args))(*args))
def node_command(self, name, *args, decoder=strict_decoder):
_1, _2, _3, pointer = _make_node_str_list([name, *args])
out = cast(create_string_buffer(sizeof(MpvNode)), POINTER(MpvNode))
ppointer = cast(pointer, POINTER(MpvNode))
_mpv_command_node(self.handle, ppointer, out)
rv = out.contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
def revert_seek(self):
"""Mapped mpv revert_seek command, see man mpv(1)."""
self.command('revert_seek');
def frame_step(self):
"""Mapped mpv frame_step command, see man mpv(1)."""
self.command('frame_step')
def frame_back_step(self):
"""Mapped mpv frame_back_step command, see man mpv(1)."""
self.command('frame_back_step')
def property_add(self, name, value=1):
"""Add the given value to the property's value. On overflow or underflow, clamp the property to the maximum. If
``value`` is omitted, assume ``1``.
"""
self.command('add', name, value)
def property_multiply(self, name, factor):
"""Multiply the value of a property with a numeric factor."""
self.command('multiply', name, factor)
def cycle(self, name, direction='up'):
"""Cycle the given property. ``up`` and ``down`` set the cycle direction. On overflow, set the property back to
the minimum, on underflow set it to the maximum. If ``up`` or ``down`` is omitted, assume ``up``.
"""
self.command('cycle', name, direction)
def screenshot(self, includes='subtitles', mode='single'):
"""Mapped mpv screenshot command, see man mpv(1)."""
self.command('screenshot', includes, mode)
def screenshot_to_file(self, filename, includes='subtitles'):
"""Mapped mpv screenshot_to_file command, see man mpv(1)."""
self.command('screenshot_to_file', filename.encode(fs_enc), includes)
def screenshot_raw(self, includes='subtitles'):
"""Mapped mpv screenshot_raw command, see man mpv(1). Returns a pillow Image object."""
from PIL import Image
res = self.node_command('screenshot-raw', includes)
if res['format'] != 'bgr0':
raise ValueError('Screenshot in unknown format "{}". Currently, only bgr0 is supported.'
.format(res['format']))
img = Image.frombytes('RGBA', (res['w'], res['h']), res['data'])
b,g,r,a = img.split()
return Image.merge('RGB', (r,g,b))
def playlist_next(self, mode='weak'):
"""Mapped mpv playlist_next command, see man mpv(1)."""
self.command('playlist_next', mode)
def playlist_prev(self, mode='weak'):
"""Mapped mpv playlist_prev command, see man mpv(1)."""
self.command('playlist_prev', mode)
@staticmethod
def _encode_options(options):
return ','.join('{}={}'.format(str(key), str(val)) for key, val in options.items())
def loadfile(self, filename, mode='replace', **options):
"""Mapped mpv loadfile command, see man mpv(1)."""
self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode_options(options))
def loadlist(self, playlist, mode='replace'):
"""Mapped mpv loadlist command, see man mpv(1)."""
self.command('loadlist', playlist.encode(fs_enc), mode)
def playlist_clear(self):
"""Mapped mpv playlist_clear command, see man mpv(1)."""
self.command('playlist_clear')
def playlist_remove(self, index='current'):
"""Mapped mpv playlist_remove command, see man mpv(1)."""
self.command('playlist_remove', index)
def playlist_move(self, index1, index2):
"""Mapped mpv playlist_move command, see man mpv(1)."""
self.command('playlist_move', index1, index2)
def run(self, command, *args):
"""Mapped mpv run command, see man mpv(1)."""
self.command('run', command, *args)
def quit(self, code=None):
"""Mapped mpv quit command, see man mpv(1)."""
self.command('quit', code)
def quit_watch_later(self, code=None):
"""Mapped mpv quit_watch_later command, see man mpv(1)."""
self.command('quit_watch_later', code)
def sub_add(self, filename):
"""Mapped mpv sub_add command, see man mpv(1)."""
self.command('sub_add', filename.encode(fs_enc))
def sub_remove(self, sub_id=None):
"""Mapped mpv sub_remove command, see man mpv(1)."""
self.command('sub_remove', sub_id)
def sub_reload(self, sub_id=None):
"""Mapped mpv sub_reload command, see man mpv(1)."""
self.command('sub_reload', sub_id)
def sub_step(self, skip):
"""Mapped mpv sub_step command, see man mpv(1)."""
self.command('sub_step', skip)
def sub_seek(self, skip):
"""Mapped mpv sub_seek command, see man mpv(1)."""
self.command('sub_seek', skip)
def toggle_osd(self):
"""Mapped mpv osd command, see man mpv(1)."""
self.command('osd')
def show_text(self, string, duration='-1', level=None):
"""Mapped mpv show_text command, see man mpv(1)."""
self.command('show_text', string, duration, level)
def show_progress(self):
"""Mapped mpv show_progress command, see man mpv(1)."""
self.command('show_progress')
def discnav(self, command):
"""Mapped mpv discnav command, see man mpv(1)."""
self.command('discnav', command)
def write_watch_later_config(self):
"""Mapped mpv write_watch_later_config command, see man mpv(1)."""
self.command('write_watch_later_config')
def overlay_add(self, overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride):
"""Mapped mpv overlay_add command, see man mpv(1)."""
self.command('overlay_add', overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride)
def overlay_remove(self, overlay_id):
"""Mapped mpv overlay_remove command, see man mpv(1)."""
self.command('overlay_remove', overlay_id)
def script_message(self, *args):
"""Mapped mpv script_message command, see man mpv(1)."""
self.command('script_message', *args)
def script_message_to(self, target, *args):
"""Mapped mpv script_message_to command, see man mpv(1)."""
self.command('script_message_to', target, *args)
def observe_property(self, name, handler):
"""Register an observer on the named property. An observer is a function that is called with the new property
value every time the property's value is changed. The basic function signature is ``fun(property_name,
new_value)`` with new_value being the decoded property value as a python object. This function can be used as a
function decorator if no handler is given.
To unregister the observer, call either of ``mpv.unobserve_property(name, handler)``,
``mpv.unobserve_all_properties(handler)`` or the handler's ``unregister_mpv_properties`` attribute::
@player.observe_property('volume')
def my_handler(new_volume, *):
print("It's loud!", volume)
my_handler.unregister_mpv_properties()
"""
self._property_handlers[name].append(handler)
_mpv_observe_property(self._event_handle, hash(name)&0xffffffffffffffff, name.encode('utf-8'), MpvFormat.NODE)
def property_observer(self, name):
"""Function decorator to register a property observer. See ``MPV.observe_property`` for details."""
def wrapper(fun):
self.observe_property(name, fun)
fun.unobserve_mpv_properties = lambda: self.unobserve_property(name, fun)
return fun
return wrapper
def unobserve_property(self, name, handler):
"""Unregister a property observer. This requires both the observed property's name and the handler function that
was originally registered as one handler could be registered for several properties. To unregister a handler
from *all* observed properties see ``unobserve_all_properties``.
"""
self._property_handlers[name].remove(handler)
if not self._property_handlers[name]:
_mpv_unobserve_property(self._event_handle, hash(name)&0xffffffffffffffff)
def unobserve_all_properties(self, handler):
"""Unregister a property observer from *all* observed properties."""
for name in self._property_handlers:
self.unobserve_property(name, handler)
def register_message_handler(self, target, handler=None):
"""Register a mpv script message handler. This can be used to communicate with embedded lua scripts. Pass the
script message target name this handler should be listening to and the handler function.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
self._register_message_handler_internal(target, handler)
def _register_message_handler_internal(self, target, handler):
self._message_handlers[target] = handler
def unregister_message_handler(self, target_or_handler):
"""Unregister a mpv script message handler for the given script message target name.
You can also call the ``unregister_mpv_messages`` function attribute set on the handler function when it is
registered.
"""
if isinstance(target_or_handler, str):
del self._message_handlers[target_or_handler]
else:
for key, val in self._message_handlers.items():
if val == target_or_handler:
del self._message_handlers[key]
def message_handler(self, target):
"""Decorator to register a mpv script message handler.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
def register(handler):
self._register_message_handler_internal(target, handler)
handler.unregister_mpv_messages = lambda: self.unregister_message_handler(handler)
return handler
return register
def register_event_callback(self, callback):
"""Register a blanket event callback receiving all event types.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
self._event_callbacks.append(callback)
def unregister_event_callback(self, callback):
"""Unregiser an event callback."""
self._event_callbacks.remove(callback)
def event_callback(self, *event_types):
"""Function decorator to register a blanket event callback for the given event types. Event types can be given
as str (e.g. 'start-file'), integer or MpvEventID object.
WARNING: Due to the way this is filtering events, this decorator cannot be chained with itself.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
def register(callback):
types = [MpvEventID.from_str(t) if isinstance(t, str) else t for t in event_types] or MpvEventID.ANY
@wraps(callback)
def wrapper(event, *args, **kwargs):
if event['event_id'] in types:
callback(event, *args, **kwargs)
self._event_callbacks.append(wrapper)
wrapper.unregister_mpv_events = partial(self.unregister_event_callback, wrapper)
return wrapper
return register
@staticmethod
def _binding_name(callback_or_cmd):
return 'py_kb_{:016x}'.format(hash(callback_or_cmd)&0xffffffffffffffff)
def on_key_press(self, keydef, mode='force'):
"""Function decorator to register a simplified key binding. The callback is called whenever the key given is
*pressed*.
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.on_key_press('Q')
def binding():
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
The BIG FAT WARNING regarding untrusted keydefs from the key_binding method applies here as well.
"""
def register(fun):
@self.key_binding(keydef, mode)
@wraps(fun)
def wrapper(state='p-', name=None):
if state[0] in ('d', 'p'):
fun()
return wrapper
return register
def key_binding(self, keydef, mode='force'):
"""Function decorator to register a low-level key binding.
The callback function signature is ``fun(key_state, key_name)`` where ``key_state`` is either ``'U'`` for "key
up" or ``'D'`` for "key down".
The keydef format is: ``[Shift+][Ctrl+][Alt+][Meta+]<key>`` where ``<key>`` is either the literal character the
key produces (ASCII or Unicode character), or a symbolic name (as printed by ``mpv --input-keylist``).
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.key_binding('Q')
def binding(state, name):
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
BIG FAT WARNING: mpv's key binding mechanism is pretty powerful. This means, you essentially get arbitrary code
exectution through key bindings. This interface makes some limited effort to sanitize the keydef given in the
first parameter, but YOU SHOULD NOT RELY ON THIS IN FOR SECURITY. If your input comes from config files, this is
completely fine--but, if you are about to pass untrusted input into this parameter, better double-check whether
this is secure in your case.
"""
def register(fun):
fun.mpv_key_bindings = getattr(fun, 'mpv_key_bindings', []) + [keydef]
def unregister_all():
for keydef in fun.mpv_key_bindings:
self.unregister_key_binding(keydef)
fun.unregister_mpv_key_bindings = unregister_all
self.register_key_binding(keydef, fun, mode)
return fun
return register
def register_key_binding(self, keydef, callback_or_cmd, mode='force'):
"""Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python
callback function. See ``MPV.key_binding`` for details.
"""
if not re.match(r'(Shift+)?(Ctrl+)?(Alt+)?(Meta+)?(.|\w+)', keydef):
raise ValueError('Invalid keydef. Expected format: [Shift+][Ctrl+][Alt+][Meta+]<key>\n'
'<key> is either the literal character the key produces (ASCII or Unicode character), or a '
'symbolic name (as printed by --input-keylist')
binding_name = MPV._binding_name(keydef)
if callable(callback_or_cmd):
self._key_binding_handlers[binding_name] = callback_or_cmd
self.register_message_handler('key-binding', self._handle_key_binding_message)
self.command('define-section',
binding_name, '{} script-binding py_event_handler/{}'.format(keydef, binding_name), mode)
elif isinstance(callback_or_cmd, str):
self.command('define-section', binding_name, '{} {}'.format(keydef, callback_or_cmd), mode)
else:
raise TypeError('register_key_binding expects either an str with an mpv command or a python callable.')
self.command('enable-section', binding_name, 'allow-hide-cursor+allow-vo-dragging')
def _handle_key_binding_message(self, binding_name, key_state, key_name=None):
self._key_binding_handlers[binding_name](key_state, key_name)
def unregister_key_binding(self, keydef):
"""Unregister a key binding by keydef."""
binding_name = MPV._binding_name(keydef)
self.command('disable-section', binding_name)
self.command('define-section', binding_name, '')
if binding_name in self._key_binding_handlers:
del self._key_binding_handlers[binding_name]
if not self._key_binding_handlers:
self.unregister_message_handler('key-binding')
# Convenience functions
def play(self, filename):
"""Play a path or URL (requires ``ytdl`` option to be set)."""
self.loadfile(filename)
@property
def playlist_filenames(self):
"""Return all playlist item file names/URLs as a list of strs."""
return [element['filename'] for element in self.playlist]
def playlist_append(self, filename, **options):
"""Append a path or URL to the playlist. This does not start playing the file automatically. To do that, use
``MPV.loadfile(filename, 'append-play')``."""
self.loadfile(filename, 'append', **options)
# Property accessors
def _get_property(self, name, decoder=strict_decoder, fmt=MpvFormat.NODE):
out = create_string_buffer(sizeof(MpvNode))
try:
cval = _mpv_get_property(self.handle, name.encode('utf-8'), fmt, out)
if fmt is MpvFormat.OSD_STRING:
return cast(out, POINTER(c_char_p)).contents.value.decode('utf-8')
elif fmt is MpvFormat.NODE:
rv = cast(out, POINTER(MpvNode)).contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
else:
raise TypeError('_get_property only supports NODE and OSD_STRING formats.')
except PropertyUnavailableError as ex:
return None
def _set_property(self, name, value):
ename = name.encode('utf-8')
if isinstance(value, (list, set, dict)):
_1, _2, _3, pointer = _make_node_str_list(value)
_mpv_set_property(self.handle, ename, MpvFormat.NODE, pointer)
else:
_mpv_set_property_string(self.handle, ename, _mpv_coax_proptype(value))
def __getattr__(self, name):
return self._get_property(_py_to_mpv(name), lazy_decoder)
def __setattr__(self, name, value):
try:
if name != 'handle' and not name.startswith('_'):
self._set_property(_py_to_mpv(name), value)
else:
super().__setattr__(name, value)
except AttributeError:
super().__setattr__(name, value)
def __dir__(self):
return super().__dir__() + [ name.replace('-', '_') for name in self.property_list ]
@property
def properties(self):
return { name: self.option_info(name) for name in self.property_list }
# Dict-like option access
def __getitem__(self, name, file_local=False):
"""Get an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._get_property(prefix+name, lazy_decoder)
def __setitem__(self, name, value, file_local=False):
"""Set an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._set_property(prefix+name, value)
def __iter__(self):
"""Iterate over all option names."""
return iter(self.options)
def option_info(self, name):
"""Get information on the given option."""
try:
return self._get_property('option-info/'+name)
except AttributeError:
return None
|
jaseg/python-mpv | mpv.py | MPV.screenshot_to_file | python | def screenshot_to_file(self, filename, includes='subtitles'):
self.command('screenshot_to_file', filename.encode(fs_enc), includes) | Mapped mpv screenshot_to_file command, see man mpv(1). | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L675-L677 | null | class MPV(object):
"""See man mpv(1) for the details of the implemented commands. All mpv properties can be accessed as
``my_mpv.some_property`` and all mpv options can be accessed as ``my_mpv['some-option']``.
By default, properties are returned as decoded ``str`` and an error is thrown if the value does not contain valid
utf-8. To get a decoded ``str`` if possibly but ``bytes`` instead of an error if not, use
``my_mpv.lazy.some_property``. To always get raw ``bytes``, use ``my_mpv.raw.some_property``. To access a
property's decoded OSD value, use ``my_mpv.osd.some_property``.
To get API information on an option, use ``my_mpv.option_info('option-name')``. To get API information on a
property, use ``my_mpv.properties['property-name']``. Take care to use mpv's dashed-names instead of the
underscore_names exposed on the python object.
To make your program not barf hard the first time its used on a weird file system **always** access properties
containing file names or file tags through ``MPV.raw``. """
def __init__(self, *extra_mpv_flags, log_handler=None, start_event_thread=True, loglevel=None, **extra_mpv_opts):
"""Create an MPV instance.
Extra arguments and extra keyword arguments will be passed to mpv as options.
"""
self.handle = _mpv_create()
self._event_thread = None
_mpv_set_option_string(self.handle, b'audio-display', b'no')
istr = lambda o: ('yes' if o else 'no') if type(o) is bool else str(o)
try:
for flag in extra_mpv_flags:
_mpv_set_option_string(self.handle, flag.encode('utf-8'), b'')
for k,v in extra_mpv_opts.items():
_mpv_set_option_string(self.handle, k.replace('_', '-').encode('utf-8'), istr(v).encode('utf-8'))
finally:
_mpv_initialize(self.handle)
self.osd = _OSDPropertyProxy(self)
self.file_local = _FileLocalProxy(self)
self.raw = _DecoderPropertyProxy(self, identity_decoder)
self.strict = _DecoderPropertyProxy(self, strict_decoder)
self.lazy = _DecoderPropertyProxy(self, lazy_decoder)
self._event_callbacks = []
self._property_handlers = collections.defaultdict(lambda: [])
self._message_handlers = {}
self._key_binding_handlers = {}
self._playback_cond = threading.Condition()
self._event_handle = _mpv_create_client(self.handle, b'py_event_handler')
self._loop = partial(_event_loop, self._event_handle, self._playback_cond, self._event_callbacks,
self._message_handlers, self._property_handlers, log_handler)
if loglevel is not None or log_handler is not None:
self.set_loglevel(loglevel or 'terminal-default')
if start_event_thread:
self._event_thread = threading.Thread(target=self._loop, name='MPVEventHandlerThread')
self._event_thread.setDaemon(True)
self._event_thread.start()
else:
self._event_thread = None
def wait_for_playback(self):
"""Waits until playback of the current title is paused or done."""
with self._playback_cond:
self._playback_cond.wait()
def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True):
"""Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for
properties such as ``idle_active`` indicating the player is done with regular playback and just idling around
"""
sema = threading.Semaphore(value=0)
def observer(name, val):
if cond(val):
sema.release()
self.observe_property(name, observer)
if not level_sensitive or not cond(getattr(self, name.replace('-', '_'))):
sema.acquire()
self.unobserve_property(name, observer)
def __del__(self):
if self.handle:
self.terminate()
def terminate(self):
"""Properly terminates this player instance. Preferably use this instead of relying on python's garbage
collector to cause this to be called from the object's destructor.
"""
self.handle, handle = None, self.handle
if threading.current_thread() is self._event_thread:
# Handle special case to allow event handle to be detached.
# This is necessary since otherwise the event thread would deadlock itself.
grim_reaper = threading.Thread(target=lambda: _mpv_terminate_destroy(handle))
grim_reaper.start()
else:
_mpv_terminate_destroy(handle)
if self._event_thread:
self._event_thread.join()
def set_loglevel(self, level):
"""Set MPV's log level. This adjusts which output will be sent to this object's log handlers. If you just want
mpv's regular terminal output, you don't need to adjust this but just need to pass a log handler to the MPV
constructur such as ``MPV(log_handler=print)``.
Valid log levels are "no", "fatal", "error", "warn", "info", "v" "debug" and "trace". For details see your mpv's
client.h header file.
"""
_mpv_request_log_messages(self._event_handle, level.encode('utf-8'))
def command(self, name, *args):
"""Execute a raw command."""
args = [name.encode('utf-8')] + [ (arg if type(arg) is bytes else str(arg).encode('utf-8'))
for arg in args if arg is not None ] + [None]
_mpv_command(self.handle, (c_char_p*len(args))(*args))
def node_command(self, name, *args, decoder=strict_decoder):
_1, _2, _3, pointer = _make_node_str_list([name, *args])
out = cast(create_string_buffer(sizeof(MpvNode)), POINTER(MpvNode))
ppointer = cast(pointer, POINTER(MpvNode))
_mpv_command_node(self.handle, ppointer, out)
rv = out.contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
def seek(self, amount, reference="relative", precision="default-precise"):
"""Mapped mpv seek command, see man mpv(1)."""
self.command('seek', amount, reference, precision)
def revert_seek(self):
"""Mapped mpv revert_seek command, see man mpv(1)."""
self.command('revert_seek');
def frame_step(self):
"""Mapped mpv frame_step command, see man mpv(1)."""
self.command('frame_step')
def frame_back_step(self):
"""Mapped mpv frame_back_step command, see man mpv(1)."""
self.command('frame_back_step')
def property_add(self, name, value=1):
"""Add the given value to the property's value. On overflow or underflow, clamp the property to the maximum. If
``value`` is omitted, assume ``1``.
"""
self.command('add', name, value)
def property_multiply(self, name, factor):
"""Multiply the value of a property with a numeric factor."""
self.command('multiply', name, factor)
def cycle(self, name, direction='up'):
"""Cycle the given property. ``up`` and ``down`` set the cycle direction. On overflow, set the property back to
the minimum, on underflow set it to the maximum. If ``up`` or ``down`` is omitted, assume ``up``.
"""
self.command('cycle', name, direction)
def screenshot(self, includes='subtitles', mode='single'):
"""Mapped mpv screenshot command, see man mpv(1)."""
self.command('screenshot', includes, mode)
def screenshot_raw(self, includes='subtitles'):
"""Mapped mpv screenshot_raw command, see man mpv(1). Returns a pillow Image object."""
from PIL import Image
res = self.node_command('screenshot-raw', includes)
if res['format'] != 'bgr0':
raise ValueError('Screenshot in unknown format "{}". Currently, only bgr0 is supported.'
.format(res['format']))
img = Image.frombytes('RGBA', (res['w'], res['h']), res['data'])
b,g,r,a = img.split()
return Image.merge('RGB', (r,g,b))
def playlist_next(self, mode='weak'):
"""Mapped mpv playlist_next command, see man mpv(1)."""
self.command('playlist_next', mode)
def playlist_prev(self, mode='weak'):
"""Mapped mpv playlist_prev command, see man mpv(1)."""
self.command('playlist_prev', mode)
@staticmethod
def _encode_options(options):
return ','.join('{}={}'.format(str(key), str(val)) for key, val in options.items())
def loadfile(self, filename, mode='replace', **options):
"""Mapped mpv loadfile command, see man mpv(1)."""
self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode_options(options))
def loadlist(self, playlist, mode='replace'):
"""Mapped mpv loadlist command, see man mpv(1)."""
self.command('loadlist', playlist.encode(fs_enc), mode)
def playlist_clear(self):
"""Mapped mpv playlist_clear command, see man mpv(1)."""
self.command('playlist_clear')
def playlist_remove(self, index='current'):
"""Mapped mpv playlist_remove command, see man mpv(1)."""
self.command('playlist_remove', index)
def playlist_move(self, index1, index2):
"""Mapped mpv playlist_move command, see man mpv(1)."""
self.command('playlist_move', index1, index2)
def run(self, command, *args):
"""Mapped mpv run command, see man mpv(1)."""
self.command('run', command, *args)
def quit(self, code=None):
"""Mapped mpv quit command, see man mpv(1)."""
self.command('quit', code)
def quit_watch_later(self, code=None):
"""Mapped mpv quit_watch_later command, see man mpv(1)."""
self.command('quit_watch_later', code)
def sub_add(self, filename):
"""Mapped mpv sub_add command, see man mpv(1)."""
self.command('sub_add', filename.encode(fs_enc))
def sub_remove(self, sub_id=None):
"""Mapped mpv sub_remove command, see man mpv(1)."""
self.command('sub_remove', sub_id)
def sub_reload(self, sub_id=None):
"""Mapped mpv sub_reload command, see man mpv(1)."""
self.command('sub_reload', sub_id)
def sub_step(self, skip):
"""Mapped mpv sub_step command, see man mpv(1)."""
self.command('sub_step', skip)
def sub_seek(self, skip):
"""Mapped mpv sub_seek command, see man mpv(1)."""
self.command('sub_seek', skip)
def toggle_osd(self):
"""Mapped mpv osd command, see man mpv(1)."""
self.command('osd')
def show_text(self, string, duration='-1', level=None):
"""Mapped mpv show_text command, see man mpv(1)."""
self.command('show_text', string, duration, level)
def show_progress(self):
"""Mapped mpv show_progress command, see man mpv(1)."""
self.command('show_progress')
def discnav(self, command):
"""Mapped mpv discnav command, see man mpv(1)."""
self.command('discnav', command)
def write_watch_later_config(self):
"""Mapped mpv write_watch_later_config command, see man mpv(1)."""
self.command('write_watch_later_config')
def overlay_add(self, overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride):
"""Mapped mpv overlay_add command, see man mpv(1)."""
self.command('overlay_add', overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride)
def overlay_remove(self, overlay_id):
"""Mapped mpv overlay_remove command, see man mpv(1)."""
self.command('overlay_remove', overlay_id)
def script_message(self, *args):
"""Mapped mpv script_message command, see man mpv(1)."""
self.command('script_message', *args)
def script_message_to(self, target, *args):
"""Mapped mpv script_message_to command, see man mpv(1)."""
self.command('script_message_to', target, *args)
def observe_property(self, name, handler):
"""Register an observer on the named property. An observer is a function that is called with the new property
value every time the property's value is changed. The basic function signature is ``fun(property_name,
new_value)`` with new_value being the decoded property value as a python object. This function can be used as a
function decorator if no handler is given.
To unregister the observer, call either of ``mpv.unobserve_property(name, handler)``,
``mpv.unobserve_all_properties(handler)`` or the handler's ``unregister_mpv_properties`` attribute::
@player.observe_property('volume')
def my_handler(new_volume, *):
print("It's loud!", volume)
my_handler.unregister_mpv_properties()
"""
self._property_handlers[name].append(handler)
_mpv_observe_property(self._event_handle, hash(name)&0xffffffffffffffff, name.encode('utf-8'), MpvFormat.NODE)
def property_observer(self, name):
"""Function decorator to register a property observer. See ``MPV.observe_property`` for details."""
def wrapper(fun):
self.observe_property(name, fun)
fun.unobserve_mpv_properties = lambda: self.unobserve_property(name, fun)
return fun
return wrapper
def unobserve_property(self, name, handler):
"""Unregister a property observer. This requires both the observed property's name and the handler function that
was originally registered as one handler could be registered for several properties. To unregister a handler
from *all* observed properties see ``unobserve_all_properties``.
"""
self._property_handlers[name].remove(handler)
if not self._property_handlers[name]:
_mpv_unobserve_property(self._event_handle, hash(name)&0xffffffffffffffff)
def unobserve_all_properties(self, handler):
"""Unregister a property observer from *all* observed properties."""
for name in self._property_handlers:
self.unobserve_property(name, handler)
def register_message_handler(self, target, handler=None):
"""Register a mpv script message handler. This can be used to communicate with embedded lua scripts. Pass the
script message target name this handler should be listening to and the handler function.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
self._register_message_handler_internal(target, handler)
def _register_message_handler_internal(self, target, handler):
self._message_handlers[target] = handler
def unregister_message_handler(self, target_or_handler):
"""Unregister a mpv script message handler for the given script message target name.
You can also call the ``unregister_mpv_messages`` function attribute set on the handler function when it is
registered.
"""
if isinstance(target_or_handler, str):
del self._message_handlers[target_or_handler]
else:
for key, val in self._message_handlers.items():
if val == target_or_handler:
del self._message_handlers[key]
def message_handler(self, target):
"""Decorator to register a mpv script message handler.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
def register(handler):
self._register_message_handler_internal(target, handler)
handler.unregister_mpv_messages = lambda: self.unregister_message_handler(handler)
return handler
return register
def register_event_callback(self, callback):
"""Register a blanket event callback receiving all event types.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
self._event_callbacks.append(callback)
def unregister_event_callback(self, callback):
"""Unregiser an event callback."""
self._event_callbacks.remove(callback)
def event_callback(self, *event_types):
"""Function decorator to register a blanket event callback for the given event types. Event types can be given
as str (e.g. 'start-file'), integer or MpvEventID object.
WARNING: Due to the way this is filtering events, this decorator cannot be chained with itself.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
def register(callback):
types = [MpvEventID.from_str(t) if isinstance(t, str) else t for t in event_types] or MpvEventID.ANY
@wraps(callback)
def wrapper(event, *args, **kwargs):
if event['event_id'] in types:
callback(event, *args, **kwargs)
self._event_callbacks.append(wrapper)
wrapper.unregister_mpv_events = partial(self.unregister_event_callback, wrapper)
return wrapper
return register
@staticmethod
def _binding_name(callback_or_cmd):
return 'py_kb_{:016x}'.format(hash(callback_or_cmd)&0xffffffffffffffff)
def on_key_press(self, keydef, mode='force'):
"""Function decorator to register a simplified key binding. The callback is called whenever the key given is
*pressed*.
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.on_key_press('Q')
def binding():
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
The BIG FAT WARNING regarding untrusted keydefs from the key_binding method applies here as well.
"""
def register(fun):
@self.key_binding(keydef, mode)
@wraps(fun)
def wrapper(state='p-', name=None):
if state[0] in ('d', 'p'):
fun()
return wrapper
return register
def key_binding(self, keydef, mode='force'):
"""Function decorator to register a low-level key binding.
The callback function signature is ``fun(key_state, key_name)`` where ``key_state`` is either ``'U'`` for "key
up" or ``'D'`` for "key down".
The keydef format is: ``[Shift+][Ctrl+][Alt+][Meta+]<key>`` where ``<key>`` is either the literal character the
key produces (ASCII or Unicode character), or a symbolic name (as printed by ``mpv --input-keylist``).
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.key_binding('Q')
def binding(state, name):
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
BIG FAT WARNING: mpv's key binding mechanism is pretty powerful. This means, you essentially get arbitrary code
exectution through key bindings. This interface makes some limited effort to sanitize the keydef given in the
first parameter, but YOU SHOULD NOT RELY ON THIS IN FOR SECURITY. If your input comes from config files, this is
completely fine--but, if you are about to pass untrusted input into this parameter, better double-check whether
this is secure in your case.
"""
def register(fun):
fun.mpv_key_bindings = getattr(fun, 'mpv_key_bindings', []) + [keydef]
def unregister_all():
for keydef in fun.mpv_key_bindings:
self.unregister_key_binding(keydef)
fun.unregister_mpv_key_bindings = unregister_all
self.register_key_binding(keydef, fun, mode)
return fun
return register
def register_key_binding(self, keydef, callback_or_cmd, mode='force'):
"""Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python
callback function. See ``MPV.key_binding`` for details.
"""
if not re.match(r'(Shift+)?(Ctrl+)?(Alt+)?(Meta+)?(.|\w+)', keydef):
raise ValueError('Invalid keydef. Expected format: [Shift+][Ctrl+][Alt+][Meta+]<key>\n'
'<key> is either the literal character the key produces (ASCII or Unicode character), or a '
'symbolic name (as printed by --input-keylist')
binding_name = MPV._binding_name(keydef)
if callable(callback_or_cmd):
self._key_binding_handlers[binding_name] = callback_or_cmd
self.register_message_handler('key-binding', self._handle_key_binding_message)
self.command('define-section',
binding_name, '{} script-binding py_event_handler/{}'.format(keydef, binding_name), mode)
elif isinstance(callback_or_cmd, str):
self.command('define-section', binding_name, '{} {}'.format(keydef, callback_or_cmd), mode)
else:
raise TypeError('register_key_binding expects either an str with an mpv command or a python callable.')
self.command('enable-section', binding_name, 'allow-hide-cursor+allow-vo-dragging')
def _handle_key_binding_message(self, binding_name, key_state, key_name=None):
self._key_binding_handlers[binding_name](key_state, key_name)
def unregister_key_binding(self, keydef):
"""Unregister a key binding by keydef."""
binding_name = MPV._binding_name(keydef)
self.command('disable-section', binding_name)
self.command('define-section', binding_name, '')
if binding_name in self._key_binding_handlers:
del self._key_binding_handlers[binding_name]
if not self._key_binding_handlers:
self.unregister_message_handler('key-binding')
# Convenience functions
def play(self, filename):
"""Play a path or URL (requires ``ytdl`` option to be set)."""
self.loadfile(filename)
@property
def playlist_filenames(self):
"""Return all playlist item file names/URLs as a list of strs."""
return [element['filename'] for element in self.playlist]
def playlist_append(self, filename, **options):
"""Append a path or URL to the playlist. This does not start playing the file automatically. To do that, use
``MPV.loadfile(filename, 'append-play')``."""
self.loadfile(filename, 'append', **options)
# Property accessors
def _get_property(self, name, decoder=strict_decoder, fmt=MpvFormat.NODE):
out = create_string_buffer(sizeof(MpvNode))
try:
cval = _mpv_get_property(self.handle, name.encode('utf-8'), fmt, out)
if fmt is MpvFormat.OSD_STRING:
return cast(out, POINTER(c_char_p)).contents.value.decode('utf-8')
elif fmt is MpvFormat.NODE:
rv = cast(out, POINTER(MpvNode)).contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
else:
raise TypeError('_get_property only supports NODE and OSD_STRING formats.')
except PropertyUnavailableError as ex:
return None
def _set_property(self, name, value):
ename = name.encode('utf-8')
if isinstance(value, (list, set, dict)):
_1, _2, _3, pointer = _make_node_str_list(value)
_mpv_set_property(self.handle, ename, MpvFormat.NODE, pointer)
else:
_mpv_set_property_string(self.handle, ename, _mpv_coax_proptype(value))
def __getattr__(self, name):
return self._get_property(_py_to_mpv(name), lazy_decoder)
def __setattr__(self, name, value):
try:
if name != 'handle' and not name.startswith('_'):
self._set_property(_py_to_mpv(name), value)
else:
super().__setattr__(name, value)
except AttributeError:
super().__setattr__(name, value)
def __dir__(self):
return super().__dir__() + [ name.replace('-', '_') for name in self.property_list ]
@property
def properties(self):
return { name: self.option_info(name) for name in self.property_list }
# Dict-like option access
def __getitem__(self, name, file_local=False):
"""Get an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._get_property(prefix+name, lazy_decoder)
def __setitem__(self, name, value, file_local=False):
"""Set an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._set_property(prefix+name, value)
def __iter__(self):
"""Iterate over all option names."""
return iter(self.options)
def option_info(self, name):
"""Get information on the given option."""
try:
return self._get_property('option-info/'+name)
except AttributeError:
return None
|
jaseg/python-mpv | mpv.py | MPV.screenshot_raw | python | def screenshot_raw(self, includes='subtitles'):
from PIL import Image
res = self.node_command('screenshot-raw', includes)
if res['format'] != 'bgr0':
raise ValueError('Screenshot in unknown format "{}". Currently, only bgr0 is supported.'
.format(res['format']))
img = Image.frombytes('RGBA', (res['w'], res['h']), res['data'])
b,g,r,a = img.split()
return Image.merge('RGB', (r,g,b)) | Mapped mpv screenshot_raw command, see man mpv(1). Returns a pillow Image object. | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L679-L688 | null | class MPV(object):
"""See man mpv(1) for the details of the implemented commands. All mpv properties can be accessed as
``my_mpv.some_property`` and all mpv options can be accessed as ``my_mpv['some-option']``.
By default, properties are returned as decoded ``str`` and an error is thrown if the value does not contain valid
utf-8. To get a decoded ``str`` if possibly but ``bytes`` instead of an error if not, use
``my_mpv.lazy.some_property``. To always get raw ``bytes``, use ``my_mpv.raw.some_property``. To access a
property's decoded OSD value, use ``my_mpv.osd.some_property``.
To get API information on an option, use ``my_mpv.option_info('option-name')``. To get API information on a
property, use ``my_mpv.properties['property-name']``. Take care to use mpv's dashed-names instead of the
underscore_names exposed on the python object.
To make your program not barf hard the first time its used on a weird file system **always** access properties
containing file names or file tags through ``MPV.raw``. """
def __init__(self, *extra_mpv_flags, log_handler=None, start_event_thread=True, loglevel=None, **extra_mpv_opts):
"""Create an MPV instance.
Extra arguments and extra keyword arguments will be passed to mpv as options.
"""
self.handle = _mpv_create()
self._event_thread = None
_mpv_set_option_string(self.handle, b'audio-display', b'no')
istr = lambda o: ('yes' if o else 'no') if type(o) is bool else str(o)
try:
for flag in extra_mpv_flags:
_mpv_set_option_string(self.handle, flag.encode('utf-8'), b'')
for k,v in extra_mpv_opts.items():
_mpv_set_option_string(self.handle, k.replace('_', '-').encode('utf-8'), istr(v).encode('utf-8'))
finally:
_mpv_initialize(self.handle)
self.osd = _OSDPropertyProxy(self)
self.file_local = _FileLocalProxy(self)
self.raw = _DecoderPropertyProxy(self, identity_decoder)
self.strict = _DecoderPropertyProxy(self, strict_decoder)
self.lazy = _DecoderPropertyProxy(self, lazy_decoder)
self._event_callbacks = []
self._property_handlers = collections.defaultdict(lambda: [])
self._message_handlers = {}
self._key_binding_handlers = {}
self._playback_cond = threading.Condition()
self._event_handle = _mpv_create_client(self.handle, b'py_event_handler')
self._loop = partial(_event_loop, self._event_handle, self._playback_cond, self._event_callbacks,
self._message_handlers, self._property_handlers, log_handler)
if loglevel is not None or log_handler is not None:
self.set_loglevel(loglevel or 'terminal-default')
if start_event_thread:
self._event_thread = threading.Thread(target=self._loop, name='MPVEventHandlerThread')
self._event_thread.setDaemon(True)
self._event_thread.start()
else:
self._event_thread = None
def wait_for_playback(self):
"""Waits until playback of the current title is paused or done."""
with self._playback_cond:
self._playback_cond.wait()
def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True):
"""Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for
properties such as ``idle_active`` indicating the player is done with regular playback and just idling around
"""
sema = threading.Semaphore(value=0)
def observer(name, val):
if cond(val):
sema.release()
self.observe_property(name, observer)
if not level_sensitive or not cond(getattr(self, name.replace('-', '_'))):
sema.acquire()
self.unobserve_property(name, observer)
def __del__(self):
if self.handle:
self.terminate()
def terminate(self):
"""Properly terminates this player instance. Preferably use this instead of relying on python's garbage
collector to cause this to be called from the object's destructor.
"""
self.handle, handle = None, self.handle
if threading.current_thread() is self._event_thread:
# Handle special case to allow event handle to be detached.
# This is necessary since otherwise the event thread would deadlock itself.
grim_reaper = threading.Thread(target=lambda: _mpv_terminate_destroy(handle))
grim_reaper.start()
else:
_mpv_terminate_destroy(handle)
if self._event_thread:
self._event_thread.join()
def set_loglevel(self, level):
"""Set MPV's log level. This adjusts which output will be sent to this object's log handlers. If you just want
mpv's regular terminal output, you don't need to adjust this but just need to pass a log handler to the MPV
constructur such as ``MPV(log_handler=print)``.
Valid log levels are "no", "fatal", "error", "warn", "info", "v" "debug" and "trace". For details see your mpv's
client.h header file.
"""
_mpv_request_log_messages(self._event_handle, level.encode('utf-8'))
def command(self, name, *args):
"""Execute a raw command."""
args = [name.encode('utf-8')] + [ (arg if type(arg) is bytes else str(arg).encode('utf-8'))
for arg in args if arg is not None ] + [None]
_mpv_command(self.handle, (c_char_p*len(args))(*args))
def node_command(self, name, *args, decoder=strict_decoder):
_1, _2, _3, pointer = _make_node_str_list([name, *args])
out = cast(create_string_buffer(sizeof(MpvNode)), POINTER(MpvNode))
ppointer = cast(pointer, POINTER(MpvNode))
_mpv_command_node(self.handle, ppointer, out)
rv = out.contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
def seek(self, amount, reference="relative", precision="default-precise"):
"""Mapped mpv seek command, see man mpv(1)."""
self.command('seek', amount, reference, precision)
def revert_seek(self):
"""Mapped mpv revert_seek command, see man mpv(1)."""
self.command('revert_seek');
def frame_step(self):
"""Mapped mpv frame_step command, see man mpv(1)."""
self.command('frame_step')
def frame_back_step(self):
"""Mapped mpv frame_back_step command, see man mpv(1)."""
self.command('frame_back_step')
def property_add(self, name, value=1):
"""Add the given value to the property's value. On overflow or underflow, clamp the property to the maximum. If
``value`` is omitted, assume ``1``.
"""
self.command('add', name, value)
def property_multiply(self, name, factor):
"""Multiply the value of a property with a numeric factor."""
self.command('multiply', name, factor)
def cycle(self, name, direction='up'):
"""Cycle the given property. ``up`` and ``down`` set the cycle direction. On overflow, set the property back to
the minimum, on underflow set it to the maximum. If ``up`` or ``down`` is omitted, assume ``up``.
"""
self.command('cycle', name, direction)
def screenshot(self, includes='subtitles', mode='single'):
"""Mapped mpv screenshot command, see man mpv(1)."""
self.command('screenshot', includes, mode)
def screenshot_to_file(self, filename, includes='subtitles'):
"""Mapped mpv screenshot_to_file command, see man mpv(1)."""
self.command('screenshot_to_file', filename.encode(fs_enc), includes)
def playlist_next(self, mode='weak'):
"""Mapped mpv playlist_next command, see man mpv(1)."""
self.command('playlist_next', mode)
def playlist_prev(self, mode='weak'):
"""Mapped mpv playlist_prev command, see man mpv(1)."""
self.command('playlist_prev', mode)
@staticmethod
def _encode_options(options):
return ','.join('{}={}'.format(str(key), str(val)) for key, val in options.items())
def loadfile(self, filename, mode='replace', **options):
"""Mapped mpv loadfile command, see man mpv(1)."""
self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode_options(options))
def loadlist(self, playlist, mode='replace'):
"""Mapped mpv loadlist command, see man mpv(1)."""
self.command('loadlist', playlist.encode(fs_enc), mode)
def playlist_clear(self):
"""Mapped mpv playlist_clear command, see man mpv(1)."""
self.command('playlist_clear')
def playlist_remove(self, index='current'):
"""Mapped mpv playlist_remove command, see man mpv(1)."""
self.command('playlist_remove', index)
def playlist_move(self, index1, index2):
"""Mapped mpv playlist_move command, see man mpv(1)."""
self.command('playlist_move', index1, index2)
def run(self, command, *args):
"""Mapped mpv run command, see man mpv(1)."""
self.command('run', command, *args)
def quit(self, code=None):
"""Mapped mpv quit command, see man mpv(1)."""
self.command('quit', code)
def quit_watch_later(self, code=None):
"""Mapped mpv quit_watch_later command, see man mpv(1)."""
self.command('quit_watch_later', code)
def sub_add(self, filename):
"""Mapped mpv sub_add command, see man mpv(1)."""
self.command('sub_add', filename.encode(fs_enc))
def sub_remove(self, sub_id=None):
"""Mapped mpv sub_remove command, see man mpv(1)."""
self.command('sub_remove', sub_id)
def sub_reload(self, sub_id=None):
"""Mapped mpv sub_reload command, see man mpv(1)."""
self.command('sub_reload', sub_id)
def sub_step(self, skip):
"""Mapped mpv sub_step command, see man mpv(1)."""
self.command('sub_step', skip)
def sub_seek(self, skip):
"""Mapped mpv sub_seek command, see man mpv(1)."""
self.command('sub_seek', skip)
def toggle_osd(self):
"""Mapped mpv osd command, see man mpv(1)."""
self.command('osd')
def show_text(self, string, duration='-1', level=None):
"""Mapped mpv show_text command, see man mpv(1)."""
self.command('show_text', string, duration, level)
def show_progress(self):
"""Mapped mpv show_progress command, see man mpv(1)."""
self.command('show_progress')
def discnav(self, command):
"""Mapped mpv discnav command, see man mpv(1)."""
self.command('discnav', command)
def write_watch_later_config(self):
"""Mapped mpv write_watch_later_config command, see man mpv(1)."""
self.command('write_watch_later_config')
def overlay_add(self, overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride):
"""Mapped mpv overlay_add command, see man mpv(1)."""
self.command('overlay_add', overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride)
def overlay_remove(self, overlay_id):
"""Mapped mpv overlay_remove command, see man mpv(1)."""
self.command('overlay_remove', overlay_id)
def script_message(self, *args):
"""Mapped mpv script_message command, see man mpv(1)."""
self.command('script_message', *args)
def script_message_to(self, target, *args):
"""Mapped mpv script_message_to command, see man mpv(1)."""
self.command('script_message_to', target, *args)
def observe_property(self, name, handler):
"""Register an observer on the named property. An observer is a function that is called with the new property
value every time the property's value is changed. The basic function signature is ``fun(property_name,
new_value)`` with new_value being the decoded property value as a python object. This function can be used as a
function decorator if no handler is given.
To unregister the observer, call either of ``mpv.unobserve_property(name, handler)``,
``mpv.unobserve_all_properties(handler)`` or the handler's ``unregister_mpv_properties`` attribute::
@player.observe_property('volume')
def my_handler(new_volume, *):
print("It's loud!", volume)
my_handler.unregister_mpv_properties()
"""
self._property_handlers[name].append(handler)
_mpv_observe_property(self._event_handle, hash(name)&0xffffffffffffffff, name.encode('utf-8'), MpvFormat.NODE)
def property_observer(self, name):
"""Function decorator to register a property observer. See ``MPV.observe_property`` for details."""
def wrapper(fun):
self.observe_property(name, fun)
fun.unobserve_mpv_properties = lambda: self.unobserve_property(name, fun)
return fun
return wrapper
def unobserve_property(self, name, handler):
"""Unregister a property observer. This requires both the observed property's name and the handler function that
was originally registered as one handler could be registered for several properties. To unregister a handler
from *all* observed properties see ``unobserve_all_properties``.
"""
self._property_handlers[name].remove(handler)
if not self._property_handlers[name]:
_mpv_unobserve_property(self._event_handle, hash(name)&0xffffffffffffffff)
def unobserve_all_properties(self, handler):
"""Unregister a property observer from *all* observed properties."""
for name in self._property_handlers:
self.unobserve_property(name, handler)
def register_message_handler(self, target, handler=None):
"""Register a mpv script message handler. This can be used to communicate with embedded lua scripts. Pass the
script message target name this handler should be listening to and the handler function.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
self._register_message_handler_internal(target, handler)
def _register_message_handler_internal(self, target, handler):
self._message_handlers[target] = handler
def unregister_message_handler(self, target_or_handler):
"""Unregister a mpv script message handler for the given script message target name.
You can also call the ``unregister_mpv_messages`` function attribute set on the handler function when it is
registered.
"""
if isinstance(target_or_handler, str):
del self._message_handlers[target_or_handler]
else:
for key, val in self._message_handlers.items():
if val == target_or_handler:
del self._message_handlers[key]
def message_handler(self, target):
"""Decorator to register a mpv script message handler.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
def register(handler):
self._register_message_handler_internal(target, handler)
handler.unregister_mpv_messages = lambda: self.unregister_message_handler(handler)
return handler
return register
def register_event_callback(self, callback):
"""Register a blanket event callback receiving all event types.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
self._event_callbacks.append(callback)
def unregister_event_callback(self, callback):
"""Unregiser an event callback."""
self._event_callbacks.remove(callback)
def event_callback(self, *event_types):
"""Function decorator to register a blanket event callback for the given event types. Event types can be given
as str (e.g. 'start-file'), integer or MpvEventID object.
WARNING: Due to the way this is filtering events, this decorator cannot be chained with itself.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
def register(callback):
types = [MpvEventID.from_str(t) if isinstance(t, str) else t for t in event_types] or MpvEventID.ANY
@wraps(callback)
def wrapper(event, *args, **kwargs):
if event['event_id'] in types:
callback(event, *args, **kwargs)
self._event_callbacks.append(wrapper)
wrapper.unregister_mpv_events = partial(self.unregister_event_callback, wrapper)
return wrapper
return register
@staticmethod
def _binding_name(callback_or_cmd):
return 'py_kb_{:016x}'.format(hash(callback_or_cmd)&0xffffffffffffffff)
def on_key_press(self, keydef, mode='force'):
"""Function decorator to register a simplified key binding. The callback is called whenever the key given is
*pressed*.
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.on_key_press('Q')
def binding():
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
The BIG FAT WARNING regarding untrusted keydefs from the key_binding method applies here as well.
"""
def register(fun):
@self.key_binding(keydef, mode)
@wraps(fun)
def wrapper(state='p-', name=None):
if state[0] in ('d', 'p'):
fun()
return wrapper
return register
def key_binding(self, keydef, mode='force'):
"""Function decorator to register a low-level key binding.
The callback function signature is ``fun(key_state, key_name)`` where ``key_state`` is either ``'U'`` for "key
up" or ``'D'`` for "key down".
The keydef format is: ``[Shift+][Ctrl+][Alt+][Meta+]<key>`` where ``<key>`` is either the literal character the
key produces (ASCII or Unicode character), or a symbolic name (as printed by ``mpv --input-keylist``).
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.key_binding('Q')
def binding(state, name):
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
BIG FAT WARNING: mpv's key binding mechanism is pretty powerful. This means, you essentially get arbitrary code
exectution through key bindings. This interface makes some limited effort to sanitize the keydef given in the
first parameter, but YOU SHOULD NOT RELY ON THIS IN FOR SECURITY. If your input comes from config files, this is
completely fine--but, if you are about to pass untrusted input into this parameter, better double-check whether
this is secure in your case.
"""
def register(fun):
fun.mpv_key_bindings = getattr(fun, 'mpv_key_bindings', []) + [keydef]
def unregister_all():
for keydef in fun.mpv_key_bindings:
self.unregister_key_binding(keydef)
fun.unregister_mpv_key_bindings = unregister_all
self.register_key_binding(keydef, fun, mode)
return fun
return register
def register_key_binding(self, keydef, callback_or_cmd, mode='force'):
"""Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python
callback function. See ``MPV.key_binding`` for details.
"""
if not re.match(r'(Shift+)?(Ctrl+)?(Alt+)?(Meta+)?(.|\w+)', keydef):
raise ValueError('Invalid keydef. Expected format: [Shift+][Ctrl+][Alt+][Meta+]<key>\n'
'<key> is either the literal character the key produces (ASCII or Unicode character), or a '
'symbolic name (as printed by --input-keylist')
binding_name = MPV._binding_name(keydef)
if callable(callback_or_cmd):
self._key_binding_handlers[binding_name] = callback_or_cmd
self.register_message_handler('key-binding', self._handle_key_binding_message)
self.command('define-section',
binding_name, '{} script-binding py_event_handler/{}'.format(keydef, binding_name), mode)
elif isinstance(callback_or_cmd, str):
self.command('define-section', binding_name, '{} {}'.format(keydef, callback_or_cmd), mode)
else:
raise TypeError('register_key_binding expects either an str with an mpv command or a python callable.')
self.command('enable-section', binding_name, 'allow-hide-cursor+allow-vo-dragging')
def _handle_key_binding_message(self, binding_name, key_state, key_name=None):
self._key_binding_handlers[binding_name](key_state, key_name)
def unregister_key_binding(self, keydef):
"""Unregister a key binding by keydef."""
binding_name = MPV._binding_name(keydef)
self.command('disable-section', binding_name)
self.command('define-section', binding_name, '')
if binding_name in self._key_binding_handlers:
del self._key_binding_handlers[binding_name]
if not self._key_binding_handlers:
self.unregister_message_handler('key-binding')
# Convenience functions
def play(self, filename):
"""Play a path or URL (requires ``ytdl`` option to be set)."""
self.loadfile(filename)
@property
def playlist_filenames(self):
"""Return all playlist item file names/URLs as a list of strs."""
return [element['filename'] for element in self.playlist]
def playlist_append(self, filename, **options):
"""Append a path or URL to the playlist. This does not start playing the file automatically. To do that, use
``MPV.loadfile(filename, 'append-play')``."""
self.loadfile(filename, 'append', **options)
# Property accessors
def _get_property(self, name, decoder=strict_decoder, fmt=MpvFormat.NODE):
out = create_string_buffer(sizeof(MpvNode))
try:
cval = _mpv_get_property(self.handle, name.encode('utf-8'), fmt, out)
if fmt is MpvFormat.OSD_STRING:
return cast(out, POINTER(c_char_p)).contents.value.decode('utf-8')
elif fmt is MpvFormat.NODE:
rv = cast(out, POINTER(MpvNode)).contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
else:
raise TypeError('_get_property only supports NODE and OSD_STRING formats.')
except PropertyUnavailableError as ex:
return None
def _set_property(self, name, value):
ename = name.encode('utf-8')
if isinstance(value, (list, set, dict)):
_1, _2, _3, pointer = _make_node_str_list(value)
_mpv_set_property(self.handle, ename, MpvFormat.NODE, pointer)
else:
_mpv_set_property_string(self.handle, ename, _mpv_coax_proptype(value))
def __getattr__(self, name):
return self._get_property(_py_to_mpv(name), lazy_decoder)
def __setattr__(self, name, value):
try:
if name != 'handle' and not name.startswith('_'):
self._set_property(_py_to_mpv(name), value)
else:
super().__setattr__(name, value)
except AttributeError:
super().__setattr__(name, value)
def __dir__(self):
return super().__dir__() + [ name.replace('-', '_') for name in self.property_list ]
@property
def properties(self):
return { name: self.option_info(name) for name in self.property_list }
# Dict-like option access
def __getitem__(self, name, file_local=False):
"""Get an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._get_property(prefix+name, lazy_decoder)
def __setitem__(self, name, value, file_local=False):
"""Set an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._set_property(prefix+name, value)
def __iter__(self):
"""Iterate over all option names."""
return iter(self.options)
def option_info(self, name):
"""Get information on the given option."""
try:
return self._get_property('option-info/'+name)
except AttributeError:
return None
|
jaseg/python-mpv | mpv.py | MPV.loadfile | python | def loadfile(self, filename, mode='replace', **options):
self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode_options(options)) | Mapped mpv loadfile command, see man mpv(1). | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L702-L704 | null | class MPV(object):
"""See man mpv(1) for the details of the implemented commands. All mpv properties can be accessed as
``my_mpv.some_property`` and all mpv options can be accessed as ``my_mpv['some-option']``.
By default, properties are returned as decoded ``str`` and an error is thrown if the value does not contain valid
utf-8. To get a decoded ``str`` if possibly but ``bytes`` instead of an error if not, use
``my_mpv.lazy.some_property``. To always get raw ``bytes``, use ``my_mpv.raw.some_property``. To access a
property's decoded OSD value, use ``my_mpv.osd.some_property``.
To get API information on an option, use ``my_mpv.option_info('option-name')``. To get API information on a
property, use ``my_mpv.properties['property-name']``. Take care to use mpv's dashed-names instead of the
underscore_names exposed on the python object.
To make your program not barf hard the first time its used on a weird file system **always** access properties
containing file names or file tags through ``MPV.raw``. """
def __init__(self, *extra_mpv_flags, log_handler=None, start_event_thread=True, loglevel=None, **extra_mpv_opts):
"""Create an MPV instance.
Extra arguments and extra keyword arguments will be passed to mpv as options.
"""
self.handle = _mpv_create()
self._event_thread = None
_mpv_set_option_string(self.handle, b'audio-display', b'no')
istr = lambda o: ('yes' if o else 'no') if type(o) is bool else str(o)
try:
for flag in extra_mpv_flags:
_mpv_set_option_string(self.handle, flag.encode('utf-8'), b'')
for k,v in extra_mpv_opts.items():
_mpv_set_option_string(self.handle, k.replace('_', '-').encode('utf-8'), istr(v).encode('utf-8'))
finally:
_mpv_initialize(self.handle)
self.osd = _OSDPropertyProxy(self)
self.file_local = _FileLocalProxy(self)
self.raw = _DecoderPropertyProxy(self, identity_decoder)
self.strict = _DecoderPropertyProxy(self, strict_decoder)
self.lazy = _DecoderPropertyProxy(self, lazy_decoder)
self._event_callbacks = []
self._property_handlers = collections.defaultdict(lambda: [])
self._message_handlers = {}
self._key_binding_handlers = {}
self._playback_cond = threading.Condition()
self._event_handle = _mpv_create_client(self.handle, b'py_event_handler')
self._loop = partial(_event_loop, self._event_handle, self._playback_cond, self._event_callbacks,
self._message_handlers, self._property_handlers, log_handler)
if loglevel is not None or log_handler is not None:
self.set_loglevel(loglevel or 'terminal-default')
if start_event_thread:
self._event_thread = threading.Thread(target=self._loop, name='MPVEventHandlerThread')
self._event_thread.setDaemon(True)
self._event_thread.start()
else:
self._event_thread = None
def wait_for_playback(self):
"""Waits until playback of the current title is paused or done."""
with self._playback_cond:
self._playback_cond.wait()
def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True):
"""Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for
properties such as ``idle_active`` indicating the player is done with regular playback and just idling around
"""
sema = threading.Semaphore(value=0)
def observer(name, val):
if cond(val):
sema.release()
self.observe_property(name, observer)
if not level_sensitive or not cond(getattr(self, name.replace('-', '_'))):
sema.acquire()
self.unobserve_property(name, observer)
def __del__(self):
if self.handle:
self.terminate()
def terminate(self):
"""Properly terminates this player instance. Preferably use this instead of relying on python's garbage
collector to cause this to be called from the object's destructor.
"""
self.handle, handle = None, self.handle
if threading.current_thread() is self._event_thread:
# Handle special case to allow event handle to be detached.
# This is necessary since otherwise the event thread would deadlock itself.
grim_reaper = threading.Thread(target=lambda: _mpv_terminate_destroy(handle))
grim_reaper.start()
else:
_mpv_terminate_destroy(handle)
if self._event_thread:
self._event_thread.join()
def set_loglevel(self, level):
"""Set MPV's log level. This adjusts which output will be sent to this object's log handlers. If you just want
mpv's regular terminal output, you don't need to adjust this but just need to pass a log handler to the MPV
constructur such as ``MPV(log_handler=print)``.
Valid log levels are "no", "fatal", "error", "warn", "info", "v" "debug" and "trace". For details see your mpv's
client.h header file.
"""
_mpv_request_log_messages(self._event_handle, level.encode('utf-8'))
def command(self, name, *args):
"""Execute a raw command."""
args = [name.encode('utf-8')] + [ (arg if type(arg) is bytes else str(arg).encode('utf-8'))
for arg in args if arg is not None ] + [None]
_mpv_command(self.handle, (c_char_p*len(args))(*args))
def node_command(self, name, *args, decoder=strict_decoder):
_1, _2, _3, pointer = _make_node_str_list([name, *args])
out = cast(create_string_buffer(sizeof(MpvNode)), POINTER(MpvNode))
ppointer = cast(pointer, POINTER(MpvNode))
_mpv_command_node(self.handle, ppointer, out)
rv = out.contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
def seek(self, amount, reference="relative", precision="default-precise"):
"""Mapped mpv seek command, see man mpv(1)."""
self.command('seek', amount, reference, precision)
def revert_seek(self):
"""Mapped mpv revert_seek command, see man mpv(1)."""
self.command('revert_seek');
def frame_step(self):
"""Mapped mpv frame_step command, see man mpv(1)."""
self.command('frame_step')
def frame_back_step(self):
"""Mapped mpv frame_back_step command, see man mpv(1)."""
self.command('frame_back_step')
def property_add(self, name, value=1):
"""Add the given value to the property's value. On overflow or underflow, clamp the property to the maximum. If
``value`` is omitted, assume ``1``.
"""
self.command('add', name, value)
def property_multiply(self, name, factor):
"""Multiply the value of a property with a numeric factor."""
self.command('multiply', name, factor)
def cycle(self, name, direction='up'):
"""Cycle the given property. ``up`` and ``down`` set the cycle direction. On overflow, set the property back to
the minimum, on underflow set it to the maximum. If ``up`` or ``down`` is omitted, assume ``up``.
"""
self.command('cycle', name, direction)
def screenshot(self, includes='subtitles', mode='single'):
"""Mapped mpv screenshot command, see man mpv(1)."""
self.command('screenshot', includes, mode)
def screenshot_to_file(self, filename, includes='subtitles'):
"""Mapped mpv screenshot_to_file command, see man mpv(1)."""
self.command('screenshot_to_file', filename.encode(fs_enc), includes)
def screenshot_raw(self, includes='subtitles'):
"""Mapped mpv screenshot_raw command, see man mpv(1). Returns a pillow Image object."""
from PIL import Image
res = self.node_command('screenshot-raw', includes)
if res['format'] != 'bgr0':
raise ValueError('Screenshot in unknown format "{}". Currently, only bgr0 is supported.'
.format(res['format']))
img = Image.frombytes('RGBA', (res['w'], res['h']), res['data'])
b,g,r,a = img.split()
return Image.merge('RGB', (r,g,b))
def playlist_next(self, mode='weak'):
"""Mapped mpv playlist_next command, see man mpv(1)."""
self.command('playlist_next', mode)
def playlist_prev(self, mode='weak'):
"""Mapped mpv playlist_prev command, see man mpv(1)."""
self.command('playlist_prev', mode)
@staticmethod
def _encode_options(options):
return ','.join('{}={}'.format(str(key), str(val)) for key, val in options.items())
def loadlist(self, playlist, mode='replace'):
"""Mapped mpv loadlist command, see man mpv(1)."""
self.command('loadlist', playlist.encode(fs_enc), mode)
def playlist_clear(self):
"""Mapped mpv playlist_clear command, see man mpv(1)."""
self.command('playlist_clear')
def playlist_remove(self, index='current'):
"""Mapped mpv playlist_remove command, see man mpv(1)."""
self.command('playlist_remove', index)
def playlist_move(self, index1, index2):
"""Mapped mpv playlist_move command, see man mpv(1)."""
self.command('playlist_move', index1, index2)
def run(self, command, *args):
"""Mapped mpv run command, see man mpv(1)."""
self.command('run', command, *args)
def quit(self, code=None):
"""Mapped mpv quit command, see man mpv(1)."""
self.command('quit', code)
def quit_watch_later(self, code=None):
"""Mapped mpv quit_watch_later command, see man mpv(1)."""
self.command('quit_watch_later', code)
def sub_add(self, filename):
"""Mapped mpv sub_add command, see man mpv(1)."""
self.command('sub_add', filename.encode(fs_enc))
def sub_remove(self, sub_id=None):
"""Mapped mpv sub_remove command, see man mpv(1)."""
self.command('sub_remove', sub_id)
def sub_reload(self, sub_id=None):
"""Mapped mpv sub_reload command, see man mpv(1)."""
self.command('sub_reload', sub_id)
def sub_step(self, skip):
"""Mapped mpv sub_step command, see man mpv(1)."""
self.command('sub_step', skip)
def sub_seek(self, skip):
"""Mapped mpv sub_seek command, see man mpv(1)."""
self.command('sub_seek', skip)
def toggle_osd(self):
"""Mapped mpv osd command, see man mpv(1)."""
self.command('osd')
def show_text(self, string, duration='-1', level=None):
"""Mapped mpv show_text command, see man mpv(1)."""
self.command('show_text', string, duration, level)
def show_progress(self):
"""Mapped mpv show_progress command, see man mpv(1)."""
self.command('show_progress')
def discnav(self, command):
"""Mapped mpv discnav command, see man mpv(1)."""
self.command('discnav', command)
def write_watch_later_config(self):
"""Mapped mpv write_watch_later_config command, see man mpv(1)."""
self.command('write_watch_later_config')
def overlay_add(self, overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride):
"""Mapped mpv overlay_add command, see man mpv(1)."""
self.command('overlay_add', overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride)
def overlay_remove(self, overlay_id):
"""Mapped mpv overlay_remove command, see man mpv(1)."""
self.command('overlay_remove', overlay_id)
def script_message(self, *args):
"""Mapped mpv script_message command, see man mpv(1)."""
self.command('script_message', *args)
def script_message_to(self, target, *args):
"""Mapped mpv script_message_to command, see man mpv(1)."""
self.command('script_message_to', target, *args)
def observe_property(self, name, handler):
"""Register an observer on the named property. An observer is a function that is called with the new property
value every time the property's value is changed. The basic function signature is ``fun(property_name,
new_value)`` with new_value being the decoded property value as a python object. This function can be used as a
function decorator if no handler is given.
To unregister the observer, call either of ``mpv.unobserve_property(name, handler)``,
``mpv.unobserve_all_properties(handler)`` or the handler's ``unregister_mpv_properties`` attribute::
@player.observe_property('volume')
def my_handler(new_volume, *):
print("It's loud!", volume)
my_handler.unregister_mpv_properties()
"""
self._property_handlers[name].append(handler)
_mpv_observe_property(self._event_handle, hash(name)&0xffffffffffffffff, name.encode('utf-8'), MpvFormat.NODE)
def property_observer(self, name):
"""Function decorator to register a property observer. See ``MPV.observe_property`` for details."""
def wrapper(fun):
self.observe_property(name, fun)
fun.unobserve_mpv_properties = lambda: self.unobserve_property(name, fun)
return fun
return wrapper
def unobserve_property(self, name, handler):
"""Unregister a property observer. This requires both the observed property's name and the handler function that
was originally registered as one handler could be registered for several properties. To unregister a handler
from *all* observed properties see ``unobserve_all_properties``.
"""
self._property_handlers[name].remove(handler)
if not self._property_handlers[name]:
_mpv_unobserve_property(self._event_handle, hash(name)&0xffffffffffffffff)
def unobserve_all_properties(self, handler):
"""Unregister a property observer from *all* observed properties."""
for name in self._property_handlers:
self.unobserve_property(name, handler)
def register_message_handler(self, target, handler=None):
"""Register a mpv script message handler. This can be used to communicate with embedded lua scripts. Pass the
script message target name this handler should be listening to and the handler function.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
self._register_message_handler_internal(target, handler)
def _register_message_handler_internal(self, target, handler):
self._message_handlers[target] = handler
def unregister_message_handler(self, target_or_handler):
"""Unregister a mpv script message handler for the given script message target name.
You can also call the ``unregister_mpv_messages`` function attribute set on the handler function when it is
registered.
"""
if isinstance(target_or_handler, str):
del self._message_handlers[target_or_handler]
else:
for key, val in self._message_handlers.items():
if val == target_or_handler:
del self._message_handlers[key]
def message_handler(self, target):
"""Decorator to register a mpv script message handler.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
def register(handler):
self._register_message_handler_internal(target, handler)
handler.unregister_mpv_messages = lambda: self.unregister_message_handler(handler)
return handler
return register
def register_event_callback(self, callback):
"""Register a blanket event callback receiving all event types.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
self._event_callbacks.append(callback)
def unregister_event_callback(self, callback):
"""Unregiser an event callback."""
self._event_callbacks.remove(callback)
def event_callback(self, *event_types):
"""Function decorator to register a blanket event callback for the given event types. Event types can be given
as str (e.g. 'start-file'), integer or MpvEventID object.
WARNING: Due to the way this is filtering events, this decorator cannot be chained with itself.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
def register(callback):
types = [MpvEventID.from_str(t) if isinstance(t, str) else t for t in event_types] or MpvEventID.ANY
@wraps(callback)
def wrapper(event, *args, **kwargs):
if event['event_id'] in types:
callback(event, *args, **kwargs)
self._event_callbacks.append(wrapper)
wrapper.unregister_mpv_events = partial(self.unregister_event_callback, wrapper)
return wrapper
return register
@staticmethod
def _binding_name(callback_or_cmd):
return 'py_kb_{:016x}'.format(hash(callback_or_cmd)&0xffffffffffffffff)
def on_key_press(self, keydef, mode='force'):
"""Function decorator to register a simplified key binding. The callback is called whenever the key given is
*pressed*.
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.on_key_press('Q')
def binding():
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
The BIG FAT WARNING regarding untrusted keydefs from the key_binding method applies here as well.
"""
def register(fun):
@self.key_binding(keydef, mode)
@wraps(fun)
def wrapper(state='p-', name=None):
if state[0] in ('d', 'p'):
fun()
return wrapper
return register
def key_binding(self, keydef, mode='force'):
"""Function decorator to register a low-level key binding.
The callback function signature is ``fun(key_state, key_name)`` where ``key_state`` is either ``'U'`` for "key
up" or ``'D'`` for "key down".
The keydef format is: ``[Shift+][Ctrl+][Alt+][Meta+]<key>`` where ``<key>`` is either the literal character the
key produces (ASCII or Unicode character), or a symbolic name (as printed by ``mpv --input-keylist``).
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.key_binding('Q')
def binding(state, name):
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
BIG FAT WARNING: mpv's key binding mechanism is pretty powerful. This means, you essentially get arbitrary code
exectution through key bindings. This interface makes some limited effort to sanitize the keydef given in the
first parameter, but YOU SHOULD NOT RELY ON THIS IN FOR SECURITY. If your input comes from config files, this is
completely fine--but, if you are about to pass untrusted input into this parameter, better double-check whether
this is secure in your case.
"""
def register(fun):
fun.mpv_key_bindings = getattr(fun, 'mpv_key_bindings', []) + [keydef]
def unregister_all():
for keydef in fun.mpv_key_bindings:
self.unregister_key_binding(keydef)
fun.unregister_mpv_key_bindings = unregister_all
self.register_key_binding(keydef, fun, mode)
return fun
return register
def register_key_binding(self, keydef, callback_or_cmd, mode='force'):
"""Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python
callback function. See ``MPV.key_binding`` for details.
"""
if not re.match(r'(Shift+)?(Ctrl+)?(Alt+)?(Meta+)?(.|\w+)', keydef):
raise ValueError('Invalid keydef. Expected format: [Shift+][Ctrl+][Alt+][Meta+]<key>\n'
'<key> is either the literal character the key produces (ASCII or Unicode character), or a '
'symbolic name (as printed by --input-keylist')
binding_name = MPV._binding_name(keydef)
if callable(callback_or_cmd):
self._key_binding_handlers[binding_name] = callback_or_cmd
self.register_message_handler('key-binding', self._handle_key_binding_message)
self.command('define-section',
binding_name, '{} script-binding py_event_handler/{}'.format(keydef, binding_name), mode)
elif isinstance(callback_or_cmd, str):
self.command('define-section', binding_name, '{} {}'.format(keydef, callback_or_cmd), mode)
else:
raise TypeError('register_key_binding expects either an str with an mpv command or a python callable.')
self.command('enable-section', binding_name, 'allow-hide-cursor+allow-vo-dragging')
def _handle_key_binding_message(self, binding_name, key_state, key_name=None):
self._key_binding_handlers[binding_name](key_state, key_name)
def unregister_key_binding(self, keydef):
"""Unregister a key binding by keydef."""
binding_name = MPV._binding_name(keydef)
self.command('disable-section', binding_name)
self.command('define-section', binding_name, '')
if binding_name in self._key_binding_handlers:
del self._key_binding_handlers[binding_name]
if not self._key_binding_handlers:
self.unregister_message_handler('key-binding')
# Convenience functions
def play(self, filename):
"""Play a path or URL (requires ``ytdl`` option to be set)."""
self.loadfile(filename)
@property
def playlist_filenames(self):
"""Return all playlist item file names/URLs as a list of strs."""
return [element['filename'] for element in self.playlist]
def playlist_append(self, filename, **options):
"""Append a path or URL to the playlist. This does not start playing the file automatically. To do that, use
``MPV.loadfile(filename, 'append-play')``."""
self.loadfile(filename, 'append', **options)
# Property accessors
def _get_property(self, name, decoder=strict_decoder, fmt=MpvFormat.NODE):
out = create_string_buffer(sizeof(MpvNode))
try:
cval = _mpv_get_property(self.handle, name.encode('utf-8'), fmt, out)
if fmt is MpvFormat.OSD_STRING:
return cast(out, POINTER(c_char_p)).contents.value.decode('utf-8')
elif fmt is MpvFormat.NODE:
rv = cast(out, POINTER(MpvNode)).contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
else:
raise TypeError('_get_property only supports NODE and OSD_STRING formats.')
except PropertyUnavailableError as ex:
return None
def _set_property(self, name, value):
ename = name.encode('utf-8')
if isinstance(value, (list, set, dict)):
_1, _2, _3, pointer = _make_node_str_list(value)
_mpv_set_property(self.handle, ename, MpvFormat.NODE, pointer)
else:
_mpv_set_property_string(self.handle, ename, _mpv_coax_proptype(value))
def __getattr__(self, name):
return self._get_property(_py_to_mpv(name), lazy_decoder)
def __setattr__(self, name, value):
try:
if name != 'handle' and not name.startswith('_'):
self._set_property(_py_to_mpv(name), value)
else:
super().__setattr__(name, value)
except AttributeError:
super().__setattr__(name, value)
def __dir__(self):
return super().__dir__() + [ name.replace('-', '_') for name in self.property_list ]
@property
def properties(self):
return { name: self.option_info(name) for name in self.property_list }
# Dict-like option access
def __getitem__(self, name, file_local=False):
"""Get an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._get_property(prefix+name, lazy_decoder)
def __setitem__(self, name, value, file_local=False):
"""Set an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._set_property(prefix+name, value)
def __iter__(self):
"""Iterate over all option names."""
return iter(self.options)
def option_info(self, name):
"""Get information on the given option."""
try:
return self._get_property('option-info/'+name)
except AttributeError:
return None
|
jaseg/python-mpv | mpv.py | MPV.loadlist | python | def loadlist(self, playlist, mode='replace'):
self.command('loadlist', playlist.encode(fs_enc), mode) | Mapped mpv loadlist command, see man mpv(1). | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L706-L708 | null | class MPV(object):
"""See man mpv(1) for the details of the implemented commands. All mpv properties can be accessed as
``my_mpv.some_property`` and all mpv options can be accessed as ``my_mpv['some-option']``.
By default, properties are returned as decoded ``str`` and an error is thrown if the value does not contain valid
utf-8. To get a decoded ``str`` if possibly but ``bytes`` instead of an error if not, use
``my_mpv.lazy.some_property``. To always get raw ``bytes``, use ``my_mpv.raw.some_property``. To access a
property's decoded OSD value, use ``my_mpv.osd.some_property``.
To get API information on an option, use ``my_mpv.option_info('option-name')``. To get API information on a
property, use ``my_mpv.properties['property-name']``. Take care to use mpv's dashed-names instead of the
underscore_names exposed on the python object.
To make your program not barf hard the first time its used on a weird file system **always** access properties
containing file names or file tags through ``MPV.raw``. """
def __init__(self, *extra_mpv_flags, log_handler=None, start_event_thread=True, loglevel=None, **extra_mpv_opts):
"""Create an MPV instance.
Extra arguments and extra keyword arguments will be passed to mpv as options.
"""
self.handle = _mpv_create()
self._event_thread = None
_mpv_set_option_string(self.handle, b'audio-display', b'no')
istr = lambda o: ('yes' if o else 'no') if type(o) is bool else str(o)
try:
for flag in extra_mpv_flags:
_mpv_set_option_string(self.handle, flag.encode('utf-8'), b'')
for k,v in extra_mpv_opts.items():
_mpv_set_option_string(self.handle, k.replace('_', '-').encode('utf-8'), istr(v).encode('utf-8'))
finally:
_mpv_initialize(self.handle)
self.osd = _OSDPropertyProxy(self)
self.file_local = _FileLocalProxy(self)
self.raw = _DecoderPropertyProxy(self, identity_decoder)
self.strict = _DecoderPropertyProxy(self, strict_decoder)
self.lazy = _DecoderPropertyProxy(self, lazy_decoder)
self._event_callbacks = []
self._property_handlers = collections.defaultdict(lambda: [])
self._message_handlers = {}
self._key_binding_handlers = {}
self._playback_cond = threading.Condition()
self._event_handle = _mpv_create_client(self.handle, b'py_event_handler')
self._loop = partial(_event_loop, self._event_handle, self._playback_cond, self._event_callbacks,
self._message_handlers, self._property_handlers, log_handler)
if loglevel is not None or log_handler is not None:
self.set_loglevel(loglevel or 'terminal-default')
if start_event_thread:
self._event_thread = threading.Thread(target=self._loop, name='MPVEventHandlerThread')
self._event_thread.setDaemon(True)
self._event_thread.start()
else:
self._event_thread = None
def wait_for_playback(self):
"""Waits until playback of the current title is paused or done."""
with self._playback_cond:
self._playback_cond.wait()
def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True):
"""Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for
properties such as ``idle_active`` indicating the player is done with regular playback and just idling around
"""
sema = threading.Semaphore(value=0)
def observer(name, val):
if cond(val):
sema.release()
self.observe_property(name, observer)
if not level_sensitive or not cond(getattr(self, name.replace('-', '_'))):
sema.acquire()
self.unobserve_property(name, observer)
def __del__(self):
if self.handle:
self.terminate()
def terminate(self):
"""Properly terminates this player instance. Preferably use this instead of relying on python's garbage
collector to cause this to be called from the object's destructor.
"""
self.handle, handle = None, self.handle
if threading.current_thread() is self._event_thread:
# Handle special case to allow event handle to be detached.
# This is necessary since otherwise the event thread would deadlock itself.
grim_reaper = threading.Thread(target=lambda: _mpv_terminate_destroy(handle))
grim_reaper.start()
else:
_mpv_terminate_destroy(handle)
if self._event_thread:
self._event_thread.join()
def set_loglevel(self, level):
"""Set MPV's log level. This adjusts which output will be sent to this object's log handlers. If you just want
mpv's regular terminal output, you don't need to adjust this but just need to pass a log handler to the MPV
constructur such as ``MPV(log_handler=print)``.
Valid log levels are "no", "fatal", "error", "warn", "info", "v" "debug" and "trace". For details see your mpv's
client.h header file.
"""
_mpv_request_log_messages(self._event_handle, level.encode('utf-8'))
def command(self, name, *args):
"""Execute a raw command."""
args = [name.encode('utf-8')] + [ (arg if type(arg) is bytes else str(arg).encode('utf-8'))
for arg in args if arg is not None ] + [None]
_mpv_command(self.handle, (c_char_p*len(args))(*args))
def node_command(self, name, *args, decoder=strict_decoder):
_1, _2, _3, pointer = _make_node_str_list([name, *args])
out = cast(create_string_buffer(sizeof(MpvNode)), POINTER(MpvNode))
ppointer = cast(pointer, POINTER(MpvNode))
_mpv_command_node(self.handle, ppointer, out)
rv = out.contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
def seek(self, amount, reference="relative", precision="default-precise"):
"""Mapped mpv seek command, see man mpv(1)."""
self.command('seek', amount, reference, precision)
def revert_seek(self):
"""Mapped mpv revert_seek command, see man mpv(1)."""
self.command('revert_seek');
def frame_step(self):
"""Mapped mpv frame_step command, see man mpv(1)."""
self.command('frame_step')
def frame_back_step(self):
"""Mapped mpv frame_back_step command, see man mpv(1)."""
self.command('frame_back_step')
def property_add(self, name, value=1):
"""Add the given value to the property's value. On overflow or underflow, clamp the property to the maximum. If
``value`` is omitted, assume ``1``.
"""
self.command('add', name, value)
def property_multiply(self, name, factor):
"""Multiply the value of a property with a numeric factor."""
self.command('multiply', name, factor)
def cycle(self, name, direction='up'):
"""Cycle the given property. ``up`` and ``down`` set the cycle direction. On overflow, set the property back to
the minimum, on underflow set it to the maximum. If ``up`` or ``down`` is omitted, assume ``up``.
"""
self.command('cycle', name, direction)
def screenshot(self, includes='subtitles', mode='single'):
"""Mapped mpv screenshot command, see man mpv(1)."""
self.command('screenshot', includes, mode)
def screenshot_to_file(self, filename, includes='subtitles'):
"""Mapped mpv screenshot_to_file command, see man mpv(1)."""
self.command('screenshot_to_file', filename.encode(fs_enc), includes)
def screenshot_raw(self, includes='subtitles'):
"""Mapped mpv screenshot_raw command, see man mpv(1). Returns a pillow Image object."""
from PIL import Image
res = self.node_command('screenshot-raw', includes)
if res['format'] != 'bgr0':
raise ValueError('Screenshot in unknown format "{}". Currently, only bgr0 is supported.'
.format(res['format']))
img = Image.frombytes('RGBA', (res['w'], res['h']), res['data'])
b,g,r,a = img.split()
return Image.merge('RGB', (r,g,b))
def playlist_next(self, mode='weak'):
"""Mapped mpv playlist_next command, see man mpv(1)."""
self.command('playlist_next', mode)
def playlist_prev(self, mode='weak'):
"""Mapped mpv playlist_prev command, see man mpv(1)."""
self.command('playlist_prev', mode)
@staticmethod
def _encode_options(options):
return ','.join('{}={}'.format(str(key), str(val)) for key, val in options.items())
def loadfile(self, filename, mode='replace', **options):
"""Mapped mpv loadfile command, see man mpv(1)."""
self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode_options(options))
def playlist_clear(self):
"""Mapped mpv playlist_clear command, see man mpv(1)."""
self.command('playlist_clear')
def playlist_remove(self, index='current'):
"""Mapped mpv playlist_remove command, see man mpv(1)."""
self.command('playlist_remove', index)
def playlist_move(self, index1, index2):
"""Mapped mpv playlist_move command, see man mpv(1)."""
self.command('playlist_move', index1, index2)
def run(self, command, *args):
"""Mapped mpv run command, see man mpv(1)."""
self.command('run', command, *args)
def quit(self, code=None):
"""Mapped mpv quit command, see man mpv(1)."""
self.command('quit', code)
def quit_watch_later(self, code=None):
"""Mapped mpv quit_watch_later command, see man mpv(1)."""
self.command('quit_watch_later', code)
def sub_add(self, filename):
"""Mapped mpv sub_add command, see man mpv(1)."""
self.command('sub_add', filename.encode(fs_enc))
def sub_remove(self, sub_id=None):
"""Mapped mpv sub_remove command, see man mpv(1)."""
self.command('sub_remove', sub_id)
def sub_reload(self, sub_id=None):
"""Mapped mpv sub_reload command, see man mpv(1)."""
self.command('sub_reload', sub_id)
def sub_step(self, skip):
"""Mapped mpv sub_step command, see man mpv(1)."""
self.command('sub_step', skip)
def sub_seek(self, skip):
"""Mapped mpv sub_seek command, see man mpv(1)."""
self.command('sub_seek', skip)
def toggle_osd(self):
"""Mapped mpv osd command, see man mpv(1)."""
self.command('osd')
def show_text(self, string, duration='-1', level=None):
"""Mapped mpv show_text command, see man mpv(1)."""
self.command('show_text', string, duration, level)
def show_progress(self):
"""Mapped mpv show_progress command, see man mpv(1)."""
self.command('show_progress')
def discnav(self, command):
"""Mapped mpv discnav command, see man mpv(1)."""
self.command('discnav', command)
def write_watch_later_config(self):
"""Mapped mpv write_watch_later_config command, see man mpv(1)."""
self.command('write_watch_later_config')
def overlay_add(self, overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride):
"""Mapped mpv overlay_add command, see man mpv(1)."""
self.command('overlay_add', overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride)
def overlay_remove(self, overlay_id):
"""Mapped mpv overlay_remove command, see man mpv(1)."""
self.command('overlay_remove', overlay_id)
def script_message(self, *args):
"""Mapped mpv script_message command, see man mpv(1)."""
self.command('script_message', *args)
def script_message_to(self, target, *args):
"""Mapped mpv script_message_to command, see man mpv(1)."""
self.command('script_message_to', target, *args)
def observe_property(self, name, handler):
"""Register an observer on the named property. An observer is a function that is called with the new property
value every time the property's value is changed. The basic function signature is ``fun(property_name,
new_value)`` with new_value being the decoded property value as a python object. This function can be used as a
function decorator if no handler is given.
To unregister the observer, call either of ``mpv.unobserve_property(name, handler)``,
``mpv.unobserve_all_properties(handler)`` or the handler's ``unregister_mpv_properties`` attribute::
@player.observe_property('volume')
def my_handler(new_volume, *):
print("It's loud!", volume)
my_handler.unregister_mpv_properties()
"""
self._property_handlers[name].append(handler)
_mpv_observe_property(self._event_handle, hash(name)&0xffffffffffffffff, name.encode('utf-8'), MpvFormat.NODE)
def property_observer(self, name):
"""Function decorator to register a property observer. See ``MPV.observe_property`` for details."""
def wrapper(fun):
self.observe_property(name, fun)
fun.unobserve_mpv_properties = lambda: self.unobserve_property(name, fun)
return fun
return wrapper
def unobserve_property(self, name, handler):
"""Unregister a property observer. This requires both the observed property's name and the handler function that
was originally registered as one handler could be registered for several properties. To unregister a handler
from *all* observed properties see ``unobserve_all_properties``.
"""
self._property_handlers[name].remove(handler)
if not self._property_handlers[name]:
_mpv_unobserve_property(self._event_handle, hash(name)&0xffffffffffffffff)
def unobserve_all_properties(self, handler):
"""Unregister a property observer from *all* observed properties."""
for name in self._property_handlers:
self.unobserve_property(name, handler)
def register_message_handler(self, target, handler=None):
"""Register a mpv script message handler. This can be used to communicate with embedded lua scripts. Pass the
script message target name this handler should be listening to and the handler function.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
self._register_message_handler_internal(target, handler)
def _register_message_handler_internal(self, target, handler):
self._message_handlers[target] = handler
def unregister_message_handler(self, target_or_handler):
"""Unregister a mpv script message handler for the given script message target name.
You can also call the ``unregister_mpv_messages`` function attribute set on the handler function when it is
registered.
"""
if isinstance(target_or_handler, str):
del self._message_handlers[target_or_handler]
else:
for key, val in self._message_handlers.items():
if val == target_or_handler:
del self._message_handlers[key]
def message_handler(self, target):
"""Decorator to register a mpv script message handler.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
def register(handler):
self._register_message_handler_internal(target, handler)
handler.unregister_mpv_messages = lambda: self.unregister_message_handler(handler)
return handler
return register
def register_event_callback(self, callback):
"""Register a blanket event callback receiving all event types.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
self._event_callbacks.append(callback)
def unregister_event_callback(self, callback):
"""Unregiser an event callback."""
self._event_callbacks.remove(callback)
def event_callback(self, *event_types):
"""Function decorator to register a blanket event callback for the given event types. Event types can be given
as str (e.g. 'start-file'), integer or MpvEventID object.
WARNING: Due to the way this is filtering events, this decorator cannot be chained with itself.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
def register(callback):
types = [MpvEventID.from_str(t) if isinstance(t, str) else t for t in event_types] or MpvEventID.ANY
@wraps(callback)
def wrapper(event, *args, **kwargs):
if event['event_id'] in types:
callback(event, *args, **kwargs)
self._event_callbacks.append(wrapper)
wrapper.unregister_mpv_events = partial(self.unregister_event_callback, wrapper)
return wrapper
return register
@staticmethod
def _binding_name(callback_or_cmd):
return 'py_kb_{:016x}'.format(hash(callback_or_cmd)&0xffffffffffffffff)
def on_key_press(self, keydef, mode='force'):
"""Function decorator to register a simplified key binding. The callback is called whenever the key given is
*pressed*.
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.on_key_press('Q')
def binding():
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
The BIG FAT WARNING regarding untrusted keydefs from the key_binding method applies here as well.
"""
def register(fun):
@self.key_binding(keydef, mode)
@wraps(fun)
def wrapper(state='p-', name=None):
if state[0] in ('d', 'p'):
fun()
return wrapper
return register
def key_binding(self, keydef, mode='force'):
"""Function decorator to register a low-level key binding.
The callback function signature is ``fun(key_state, key_name)`` where ``key_state`` is either ``'U'`` for "key
up" or ``'D'`` for "key down".
The keydef format is: ``[Shift+][Ctrl+][Alt+][Meta+]<key>`` where ``<key>`` is either the literal character the
key produces (ASCII or Unicode character), or a symbolic name (as printed by ``mpv --input-keylist``).
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.key_binding('Q')
def binding(state, name):
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
BIG FAT WARNING: mpv's key binding mechanism is pretty powerful. This means, you essentially get arbitrary code
exectution through key bindings. This interface makes some limited effort to sanitize the keydef given in the
first parameter, but YOU SHOULD NOT RELY ON THIS IN FOR SECURITY. If your input comes from config files, this is
completely fine--but, if you are about to pass untrusted input into this parameter, better double-check whether
this is secure in your case.
"""
def register(fun):
fun.mpv_key_bindings = getattr(fun, 'mpv_key_bindings', []) + [keydef]
def unregister_all():
for keydef in fun.mpv_key_bindings:
self.unregister_key_binding(keydef)
fun.unregister_mpv_key_bindings = unregister_all
self.register_key_binding(keydef, fun, mode)
return fun
return register
def register_key_binding(self, keydef, callback_or_cmd, mode='force'):
"""Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python
callback function. See ``MPV.key_binding`` for details.
"""
if not re.match(r'(Shift+)?(Ctrl+)?(Alt+)?(Meta+)?(.|\w+)', keydef):
raise ValueError('Invalid keydef. Expected format: [Shift+][Ctrl+][Alt+][Meta+]<key>\n'
'<key> is either the literal character the key produces (ASCII or Unicode character), or a '
'symbolic name (as printed by --input-keylist')
binding_name = MPV._binding_name(keydef)
if callable(callback_or_cmd):
self._key_binding_handlers[binding_name] = callback_or_cmd
self.register_message_handler('key-binding', self._handle_key_binding_message)
self.command('define-section',
binding_name, '{} script-binding py_event_handler/{}'.format(keydef, binding_name), mode)
elif isinstance(callback_or_cmd, str):
self.command('define-section', binding_name, '{} {}'.format(keydef, callback_or_cmd), mode)
else:
raise TypeError('register_key_binding expects either an str with an mpv command or a python callable.')
self.command('enable-section', binding_name, 'allow-hide-cursor+allow-vo-dragging')
def _handle_key_binding_message(self, binding_name, key_state, key_name=None):
self._key_binding_handlers[binding_name](key_state, key_name)
def unregister_key_binding(self, keydef):
"""Unregister a key binding by keydef."""
binding_name = MPV._binding_name(keydef)
self.command('disable-section', binding_name)
self.command('define-section', binding_name, '')
if binding_name in self._key_binding_handlers:
del self._key_binding_handlers[binding_name]
if not self._key_binding_handlers:
self.unregister_message_handler('key-binding')
# Convenience functions
def play(self, filename):
"""Play a path or URL (requires ``ytdl`` option to be set)."""
self.loadfile(filename)
@property
def playlist_filenames(self):
"""Return all playlist item file names/URLs as a list of strs."""
return [element['filename'] for element in self.playlist]
def playlist_append(self, filename, **options):
"""Append a path or URL to the playlist. This does not start playing the file automatically. To do that, use
``MPV.loadfile(filename, 'append-play')``."""
self.loadfile(filename, 'append', **options)
# Property accessors
def _get_property(self, name, decoder=strict_decoder, fmt=MpvFormat.NODE):
out = create_string_buffer(sizeof(MpvNode))
try:
cval = _mpv_get_property(self.handle, name.encode('utf-8'), fmt, out)
if fmt is MpvFormat.OSD_STRING:
return cast(out, POINTER(c_char_p)).contents.value.decode('utf-8')
elif fmt is MpvFormat.NODE:
rv = cast(out, POINTER(MpvNode)).contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
else:
raise TypeError('_get_property only supports NODE and OSD_STRING formats.')
except PropertyUnavailableError as ex:
return None
def _set_property(self, name, value):
ename = name.encode('utf-8')
if isinstance(value, (list, set, dict)):
_1, _2, _3, pointer = _make_node_str_list(value)
_mpv_set_property(self.handle, ename, MpvFormat.NODE, pointer)
else:
_mpv_set_property_string(self.handle, ename, _mpv_coax_proptype(value))
def __getattr__(self, name):
return self._get_property(_py_to_mpv(name), lazy_decoder)
def __setattr__(self, name, value):
try:
if name != 'handle' and not name.startswith('_'):
self._set_property(_py_to_mpv(name), value)
else:
super().__setattr__(name, value)
except AttributeError:
super().__setattr__(name, value)
def __dir__(self):
return super().__dir__() + [ name.replace('-', '_') for name in self.property_list ]
@property
def properties(self):
return { name: self.option_info(name) for name in self.property_list }
# Dict-like option access
def __getitem__(self, name, file_local=False):
"""Get an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._get_property(prefix+name, lazy_decoder)
def __setitem__(self, name, value, file_local=False):
"""Set an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._set_property(prefix+name, value)
def __iter__(self):
"""Iterate over all option names."""
return iter(self.options)
def option_info(self, name):
"""Get information on the given option."""
try:
return self._get_property('option-info/'+name)
except AttributeError:
return None
|
jaseg/python-mpv | mpv.py | MPV.overlay_add | python | def overlay_add(self, overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride):
self.command('overlay_add', overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride) | Mapped mpv overlay_add command, see man mpv(1). | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L774-L776 | null | class MPV(object):
"""See man mpv(1) for the details of the implemented commands. All mpv properties can be accessed as
``my_mpv.some_property`` and all mpv options can be accessed as ``my_mpv['some-option']``.
By default, properties are returned as decoded ``str`` and an error is thrown if the value does not contain valid
utf-8. To get a decoded ``str`` if possibly but ``bytes`` instead of an error if not, use
``my_mpv.lazy.some_property``. To always get raw ``bytes``, use ``my_mpv.raw.some_property``. To access a
property's decoded OSD value, use ``my_mpv.osd.some_property``.
To get API information on an option, use ``my_mpv.option_info('option-name')``. To get API information on a
property, use ``my_mpv.properties['property-name']``. Take care to use mpv's dashed-names instead of the
underscore_names exposed on the python object.
To make your program not barf hard the first time its used on a weird file system **always** access properties
containing file names or file tags through ``MPV.raw``. """
def __init__(self, *extra_mpv_flags, log_handler=None, start_event_thread=True, loglevel=None, **extra_mpv_opts):
"""Create an MPV instance.
Extra arguments and extra keyword arguments will be passed to mpv as options.
"""
self.handle = _mpv_create()
self._event_thread = None
_mpv_set_option_string(self.handle, b'audio-display', b'no')
istr = lambda o: ('yes' if o else 'no') if type(o) is bool else str(o)
try:
for flag in extra_mpv_flags:
_mpv_set_option_string(self.handle, flag.encode('utf-8'), b'')
for k,v in extra_mpv_opts.items():
_mpv_set_option_string(self.handle, k.replace('_', '-').encode('utf-8'), istr(v).encode('utf-8'))
finally:
_mpv_initialize(self.handle)
self.osd = _OSDPropertyProxy(self)
self.file_local = _FileLocalProxy(self)
self.raw = _DecoderPropertyProxy(self, identity_decoder)
self.strict = _DecoderPropertyProxy(self, strict_decoder)
self.lazy = _DecoderPropertyProxy(self, lazy_decoder)
self._event_callbacks = []
self._property_handlers = collections.defaultdict(lambda: [])
self._message_handlers = {}
self._key_binding_handlers = {}
self._playback_cond = threading.Condition()
self._event_handle = _mpv_create_client(self.handle, b'py_event_handler')
self._loop = partial(_event_loop, self._event_handle, self._playback_cond, self._event_callbacks,
self._message_handlers, self._property_handlers, log_handler)
if loglevel is not None or log_handler is not None:
self.set_loglevel(loglevel or 'terminal-default')
if start_event_thread:
self._event_thread = threading.Thread(target=self._loop, name='MPVEventHandlerThread')
self._event_thread.setDaemon(True)
self._event_thread.start()
else:
self._event_thread = None
def wait_for_playback(self):
"""Waits until playback of the current title is paused or done."""
with self._playback_cond:
self._playback_cond.wait()
def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True):
"""Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for
properties such as ``idle_active`` indicating the player is done with regular playback and just idling around
"""
sema = threading.Semaphore(value=0)
def observer(name, val):
if cond(val):
sema.release()
self.observe_property(name, observer)
if not level_sensitive or not cond(getattr(self, name.replace('-', '_'))):
sema.acquire()
self.unobserve_property(name, observer)
def __del__(self):
if self.handle:
self.terminate()
def terminate(self):
"""Properly terminates this player instance. Preferably use this instead of relying on python's garbage
collector to cause this to be called from the object's destructor.
"""
self.handle, handle = None, self.handle
if threading.current_thread() is self._event_thread:
# Handle special case to allow event handle to be detached.
# This is necessary since otherwise the event thread would deadlock itself.
grim_reaper = threading.Thread(target=lambda: _mpv_terminate_destroy(handle))
grim_reaper.start()
else:
_mpv_terminate_destroy(handle)
if self._event_thread:
self._event_thread.join()
def set_loglevel(self, level):
"""Set MPV's log level. This adjusts which output will be sent to this object's log handlers. If you just want
mpv's regular terminal output, you don't need to adjust this but just need to pass a log handler to the MPV
constructur such as ``MPV(log_handler=print)``.
Valid log levels are "no", "fatal", "error", "warn", "info", "v" "debug" and "trace". For details see your mpv's
client.h header file.
"""
_mpv_request_log_messages(self._event_handle, level.encode('utf-8'))
def command(self, name, *args):
"""Execute a raw command."""
args = [name.encode('utf-8')] + [ (arg if type(arg) is bytes else str(arg).encode('utf-8'))
for arg in args if arg is not None ] + [None]
_mpv_command(self.handle, (c_char_p*len(args))(*args))
def node_command(self, name, *args, decoder=strict_decoder):
_1, _2, _3, pointer = _make_node_str_list([name, *args])
out = cast(create_string_buffer(sizeof(MpvNode)), POINTER(MpvNode))
ppointer = cast(pointer, POINTER(MpvNode))
_mpv_command_node(self.handle, ppointer, out)
rv = out.contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
def seek(self, amount, reference="relative", precision="default-precise"):
"""Mapped mpv seek command, see man mpv(1)."""
self.command('seek', amount, reference, precision)
def revert_seek(self):
"""Mapped mpv revert_seek command, see man mpv(1)."""
self.command('revert_seek');
def frame_step(self):
"""Mapped mpv frame_step command, see man mpv(1)."""
self.command('frame_step')
def frame_back_step(self):
"""Mapped mpv frame_back_step command, see man mpv(1)."""
self.command('frame_back_step')
def property_add(self, name, value=1):
"""Add the given value to the property's value. On overflow or underflow, clamp the property to the maximum. If
``value`` is omitted, assume ``1``.
"""
self.command('add', name, value)
def property_multiply(self, name, factor):
"""Multiply the value of a property with a numeric factor."""
self.command('multiply', name, factor)
def cycle(self, name, direction='up'):
"""Cycle the given property. ``up`` and ``down`` set the cycle direction. On overflow, set the property back to
the minimum, on underflow set it to the maximum. If ``up`` or ``down`` is omitted, assume ``up``.
"""
self.command('cycle', name, direction)
def screenshot(self, includes='subtitles', mode='single'):
"""Mapped mpv screenshot command, see man mpv(1)."""
self.command('screenshot', includes, mode)
def screenshot_to_file(self, filename, includes='subtitles'):
"""Mapped mpv screenshot_to_file command, see man mpv(1)."""
self.command('screenshot_to_file', filename.encode(fs_enc), includes)
def screenshot_raw(self, includes='subtitles'):
"""Mapped mpv screenshot_raw command, see man mpv(1). Returns a pillow Image object."""
from PIL import Image
res = self.node_command('screenshot-raw', includes)
if res['format'] != 'bgr0':
raise ValueError('Screenshot in unknown format "{}". Currently, only bgr0 is supported.'
.format(res['format']))
img = Image.frombytes('RGBA', (res['w'], res['h']), res['data'])
b,g,r,a = img.split()
return Image.merge('RGB', (r,g,b))
def playlist_next(self, mode='weak'):
"""Mapped mpv playlist_next command, see man mpv(1)."""
self.command('playlist_next', mode)
def playlist_prev(self, mode='weak'):
"""Mapped mpv playlist_prev command, see man mpv(1)."""
self.command('playlist_prev', mode)
@staticmethod
def _encode_options(options):
return ','.join('{}={}'.format(str(key), str(val)) for key, val in options.items())
def loadfile(self, filename, mode='replace', **options):
"""Mapped mpv loadfile command, see man mpv(1)."""
self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode_options(options))
def loadlist(self, playlist, mode='replace'):
"""Mapped mpv loadlist command, see man mpv(1)."""
self.command('loadlist', playlist.encode(fs_enc), mode)
def playlist_clear(self):
"""Mapped mpv playlist_clear command, see man mpv(1)."""
self.command('playlist_clear')
def playlist_remove(self, index='current'):
"""Mapped mpv playlist_remove command, see man mpv(1)."""
self.command('playlist_remove', index)
def playlist_move(self, index1, index2):
"""Mapped mpv playlist_move command, see man mpv(1)."""
self.command('playlist_move', index1, index2)
def run(self, command, *args):
"""Mapped mpv run command, see man mpv(1)."""
self.command('run', command, *args)
def quit(self, code=None):
"""Mapped mpv quit command, see man mpv(1)."""
self.command('quit', code)
def quit_watch_later(self, code=None):
"""Mapped mpv quit_watch_later command, see man mpv(1)."""
self.command('quit_watch_later', code)
def sub_add(self, filename):
"""Mapped mpv sub_add command, see man mpv(1)."""
self.command('sub_add', filename.encode(fs_enc))
def sub_remove(self, sub_id=None):
"""Mapped mpv sub_remove command, see man mpv(1)."""
self.command('sub_remove', sub_id)
def sub_reload(self, sub_id=None):
"""Mapped mpv sub_reload command, see man mpv(1)."""
self.command('sub_reload', sub_id)
def sub_step(self, skip):
"""Mapped mpv sub_step command, see man mpv(1)."""
self.command('sub_step', skip)
def sub_seek(self, skip):
"""Mapped mpv sub_seek command, see man mpv(1)."""
self.command('sub_seek', skip)
def toggle_osd(self):
"""Mapped mpv osd command, see man mpv(1)."""
self.command('osd')
def show_text(self, string, duration='-1', level=None):
"""Mapped mpv show_text command, see man mpv(1)."""
self.command('show_text', string, duration, level)
def show_progress(self):
"""Mapped mpv show_progress command, see man mpv(1)."""
self.command('show_progress')
def discnav(self, command):
"""Mapped mpv discnav command, see man mpv(1)."""
self.command('discnav', command)
def write_watch_later_config(self):
"""Mapped mpv write_watch_later_config command, see man mpv(1)."""
self.command('write_watch_later_config')
def overlay_remove(self, overlay_id):
"""Mapped mpv overlay_remove command, see man mpv(1)."""
self.command('overlay_remove', overlay_id)
def script_message(self, *args):
"""Mapped mpv script_message command, see man mpv(1)."""
self.command('script_message', *args)
def script_message_to(self, target, *args):
"""Mapped mpv script_message_to command, see man mpv(1)."""
self.command('script_message_to', target, *args)
def observe_property(self, name, handler):
"""Register an observer on the named property. An observer is a function that is called with the new property
value every time the property's value is changed. The basic function signature is ``fun(property_name,
new_value)`` with new_value being the decoded property value as a python object. This function can be used as a
function decorator if no handler is given.
To unregister the observer, call either of ``mpv.unobserve_property(name, handler)``,
``mpv.unobserve_all_properties(handler)`` or the handler's ``unregister_mpv_properties`` attribute::
@player.observe_property('volume')
def my_handler(new_volume, *):
print("It's loud!", volume)
my_handler.unregister_mpv_properties()
"""
self._property_handlers[name].append(handler)
_mpv_observe_property(self._event_handle, hash(name)&0xffffffffffffffff, name.encode('utf-8'), MpvFormat.NODE)
def property_observer(self, name):
"""Function decorator to register a property observer. See ``MPV.observe_property`` for details."""
def wrapper(fun):
self.observe_property(name, fun)
fun.unobserve_mpv_properties = lambda: self.unobserve_property(name, fun)
return fun
return wrapper
def unobserve_property(self, name, handler):
"""Unregister a property observer. This requires both the observed property's name and the handler function that
was originally registered as one handler could be registered for several properties. To unregister a handler
from *all* observed properties see ``unobserve_all_properties``.
"""
self._property_handlers[name].remove(handler)
if not self._property_handlers[name]:
_mpv_unobserve_property(self._event_handle, hash(name)&0xffffffffffffffff)
def unobserve_all_properties(self, handler):
"""Unregister a property observer from *all* observed properties."""
for name in self._property_handlers:
self.unobserve_property(name, handler)
def register_message_handler(self, target, handler=None):
"""Register a mpv script message handler. This can be used to communicate with embedded lua scripts. Pass the
script message target name this handler should be listening to and the handler function.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
self._register_message_handler_internal(target, handler)
def _register_message_handler_internal(self, target, handler):
self._message_handlers[target] = handler
def unregister_message_handler(self, target_or_handler):
"""Unregister a mpv script message handler for the given script message target name.
You can also call the ``unregister_mpv_messages`` function attribute set on the handler function when it is
registered.
"""
if isinstance(target_or_handler, str):
del self._message_handlers[target_or_handler]
else:
for key, val in self._message_handlers.items():
if val == target_or_handler:
del self._message_handlers[key]
def message_handler(self, target):
"""Decorator to register a mpv script message handler.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
def register(handler):
self._register_message_handler_internal(target, handler)
handler.unregister_mpv_messages = lambda: self.unregister_message_handler(handler)
return handler
return register
def register_event_callback(self, callback):
"""Register a blanket event callback receiving all event types.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
self._event_callbacks.append(callback)
def unregister_event_callback(self, callback):
"""Unregiser an event callback."""
self._event_callbacks.remove(callback)
def event_callback(self, *event_types):
"""Function decorator to register a blanket event callback for the given event types. Event types can be given
as str (e.g. 'start-file'), integer or MpvEventID object.
WARNING: Due to the way this is filtering events, this decorator cannot be chained with itself.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
def register(callback):
types = [MpvEventID.from_str(t) if isinstance(t, str) else t for t in event_types] or MpvEventID.ANY
@wraps(callback)
def wrapper(event, *args, **kwargs):
if event['event_id'] in types:
callback(event, *args, **kwargs)
self._event_callbacks.append(wrapper)
wrapper.unregister_mpv_events = partial(self.unregister_event_callback, wrapper)
return wrapper
return register
@staticmethod
def _binding_name(callback_or_cmd):
return 'py_kb_{:016x}'.format(hash(callback_or_cmd)&0xffffffffffffffff)
def on_key_press(self, keydef, mode='force'):
"""Function decorator to register a simplified key binding. The callback is called whenever the key given is
*pressed*.
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.on_key_press('Q')
def binding():
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
The BIG FAT WARNING regarding untrusted keydefs from the key_binding method applies here as well.
"""
def register(fun):
@self.key_binding(keydef, mode)
@wraps(fun)
def wrapper(state='p-', name=None):
if state[0] in ('d', 'p'):
fun()
return wrapper
return register
def key_binding(self, keydef, mode='force'):
"""Function decorator to register a low-level key binding.
The callback function signature is ``fun(key_state, key_name)`` where ``key_state`` is either ``'U'`` for "key
up" or ``'D'`` for "key down".
The keydef format is: ``[Shift+][Ctrl+][Alt+][Meta+]<key>`` where ``<key>`` is either the literal character the
key produces (ASCII or Unicode character), or a symbolic name (as printed by ``mpv --input-keylist``).
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.key_binding('Q')
def binding(state, name):
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
BIG FAT WARNING: mpv's key binding mechanism is pretty powerful. This means, you essentially get arbitrary code
exectution through key bindings. This interface makes some limited effort to sanitize the keydef given in the
first parameter, but YOU SHOULD NOT RELY ON THIS IN FOR SECURITY. If your input comes from config files, this is
completely fine--but, if you are about to pass untrusted input into this parameter, better double-check whether
this is secure in your case.
"""
def register(fun):
fun.mpv_key_bindings = getattr(fun, 'mpv_key_bindings', []) + [keydef]
def unregister_all():
for keydef in fun.mpv_key_bindings:
self.unregister_key_binding(keydef)
fun.unregister_mpv_key_bindings = unregister_all
self.register_key_binding(keydef, fun, mode)
return fun
return register
def register_key_binding(self, keydef, callback_or_cmd, mode='force'):
"""Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python
callback function. See ``MPV.key_binding`` for details.
"""
if not re.match(r'(Shift+)?(Ctrl+)?(Alt+)?(Meta+)?(.|\w+)', keydef):
raise ValueError('Invalid keydef. Expected format: [Shift+][Ctrl+][Alt+][Meta+]<key>\n'
'<key> is either the literal character the key produces (ASCII or Unicode character), or a '
'symbolic name (as printed by --input-keylist')
binding_name = MPV._binding_name(keydef)
if callable(callback_or_cmd):
self._key_binding_handlers[binding_name] = callback_or_cmd
self.register_message_handler('key-binding', self._handle_key_binding_message)
self.command('define-section',
binding_name, '{} script-binding py_event_handler/{}'.format(keydef, binding_name), mode)
elif isinstance(callback_or_cmd, str):
self.command('define-section', binding_name, '{} {}'.format(keydef, callback_or_cmd), mode)
else:
raise TypeError('register_key_binding expects either an str with an mpv command or a python callable.')
self.command('enable-section', binding_name, 'allow-hide-cursor+allow-vo-dragging')
def _handle_key_binding_message(self, binding_name, key_state, key_name=None):
self._key_binding_handlers[binding_name](key_state, key_name)
def unregister_key_binding(self, keydef):
"""Unregister a key binding by keydef."""
binding_name = MPV._binding_name(keydef)
self.command('disable-section', binding_name)
self.command('define-section', binding_name, '')
if binding_name in self._key_binding_handlers:
del self._key_binding_handlers[binding_name]
if not self._key_binding_handlers:
self.unregister_message_handler('key-binding')
# Convenience functions
def play(self, filename):
"""Play a path or URL (requires ``ytdl`` option to be set)."""
self.loadfile(filename)
@property
def playlist_filenames(self):
"""Return all playlist item file names/URLs as a list of strs."""
return [element['filename'] for element in self.playlist]
def playlist_append(self, filename, **options):
"""Append a path or URL to the playlist. This does not start playing the file automatically. To do that, use
``MPV.loadfile(filename, 'append-play')``."""
self.loadfile(filename, 'append', **options)
# Property accessors
def _get_property(self, name, decoder=strict_decoder, fmt=MpvFormat.NODE):
out = create_string_buffer(sizeof(MpvNode))
try:
cval = _mpv_get_property(self.handle, name.encode('utf-8'), fmt, out)
if fmt is MpvFormat.OSD_STRING:
return cast(out, POINTER(c_char_p)).contents.value.decode('utf-8')
elif fmt is MpvFormat.NODE:
rv = cast(out, POINTER(MpvNode)).contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
else:
raise TypeError('_get_property only supports NODE and OSD_STRING formats.')
except PropertyUnavailableError as ex:
return None
def _set_property(self, name, value):
ename = name.encode('utf-8')
if isinstance(value, (list, set, dict)):
_1, _2, _3, pointer = _make_node_str_list(value)
_mpv_set_property(self.handle, ename, MpvFormat.NODE, pointer)
else:
_mpv_set_property_string(self.handle, ename, _mpv_coax_proptype(value))
def __getattr__(self, name):
return self._get_property(_py_to_mpv(name), lazy_decoder)
def __setattr__(self, name, value):
try:
if name != 'handle' and not name.startswith('_'):
self._set_property(_py_to_mpv(name), value)
else:
super().__setattr__(name, value)
except AttributeError:
super().__setattr__(name, value)
def __dir__(self):
return super().__dir__() + [ name.replace('-', '_') for name in self.property_list ]
@property
def properties(self):
return { name: self.option_info(name) for name in self.property_list }
# Dict-like option access
def __getitem__(self, name, file_local=False):
"""Get an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._get_property(prefix+name, lazy_decoder)
def __setitem__(self, name, value, file_local=False):
"""Set an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._set_property(prefix+name, value)
def __iter__(self):
"""Iterate over all option names."""
return iter(self.options)
def option_info(self, name):
"""Get information on the given option."""
try:
return self._get_property('option-info/'+name)
except AttributeError:
return None
|
jaseg/python-mpv | mpv.py | MPV.observe_property | python | def observe_property(self, name, handler):
self._property_handlers[name].append(handler)
_mpv_observe_property(self._event_handle, hash(name)&0xffffffffffffffff, name.encode('utf-8'), MpvFormat.NODE) | Register an observer on the named property. An observer is a function that is called with the new property
value every time the property's value is changed. The basic function signature is ``fun(property_name,
new_value)`` with new_value being the decoded property value as a python object. This function can be used as a
function decorator if no handler is given.
To unregister the observer, call either of ``mpv.unobserve_property(name, handler)``,
``mpv.unobserve_all_properties(handler)`` or the handler's ``unregister_mpv_properties`` attribute::
@player.observe_property('volume')
def my_handler(new_volume, *):
print("It's loud!", volume)
my_handler.unregister_mpv_properties() | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L790-L806 | null | class MPV(object):
"""See man mpv(1) for the details of the implemented commands. All mpv properties can be accessed as
``my_mpv.some_property`` and all mpv options can be accessed as ``my_mpv['some-option']``.
By default, properties are returned as decoded ``str`` and an error is thrown if the value does not contain valid
utf-8. To get a decoded ``str`` if possibly but ``bytes`` instead of an error if not, use
``my_mpv.lazy.some_property``. To always get raw ``bytes``, use ``my_mpv.raw.some_property``. To access a
property's decoded OSD value, use ``my_mpv.osd.some_property``.
To get API information on an option, use ``my_mpv.option_info('option-name')``. To get API information on a
property, use ``my_mpv.properties['property-name']``. Take care to use mpv's dashed-names instead of the
underscore_names exposed on the python object.
To make your program not barf hard the first time its used on a weird file system **always** access properties
containing file names or file tags through ``MPV.raw``. """
def __init__(self, *extra_mpv_flags, log_handler=None, start_event_thread=True, loglevel=None, **extra_mpv_opts):
"""Create an MPV instance.
Extra arguments and extra keyword arguments will be passed to mpv as options.
"""
self.handle = _mpv_create()
self._event_thread = None
_mpv_set_option_string(self.handle, b'audio-display', b'no')
istr = lambda o: ('yes' if o else 'no') if type(o) is bool else str(o)
try:
for flag in extra_mpv_flags:
_mpv_set_option_string(self.handle, flag.encode('utf-8'), b'')
for k,v in extra_mpv_opts.items():
_mpv_set_option_string(self.handle, k.replace('_', '-').encode('utf-8'), istr(v).encode('utf-8'))
finally:
_mpv_initialize(self.handle)
self.osd = _OSDPropertyProxy(self)
self.file_local = _FileLocalProxy(self)
self.raw = _DecoderPropertyProxy(self, identity_decoder)
self.strict = _DecoderPropertyProxy(self, strict_decoder)
self.lazy = _DecoderPropertyProxy(self, lazy_decoder)
self._event_callbacks = []
self._property_handlers = collections.defaultdict(lambda: [])
self._message_handlers = {}
self._key_binding_handlers = {}
self._playback_cond = threading.Condition()
self._event_handle = _mpv_create_client(self.handle, b'py_event_handler')
self._loop = partial(_event_loop, self._event_handle, self._playback_cond, self._event_callbacks,
self._message_handlers, self._property_handlers, log_handler)
if loglevel is not None or log_handler is not None:
self.set_loglevel(loglevel or 'terminal-default')
if start_event_thread:
self._event_thread = threading.Thread(target=self._loop, name='MPVEventHandlerThread')
self._event_thread.setDaemon(True)
self._event_thread.start()
else:
self._event_thread = None
def wait_for_playback(self):
"""Waits until playback of the current title is paused or done."""
with self._playback_cond:
self._playback_cond.wait()
def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True):
"""Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for
properties such as ``idle_active`` indicating the player is done with regular playback and just idling around
"""
sema = threading.Semaphore(value=0)
def observer(name, val):
if cond(val):
sema.release()
self.observe_property(name, observer)
if not level_sensitive or not cond(getattr(self, name.replace('-', '_'))):
sema.acquire()
self.unobserve_property(name, observer)
def __del__(self):
if self.handle:
self.terminate()
def terminate(self):
"""Properly terminates this player instance. Preferably use this instead of relying on python's garbage
collector to cause this to be called from the object's destructor.
"""
self.handle, handle = None, self.handle
if threading.current_thread() is self._event_thread:
# Handle special case to allow event handle to be detached.
# This is necessary since otherwise the event thread would deadlock itself.
grim_reaper = threading.Thread(target=lambda: _mpv_terminate_destroy(handle))
grim_reaper.start()
else:
_mpv_terminate_destroy(handle)
if self._event_thread:
self._event_thread.join()
def set_loglevel(self, level):
"""Set MPV's log level. This adjusts which output will be sent to this object's log handlers. If you just want
mpv's regular terminal output, you don't need to adjust this but just need to pass a log handler to the MPV
constructur such as ``MPV(log_handler=print)``.
Valid log levels are "no", "fatal", "error", "warn", "info", "v" "debug" and "trace". For details see your mpv's
client.h header file.
"""
_mpv_request_log_messages(self._event_handle, level.encode('utf-8'))
def command(self, name, *args):
"""Execute a raw command."""
args = [name.encode('utf-8')] + [ (arg if type(arg) is bytes else str(arg).encode('utf-8'))
for arg in args if arg is not None ] + [None]
_mpv_command(self.handle, (c_char_p*len(args))(*args))
def node_command(self, name, *args, decoder=strict_decoder):
_1, _2, _3, pointer = _make_node_str_list([name, *args])
out = cast(create_string_buffer(sizeof(MpvNode)), POINTER(MpvNode))
ppointer = cast(pointer, POINTER(MpvNode))
_mpv_command_node(self.handle, ppointer, out)
rv = out.contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
def seek(self, amount, reference="relative", precision="default-precise"):
"""Mapped mpv seek command, see man mpv(1)."""
self.command('seek', amount, reference, precision)
def revert_seek(self):
"""Mapped mpv revert_seek command, see man mpv(1)."""
self.command('revert_seek');
def frame_step(self):
"""Mapped mpv frame_step command, see man mpv(1)."""
self.command('frame_step')
def frame_back_step(self):
"""Mapped mpv frame_back_step command, see man mpv(1)."""
self.command('frame_back_step')
def property_add(self, name, value=1):
"""Add the given value to the property's value. On overflow or underflow, clamp the property to the maximum. If
``value`` is omitted, assume ``1``.
"""
self.command('add', name, value)
def property_multiply(self, name, factor):
"""Multiply the value of a property with a numeric factor."""
self.command('multiply', name, factor)
def cycle(self, name, direction='up'):
"""Cycle the given property. ``up`` and ``down`` set the cycle direction. On overflow, set the property back to
the minimum, on underflow set it to the maximum. If ``up`` or ``down`` is omitted, assume ``up``.
"""
self.command('cycle', name, direction)
def screenshot(self, includes='subtitles', mode='single'):
"""Mapped mpv screenshot command, see man mpv(1)."""
self.command('screenshot', includes, mode)
def screenshot_to_file(self, filename, includes='subtitles'):
"""Mapped mpv screenshot_to_file command, see man mpv(1)."""
self.command('screenshot_to_file', filename.encode(fs_enc), includes)
def screenshot_raw(self, includes='subtitles'):
"""Mapped mpv screenshot_raw command, see man mpv(1). Returns a pillow Image object."""
from PIL import Image
res = self.node_command('screenshot-raw', includes)
if res['format'] != 'bgr0':
raise ValueError('Screenshot in unknown format "{}". Currently, only bgr0 is supported.'
.format(res['format']))
img = Image.frombytes('RGBA', (res['w'], res['h']), res['data'])
b,g,r,a = img.split()
return Image.merge('RGB', (r,g,b))
def playlist_next(self, mode='weak'):
"""Mapped mpv playlist_next command, see man mpv(1)."""
self.command('playlist_next', mode)
def playlist_prev(self, mode='weak'):
"""Mapped mpv playlist_prev command, see man mpv(1)."""
self.command('playlist_prev', mode)
@staticmethod
def _encode_options(options):
return ','.join('{}={}'.format(str(key), str(val)) for key, val in options.items())
def loadfile(self, filename, mode='replace', **options):
"""Mapped mpv loadfile command, see man mpv(1)."""
self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode_options(options))
def loadlist(self, playlist, mode='replace'):
"""Mapped mpv loadlist command, see man mpv(1)."""
self.command('loadlist', playlist.encode(fs_enc), mode)
def playlist_clear(self):
"""Mapped mpv playlist_clear command, see man mpv(1)."""
self.command('playlist_clear')
def playlist_remove(self, index='current'):
"""Mapped mpv playlist_remove command, see man mpv(1)."""
self.command('playlist_remove', index)
def playlist_move(self, index1, index2):
"""Mapped mpv playlist_move command, see man mpv(1)."""
self.command('playlist_move', index1, index2)
def run(self, command, *args):
"""Mapped mpv run command, see man mpv(1)."""
self.command('run', command, *args)
def quit(self, code=None):
"""Mapped mpv quit command, see man mpv(1)."""
self.command('quit', code)
def quit_watch_later(self, code=None):
"""Mapped mpv quit_watch_later command, see man mpv(1)."""
self.command('quit_watch_later', code)
def sub_add(self, filename):
"""Mapped mpv sub_add command, see man mpv(1)."""
self.command('sub_add', filename.encode(fs_enc))
def sub_remove(self, sub_id=None):
"""Mapped mpv sub_remove command, see man mpv(1)."""
self.command('sub_remove', sub_id)
def sub_reload(self, sub_id=None):
"""Mapped mpv sub_reload command, see man mpv(1)."""
self.command('sub_reload', sub_id)
def sub_step(self, skip):
"""Mapped mpv sub_step command, see man mpv(1)."""
self.command('sub_step', skip)
def sub_seek(self, skip):
"""Mapped mpv sub_seek command, see man mpv(1)."""
self.command('sub_seek', skip)
def toggle_osd(self):
"""Mapped mpv osd command, see man mpv(1)."""
self.command('osd')
def show_text(self, string, duration='-1', level=None):
"""Mapped mpv show_text command, see man mpv(1)."""
self.command('show_text', string, duration, level)
def show_progress(self):
"""Mapped mpv show_progress command, see man mpv(1)."""
self.command('show_progress')
def discnav(self, command):
"""Mapped mpv discnav command, see man mpv(1)."""
self.command('discnav', command)
def write_watch_later_config(self):
"""Mapped mpv write_watch_later_config command, see man mpv(1)."""
self.command('write_watch_later_config')
def overlay_add(self, overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride):
"""Mapped mpv overlay_add command, see man mpv(1)."""
self.command('overlay_add', overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride)
def overlay_remove(self, overlay_id):
"""Mapped mpv overlay_remove command, see man mpv(1)."""
self.command('overlay_remove', overlay_id)
def script_message(self, *args):
"""Mapped mpv script_message command, see man mpv(1)."""
self.command('script_message', *args)
def script_message_to(self, target, *args):
"""Mapped mpv script_message_to command, see man mpv(1)."""
self.command('script_message_to', target, *args)
def property_observer(self, name):
"""Function decorator to register a property observer. See ``MPV.observe_property`` for details."""
def wrapper(fun):
self.observe_property(name, fun)
fun.unobserve_mpv_properties = lambda: self.unobserve_property(name, fun)
return fun
return wrapper
def unobserve_property(self, name, handler):
"""Unregister a property observer. This requires both the observed property's name and the handler function that
was originally registered as one handler could be registered for several properties. To unregister a handler
from *all* observed properties see ``unobserve_all_properties``.
"""
self._property_handlers[name].remove(handler)
if not self._property_handlers[name]:
_mpv_unobserve_property(self._event_handle, hash(name)&0xffffffffffffffff)
def unobserve_all_properties(self, handler):
"""Unregister a property observer from *all* observed properties."""
for name in self._property_handlers:
self.unobserve_property(name, handler)
def register_message_handler(self, target, handler=None):
"""Register a mpv script message handler. This can be used to communicate with embedded lua scripts. Pass the
script message target name this handler should be listening to and the handler function.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
self._register_message_handler_internal(target, handler)
def _register_message_handler_internal(self, target, handler):
self._message_handlers[target] = handler
def unregister_message_handler(self, target_or_handler):
"""Unregister a mpv script message handler for the given script message target name.
You can also call the ``unregister_mpv_messages`` function attribute set on the handler function when it is
registered.
"""
if isinstance(target_or_handler, str):
del self._message_handlers[target_or_handler]
else:
for key, val in self._message_handlers.items():
if val == target_or_handler:
del self._message_handlers[key]
def message_handler(self, target):
"""Decorator to register a mpv script message handler.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
def register(handler):
self._register_message_handler_internal(target, handler)
handler.unregister_mpv_messages = lambda: self.unregister_message_handler(handler)
return handler
return register
def register_event_callback(self, callback):
"""Register a blanket event callback receiving all event types.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
self._event_callbacks.append(callback)
def unregister_event_callback(self, callback):
"""Unregiser an event callback."""
self._event_callbacks.remove(callback)
def event_callback(self, *event_types):
"""Function decorator to register a blanket event callback for the given event types. Event types can be given
as str (e.g. 'start-file'), integer or MpvEventID object.
WARNING: Due to the way this is filtering events, this decorator cannot be chained with itself.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
def register(callback):
types = [MpvEventID.from_str(t) if isinstance(t, str) else t for t in event_types] or MpvEventID.ANY
@wraps(callback)
def wrapper(event, *args, **kwargs):
if event['event_id'] in types:
callback(event, *args, **kwargs)
self._event_callbacks.append(wrapper)
wrapper.unregister_mpv_events = partial(self.unregister_event_callback, wrapper)
return wrapper
return register
@staticmethod
def _binding_name(callback_or_cmd):
return 'py_kb_{:016x}'.format(hash(callback_or_cmd)&0xffffffffffffffff)
def on_key_press(self, keydef, mode='force'):
"""Function decorator to register a simplified key binding. The callback is called whenever the key given is
*pressed*.
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.on_key_press('Q')
def binding():
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
The BIG FAT WARNING regarding untrusted keydefs from the key_binding method applies here as well.
"""
def register(fun):
@self.key_binding(keydef, mode)
@wraps(fun)
def wrapper(state='p-', name=None):
if state[0] in ('d', 'p'):
fun()
return wrapper
return register
def key_binding(self, keydef, mode='force'):
"""Function decorator to register a low-level key binding.
The callback function signature is ``fun(key_state, key_name)`` where ``key_state`` is either ``'U'`` for "key
up" or ``'D'`` for "key down".
The keydef format is: ``[Shift+][Ctrl+][Alt+][Meta+]<key>`` where ``<key>`` is either the literal character the
key produces (ASCII or Unicode character), or a symbolic name (as printed by ``mpv --input-keylist``).
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.key_binding('Q')
def binding(state, name):
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
BIG FAT WARNING: mpv's key binding mechanism is pretty powerful. This means, you essentially get arbitrary code
exectution through key bindings. This interface makes some limited effort to sanitize the keydef given in the
first parameter, but YOU SHOULD NOT RELY ON THIS IN FOR SECURITY. If your input comes from config files, this is
completely fine--but, if you are about to pass untrusted input into this parameter, better double-check whether
this is secure in your case.
"""
def register(fun):
fun.mpv_key_bindings = getattr(fun, 'mpv_key_bindings', []) + [keydef]
def unregister_all():
for keydef in fun.mpv_key_bindings:
self.unregister_key_binding(keydef)
fun.unregister_mpv_key_bindings = unregister_all
self.register_key_binding(keydef, fun, mode)
return fun
return register
def register_key_binding(self, keydef, callback_or_cmd, mode='force'):
"""Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python
callback function. See ``MPV.key_binding`` for details.
"""
if not re.match(r'(Shift+)?(Ctrl+)?(Alt+)?(Meta+)?(.|\w+)', keydef):
raise ValueError('Invalid keydef. Expected format: [Shift+][Ctrl+][Alt+][Meta+]<key>\n'
'<key> is either the literal character the key produces (ASCII or Unicode character), or a '
'symbolic name (as printed by --input-keylist')
binding_name = MPV._binding_name(keydef)
if callable(callback_or_cmd):
self._key_binding_handlers[binding_name] = callback_or_cmd
self.register_message_handler('key-binding', self._handle_key_binding_message)
self.command('define-section',
binding_name, '{} script-binding py_event_handler/{}'.format(keydef, binding_name), mode)
elif isinstance(callback_or_cmd, str):
self.command('define-section', binding_name, '{} {}'.format(keydef, callback_or_cmd), mode)
else:
raise TypeError('register_key_binding expects either an str with an mpv command or a python callable.')
self.command('enable-section', binding_name, 'allow-hide-cursor+allow-vo-dragging')
def _handle_key_binding_message(self, binding_name, key_state, key_name=None):
self._key_binding_handlers[binding_name](key_state, key_name)
def unregister_key_binding(self, keydef):
"""Unregister a key binding by keydef."""
binding_name = MPV._binding_name(keydef)
self.command('disable-section', binding_name)
self.command('define-section', binding_name, '')
if binding_name in self._key_binding_handlers:
del self._key_binding_handlers[binding_name]
if not self._key_binding_handlers:
self.unregister_message_handler('key-binding')
# Convenience functions
def play(self, filename):
"""Play a path or URL (requires ``ytdl`` option to be set)."""
self.loadfile(filename)
@property
def playlist_filenames(self):
"""Return all playlist item file names/URLs as a list of strs."""
return [element['filename'] for element in self.playlist]
def playlist_append(self, filename, **options):
"""Append a path or URL to the playlist. This does not start playing the file automatically. To do that, use
``MPV.loadfile(filename, 'append-play')``."""
self.loadfile(filename, 'append', **options)
# Property accessors
def _get_property(self, name, decoder=strict_decoder, fmt=MpvFormat.NODE):
out = create_string_buffer(sizeof(MpvNode))
try:
cval = _mpv_get_property(self.handle, name.encode('utf-8'), fmt, out)
if fmt is MpvFormat.OSD_STRING:
return cast(out, POINTER(c_char_p)).contents.value.decode('utf-8')
elif fmt is MpvFormat.NODE:
rv = cast(out, POINTER(MpvNode)).contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
else:
raise TypeError('_get_property only supports NODE and OSD_STRING formats.')
except PropertyUnavailableError as ex:
return None
def _set_property(self, name, value):
ename = name.encode('utf-8')
if isinstance(value, (list, set, dict)):
_1, _2, _3, pointer = _make_node_str_list(value)
_mpv_set_property(self.handle, ename, MpvFormat.NODE, pointer)
else:
_mpv_set_property_string(self.handle, ename, _mpv_coax_proptype(value))
def __getattr__(self, name):
return self._get_property(_py_to_mpv(name), lazy_decoder)
def __setattr__(self, name, value):
try:
if name != 'handle' and not name.startswith('_'):
self._set_property(_py_to_mpv(name), value)
else:
super().__setattr__(name, value)
except AttributeError:
super().__setattr__(name, value)
def __dir__(self):
return super().__dir__() + [ name.replace('-', '_') for name in self.property_list ]
@property
def properties(self):
return { name: self.option_info(name) for name in self.property_list }
# Dict-like option access
def __getitem__(self, name, file_local=False):
"""Get an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._get_property(prefix+name, lazy_decoder)
def __setitem__(self, name, value, file_local=False):
"""Set an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._set_property(prefix+name, value)
def __iter__(self):
"""Iterate over all option names."""
return iter(self.options)
def option_info(self, name):
"""Get information on the given option."""
try:
return self._get_property('option-info/'+name)
except AttributeError:
return None
|
jaseg/python-mpv | mpv.py | MPV.property_observer | python | def property_observer(self, name):
def wrapper(fun):
self.observe_property(name, fun)
fun.unobserve_mpv_properties = lambda: self.unobserve_property(name, fun)
return fun
return wrapper | Function decorator to register a property observer. See ``MPV.observe_property`` for details. | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L808-L814 | null | class MPV(object):
"""See man mpv(1) for the details of the implemented commands. All mpv properties can be accessed as
``my_mpv.some_property`` and all mpv options can be accessed as ``my_mpv['some-option']``.
By default, properties are returned as decoded ``str`` and an error is thrown if the value does not contain valid
utf-8. To get a decoded ``str`` if possibly but ``bytes`` instead of an error if not, use
``my_mpv.lazy.some_property``. To always get raw ``bytes``, use ``my_mpv.raw.some_property``. To access a
property's decoded OSD value, use ``my_mpv.osd.some_property``.
To get API information on an option, use ``my_mpv.option_info('option-name')``. To get API information on a
property, use ``my_mpv.properties['property-name']``. Take care to use mpv's dashed-names instead of the
underscore_names exposed on the python object.
To make your program not barf hard the first time its used on a weird file system **always** access properties
containing file names or file tags through ``MPV.raw``. """
def __init__(self, *extra_mpv_flags, log_handler=None, start_event_thread=True, loglevel=None, **extra_mpv_opts):
"""Create an MPV instance.
Extra arguments and extra keyword arguments will be passed to mpv as options.
"""
self.handle = _mpv_create()
self._event_thread = None
_mpv_set_option_string(self.handle, b'audio-display', b'no')
istr = lambda o: ('yes' if o else 'no') if type(o) is bool else str(o)
try:
for flag in extra_mpv_flags:
_mpv_set_option_string(self.handle, flag.encode('utf-8'), b'')
for k,v in extra_mpv_opts.items():
_mpv_set_option_string(self.handle, k.replace('_', '-').encode('utf-8'), istr(v).encode('utf-8'))
finally:
_mpv_initialize(self.handle)
self.osd = _OSDPropertyProxy(self)
self.file_local = _FileLocalProxy(self)
self.raw = _DecoderPropertyProxy(self, identity_decoder)
self.strict = _DecoderPropertyProxy(self, strict_decoder)
self.lazy = _DecoderPropertyProxy(self, lazy_decoder)
self._event_callbacks = []
self._property_handlers = collections.defaultdict(lambda: [])
self._message_handlers = {}
self._key_binding_handlers = {}
self._playback_cond = threading.Condition()
self._event_handle = _mpv_create_client(self.handle, b'py_event_handler')
self._loop = partial(_event_loop, self._event_handle, self._playback_cond, self._event_callbacks,
self._message_handlers, self._property_handlers, log_handler)
if loglevel is not None or log_handler is not None:
self.set_loglevel(loglevel or 'terminal-default')
if start_event_thread:
self._event_thread = threading.Thread(target=self._loop, name='MPVEventHandlerThread')
self._event_thread.setDaemon(True)
self._event_thread.start()
else:
self._event_thread = None
def wait_for_playback(self):
"""Waits until playback of the current title is paused or done."""
with self._playback_cond:
self._playback_cond.wait()
def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True):
"""Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for
properties such as ``idle_active`` indicating the player is done with regular playback and just idling around
"""
sema = threading.Semaphore(value=0)
def observer(name, val):
if cond(val):
sema.release()
self.observe_property(name, observer)
if not level_sensitive or not cond(getattr(self, name.replace('-', '_'))):
sema.acquire()
self.unobserve_property(name, observer)
def __del__(self):
if self.handle:
self.terminate()
def terminate(self):
"""Properly terminates this player instance. Preferably use this instead of relying on python's garbage
collector to cause this to be called from the object's destructor.
"""
self.handle, handle = None, self.handle
if threading.current_thread() is self._event_thread:
# Handle special case to allow event handle to be detached.
# This is necessary since otherwise the event thread would deadlock itself.
grim_reaper = threading.Thread(target=lambda: _mpv_terminate_destroy(handle))
grim_reaper.start()
else:
_mpv_terminate_destroy(handle)
if self._event_thread:
self._event_thread.join()
def set_loglevel(self, level):
"""Set MPV's log level. This adjusts which output will be sent to this object's log handlers. If you just want
mpv's regular terminal output, you don't need to adjust this but just need to pass a log handler to the MPV
constructur such as ``MPV(log_handler=print)``.
Valid log levels are "no", "fatal", "error", "warn", "info", "v" "debug" and "trace". For details see your mpv's
client.h header file.
"""
_mpv_request_log_messages(self._event_handle, level.encode('utf-8'))
def command(self, name, *args):
"""Execute a raw command."""
args = [name.encode('utf-8')] + [ (arg if type(arg) is bytes else str(arg).encode('utf-8'))
for arg in args if arg is not None ] + [None]
_mpv_command(self.handle, (c_char_p*len(args))(*args))
def node_command(self, name, *args, decoder=strict_decoder):
_1, _2, _3, pointer = _make_node_str_list([name, *args])
out = cast(create_string_buffer(sizeof(MpvNode)), POINTER(MpvNode))
ppointer = cast(pointer, POINTER(MpvNode))
_mpv_command_node(self.handle, ppointer, out)
rv = out.contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
def seek(self, amount, reference="relative", precision="default-precise"):
"""Mapped mpv seek command, see man mpv(1)."""
self.command('seek', amount, reference, precision)
def revert_seek(self):
"""Mapped mpv revert_seek command, see man mpv(1)."""
self.command('revert_seek');
def frame_step(self):
"""Mapped mpv frame_step command, see man mpv(1)."""
self.command('frame_step')
def frame_back_step(self):
"""Mapped mpv frame_back_step command, see man mpv(1)."""
self.command('frame_back_step')
def property_add(self, name, value=1):
"""Add the given value to the property's value. On overflow or underflow, clamp the property to the maximum. If
``value`` is omitted, assume ``1``.
"""
self.command('add', name, value)
def property_multiply(self, name, factor):
"""Multiply the value of a property with a numeric factor."""
self.command('multiply', name, factor)
def cycle(self, name, direction='up'):
"""Cycle the given property. ``up`` and ``down`` set the cycle direction. On overflow, set the property back to
the minimum, on underflow set it to the maximum. If ``up`` or ``down`` is omitted, assume ``up``.
"""
self.command('cycle', name, direction)
def screenshot(self, includes='subtitles', mode='single'):
"""Mapped mpv screenshot command, see man mpv(1)."""
self.command('screenshot', includes, mode)
def screenshot_to_file(self, filename, includes='subtitles'):
"""Mapped mpv screenshot_to_file command, see man mpv(1)."""
self.command('screenshot_to_file', filename.encode(fs_enc), includes)
def screenshot_raw(self, includes='subtitles'):
"""Mapped mpv screenshot_raw command, see man mpv(1). Returns a pillow Image object."""
from PIL import Image
res = self.node_command('screenshot-raw', includes)
if res['format'] != 'bgr0':
raise ValueError('Screenshot in unknown format "{}". Currently, only bgr0 is supported.'
.format(res['format']))
img = Image.frombytes('RGBA', (res['w'], res['h']), res['data'])
b,g,r,a = img.split()
return Image.merge('RGB', (r,g,b))
def playlist_next(self, mode='weak'):
"""Mapped mpv playlist_next command, see man mpv(1)."""
self.command('playlist_next', mode)
def playlist_prev(self, mode='weak'):
"""Mapped mpv playlist_prev command, see man mpv(1)."""
self.command('playlist_prev', mode)
@staticmethod
def _encode_options(options):
return ','.join('{}={}'.format(str(key), str(val)) for key, val in options.items())
def loadfile(self, filename, mode='replace', **options):
"""Mapped mpv loadfile command, see man mpv(1)."""
self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode_options(options))
def loadlist(self, playlist, mode='replace'):
"""Mapped mpv loadlist command, see man mpv(1)."""
self.command('loadlist', playlist.encode(fs_enc), mode)
def playlist_clear(self):
"""Mapped mpv playlist_clear command, see man mpv(1)."""
self.command('playlist_clear')
def playlist_remove(self, index='current'):
"""Mapped mpv playlist_remove command, see man mpv(1)."""
self.command('playlist_remove', index)
def playlist_move(self, index1, index2):
"""Mapped mpv playlist_move command, see man mpv(1)."""
self.command('playlist_move', index1, index2)
def run(self, command, *args):
"""Mapped mpv run command, see man mpv(1)."""
self.command('run', command, *args)
def quit(self, code=None):
"""Mapped mpv quit command, see man mpv(1)."""
self.command('quit', code)
def quit_watch_later(self, code=None):
"""Mapped mpv quit_watch_later command, see man mpv(1)."""
self.command('quit_watch_later', code)
def sub_add(self, filename):
"""Mapped mpv sub_add command, see man mpv(1)."""
self.command('sub_add', filename.encode(fs_enc))
def sub_remove(self, sub_id=None):
"""Mapped mpv sub_remove command, see man mpv(1)."""
self.command('sub_remove', sub_id)
def sub_reload(self, sub_id=None):
"""Mapped mpv sub_reload command, see man mpv(1)."""
self.command('sub_reload', sub_id)
def sub_step(self, skip):
"""Mapped mpv sub_step command, see man mpv(1)."""
self.command('sub_step', skip)
def sub_seek(self, skip):
"""Mapped mpv sub_seek command, see man mpv(1)."""
self.command('sub_seek', skip)
def toggle_osd(self):
"""Mapped mpv osd command, see man mpv(1)."""
self.command('osd')
def show_text(self, string, duration='-1', level=None):
"""Mapped mpv show_text command, see man mpv(1)."""
self.command('show_text', string, duration, level)
def show_progress(self):
"""Mapped mpv show_progress command, see man mpv(1)."""
self.command('show_progress')
def discnav(self, command):
"""Mapped mpv discnav command, see man mpv(1)."""
self.command('discnav', command)
def write_watch_later_config(self):
"""Mapped mpv write_watch_later_config command, see man mpv(1)."""
self.command('write_watch_later_config')
def overlay_add(self, overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride):
"""Mapped mpv overlay_add command, see man mpv(1)."""
self.command('overlay_add', overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride)
def overlay_remove(self, overlay_id):
"""Mapped mpv overlay_remove command, see man mpv(1)."""
self.command('overlay_remove', overlay_id)
def script_message(self, *args):
"""Mapped mpv script_message command, see man mpv(1)."""
self.command('script_message', *args)
def script_message_to(self, target, *args):
"""Mapped mpv script_message_to command, see man mpv(1)."""
self.command('script_message_to', target, *args)
def observe_property(self, name, handler):
"""Register an observer on the named property. An observer is a function that is called with the new property
value every time the property's value is changed. The basic function signature is ``fun(property_name,
new_value)`` with new_value being the decoded property value as a python object. This function can be used as a
function decorator if no handler is given.
To unregister the observer, call either of ``mpv.unobserve_property(name, handler)``,
``mpv.unobserve_all_properties(handler)`` or the handler's ``unregister_mpv_properties`` attribute::
@player.observe_property('volume')
def my_handler(new_volume, *):
print("It's loud!", volume)
my_handler.unregister_mpv_properties()
"""
self._property_handlers[name].append(handler)
_mpv_observe_property(self._event_handle, hash(name)&0xffffffffffffffff, name.encode('utf-8'), MpvFormat.NODE)
def unobserve_property(self, name, handler):
"""Unregister a property observer. This requires both the observed property's name and the handler function that
was originally registered as one handler could be registered for several properties. To unregister a handler
from *all* observed properties see ``unobserve_all_properties``.
"""
self._property_handlers[name].remove(handler)
if not self._property_handlers[name]:
_mpv_unobserve_property(self._event_handle, hash(name)&0xffffffffffffffff)
def unobserve_all_properties(self, handler):
"""Unregister a property observer from *all* observed properties."""
for name in self._property_handlers:
self.unobserve_property(name, handler)
def register_message_handler(self, target, handler=None):
"""Register a mpv script message handler. This can be used to communicate with embedded lua scripts. Pass the
script message target name this handler should be listening to and the handler function.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
self._register_message_handler_internal(target, handler)
def _register_message_handler_internal(self, target, handler):
self._message_handlers[target] = handler
def unregister_message_handler(self, target_or_handler):
"""Unregister a mpv script message handler for the given script message target name.
You can also call the ``unregister_mpv_messages`` function attribute set on the handler function when it is
registered.
"""
if isinstance(target_or_handler, str):
del self._message_handlers[target_or_handler]
else:
for key, val in self._message_handlers.items():
if val == target_or_handler:
del self._message_handlers[key]
def message_handler(self, target):
"""Decorator to register a mpv script message handler.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
def register(handler):
self._register_message_handler_internal(target, handler)
handler.unregister_mpv_messages = lambda: self.unregister_message_handler(handler)
return handler
return register
def register_event_callback(self, callback):
"""Register a blanket event callback receiving all event types.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
self._event_callbacks.append(callback)
def unregister_event_callback(self, callback):
"""Unregiser an event callback."""
self._event_callbacks.remove(callback)
def event_callback(self, *event_types):
"""Function decorator to register a blanket event callback for the given event types. Event types can be given
as str (e.g. 'start-file'), integer or MpvEventID object.
WARNING: Due to the way this is filtering events, this decorator cannot be chained with itself.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
def register(callback):
types = [MpvEventID.from_str(t) if isinstance(t, str) else t for t in event_types] or MpvEventID.ANY
@wraps(callback)
def wrapper(event, *args, **kwargs):
if event['event_id'] in types:
callback(event, *args, **kwargs)
self._event_callbacks.append(wrapper)
wrapper.unregister_mpv_events = partial(self.unregister_event_callback, wrapper)
return wrapper
return register
@staticmethod
def _binding_name(callback_or_cmd):
return 'py_kb_{:016x}'.format(hash(callback_or_cmd)&0xffffffffffffffff)
def on_key_press(self, keydef, mode='force'):
"""Function decorator to register a simplified key binding. The callback is called whenever the key given is
*pressed*.
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.on_key_press('Q')
def binding():
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
The BIG FAT WARNING regarding untrusted keydefs from the key_binding method applies here as well.
"""
def register(fun):
@self.key_binding(keydef, mode)
@wraps(fun)
def wrapper(state='p-', name=None):
if state[0] in ('d', 'p'):
fun()
return wrapper
return register
def key_binding(self, keydef, mode='force'):
"""Function decorator to register a low-level key binding.
The callback function signature is ``fun(key_state, key_name)`` where ``key_state`` is either ``'U'`` for "key
up" or ``'D'`` for "key down".
The keydef format is: ``[Shift+][Ctrl+][Alt+][Meta+]<key>`` where ``<key>`` is either the literal character the
key produces (ASCII or Unicode character), or a symbolic name (as printed by ``mpv --input-keylist``).
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.key_binding('Q')
def binding(state, name):
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
BIG FAT WARNING: mpv's key binding mechanism is pretty powerful. This means, you essentially get arbitrary code
exectution through key bindings. This interface makes some limited effort to sanitize the keydef given in the
first parameter, but YOU SHOULD NOT RELY ON THIS IN FOR SECURITY. If your input comes from config files, this is
completely fine--but, if you are about to pass untrusted input into this parameter, better double-check whether
this is secure in your case.
"""
def register(fun):
fun.mpv_key_bindings = getattr(fun, 'mpv_key_bindings', []) + [keydef]
def unregister_all():
for keydef in fun.mpv_key_bindings:
self.unregister_key_binding(keydef)
fun.unregister_mpv_key_bindings = unregister_all
self.register_key_binding(keydef, fun, mode)
return fun
return register
def register_key_binding(self, keydef, callback_or_cmd, mode='force'):
"""Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python
callback function. See ``MPV.key_binding`` for details.
"""
if not re.match(r'(Shift+)?(Ctrl+)?(Alt+)?(Meta+)?(.|\w+)', keydef):
raise ValueError('Invalid keydef. Expected format: [Shift+][Ctrl+][Alt+][Meta+]<key>\n'
'<key> is either the literal character the key produces (ASCII or Unicode character), or a '
'symbolic name (as printed by --input-keylist')
binding_name = MPV._binding_name(keydef)
if callable(callback_or_cmd):
self._key_binding_handlers[binding_name] = callback_or_cmd
self.register_message_handler('key-binding', self._handle_key_binding_message)
self.command('define-section',
binding_name, '{} script-binding py_event_handler/{}'.format(keydef, binding_name), mode)
elif isinstance(callback_or_cmd, str):
self.command('define-section', binding_name, '{} {}'.format(keydef, callback_or_cmd), mode)
else:
raise TypeError('register_key_binding expects either an str with an mpv command or a python callable.')
self.command('enable-section', binding_name, 'allow-hide-cursor+allow-vo-dragging')
def _handle_key_binding_message(self, binding_name, key_state, key_name=None):
self._key_binding_handlers[binding_name](key_state, key_name)
def unregister_key_binding(self, keydef):
"""Unregister a key binding by keydef."""
binding_name = MPV._binding_name(keydef)
self.command('disable-section', binding_name)
self.command('define-section', binding_name, '')
if binding_name in self._key_binding_handlers:
del self._key_binding_handlers[binding_name]
if not self._key_binding_handlers:
self.unregister_message_handler('key-binding')
# Convenience functions
def play(self, filename):
"""Play a path or URL (requires ``ytdl`` option to be set)."""
self.loadfile(filename)
@property
def playlist_filenames(self):
"""Return all playlist item file names/URLs as a list of strs."""
return [element['filename'] for element in self.playlist]
def playlist_append(self, filename, **options):
"""Append a path or URL to the playlist. This does not start playing the file automatically. To do that, use
``MPV.loadfile(filename, 'append-play')``."""
self.loadfile(filename, 'append', **options)
# Property accessors
def _get_property(self, name, decoder=strict_decoder, fmt=MpvFormat.NODE):
out = create_string_buffer(sizeof(MpvNode))
try:
cval = _mpv_get_property(self.handle, name.encode('utf-8'), fmt, out)
if fmt is MpvFormat.OSD_STRING:
return cast(out, POINTER(c_char_p)).contents.value.decode('utf-8')
elif fmt is MpvFormat.NODE:
rv = cast(out, POINTER(MpvNode)).contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
else:
raise TypeError('_get_property only supports NODE and OSD_STRING formats.')
except PropertyUnavailableError as ex:
return None
def _set_property(self, name, value):
ename = name.encode('utf-8')
if isinstance(value, (list, set, dict)):
_1, _2, _3, pointer = _make_node_str_list(value)
_mpv_set_property(self.handle, ename, MpvFormat.NODE, pointer)
else:
_mpv_set_property_string(self.handle, ename, _mpv_coax_proptype(value))
def __getattr__(self, name):
return self._get_property(_py_to_mpv(name), lazy_decoder)
def __setattr__(self, name, value):
try:
if name != 'handle' and not name.startswith('_'):
self._set_property(_py_to_mpv(name), value)
else:
super().__setattr__(name, value)
except AttributeError:
super().__setattr__(name, value)
def __dir__(self):
return super().__dir__() + [ name.replace('-', '_') for name in self.property_list ]
@property
def properties(self):
return { name: self.option_info(name) for name in self.property_list }
# Dict-like option access
def __getitem__(self, name, file_local=False):
"""Get an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._get_property(prefix+name, lazy_decoder)
def __setitem__(self, name, value, file_local=False):
"""Set an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._set_property(prefix+name, value)
def __iter__(self):
"""Iterate over all option names."""
return iter(self.options)
def option_info(self, name):
"""Get information on the given option."""
try:
return self._get_property('option-info/'+name)
except AttributeError:
return None
|
jaseg/python-mpv | mpv.py | MPV.unobserve_property | python | def unobserve_property(self, name, handler):
self._property_handlers[name].remove(handler)
if not self._property_handlers[name]:
_mpv_unobserve_property(self._event_handle, hash(name)&0xffffffffffffffff) | Unregister a property observer. This requires both the observed property's name and the handler function that
was originally registered as one handler could be registered for several properties. To unregister a handler
from *all* observed properties see ``unobserve_all_properties``. | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L816-L823 | null | class MPV(object):
"""See man mpv(1) for the details of the implemented commands. All mpv properties can be accessed as
``my_mpv.some_property`` and all mpv options can be accessed as ``my_mpv['some-option']``.
By default, properties are returned as decoded ``str`` and an error is thrown if the value does not contain valid
utf-8. To get a decoded ``str`` if possibly but ``bytes`` instead of an error if not, use
``my_mpv.lazy.some_property``. To always get raw ``bytes``, use ``my_mpv.raw.some_property``. To access a
property's decoded OSD value, use ``my_mpv.osd.some_property``.
To get API information on an option, use ``my_mpv.option_info('option-name')``. To get API information on a
property, use ``my_mpv.properties['property-name']``. Take care to use mpv's dashed-names instead of the
underscore_names exposed on the python object.
To make your program not barf hard the first time its used on a weird file system **always** access properties
containing file names or file tags through ``MPV.raw``. """
def __init__(self, *extra_mpv_flags, log_handler=None, start_event_thread=True, loglevel=None, **extra_mpv_opts):
"""Create an MPV instance.
Extra arguments and extra keyword arguments will be passed to mpv as options.
"""
self.handle = _mpv_create()
self._event_thread = None
_mpv_set_option_string(self.handle, b'audio-display', b'no')
istr = lambda o: ('yes' if o else 'no') if type(o) is bool else str(o)
try:
for flag in extra_mpv_flags:
_mpv_set_option_string(self.handle, flag.encode('utf-8'), b'')
for k,v in extra_mpv_opts.items():
_mpv_set_option_string(self.handle, k.replace('_', '-').encode('utf-8'), istr(v).encode('utf-8'))
finally:
_mpv_initialize(self.handle)
self.osd = _OSDPropertyProxy(self)
self.file_local = _FileLocalProxy(self)
self.raw = _DecoderPropertyProxy(self, identity_decoder)
self.strict = _DecoderPropertyProxy(self, strict_decoder)
self.lazy = _DecoderPropertyProxy(self, lazy_decoder)
self._event_callbacks = []
self._property_handlers = collections.defaultdict(lambda: [])
self._message_handlers = {}
self._key_binding_handlers = {}
self._playback_cond = threading.Condition()
self._event_handle = _mpv_create_client(self.handle, b'py_event_handler')
self._loop = partial(_event_loop, self._event_handle, self._playback_cond, self._event_callbacks,
self._message_handlers, self._property_handlers, log_handler)
if loglevel is not None or log_handler is not None:
self.set_loglevel(loglevel or 'terminal-default')
if start_event_thread:
self._event_thread = threading.Thread(target=self._loop, name='MPVEventHandlerThread')
self._event_thread.setDaemon(True)
self._event_thread.start()
else:
self._event_thread = None
def wait_for_playback(self):
"""Waits until playback of the current title is paused or done."""
with self._playback_cond:
self._playback_cond.wait()
def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True):
"""Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for
properties such as ``idle_active`` indicating the player is done with regular playback and just idling around
"""
sema = threading.Semaphore(value=0)
def observer(name, val):
if cond(val):
sema.release()
self.observe_property(name, observer)
if not level_sensitive or not cond(getattr(self, name.replace('-', '_'))):
sema.acquire()
self.unobserve_property(name, observer)
def __del__(self):
if self.handle:
self.terminate()
def terminate(self):
"""Properly terminates this player instance. Preferably use this instead of relying on python's garbage
collector to cause this to be called from the object's destructor.
"""
self.handle, handle = None, self.handle
if threading.current_thread() is self._event_thread:
# Handle special case to allow event handle to be detached.
# This is necessary since otherwise the event thread would deadlock itself.
grim_reaper = threading.Thread(target=lambda: _mpv_terminate_destroy(handle))
grim_reaper.start()
else:
_mpv_terminate_destroy(handle)
if self._event_thread:
self._event_thread.join()
def set_loglevel(self, level):
"""Set MPV's log level. This adjusts which output will be sent to this object's log handlers. If you just want
mpv's regular terminal output, you don't need to adjust this but just need to pass a log handler to the MPV
constructur such as ``MPV(log_handler=print)``.
Valid log levels are "no", "fatal", "error", "warn", "info", "v" "debug" and "trace". For details see your mpv's
client.h header file.
"""
_mpv_request_log_messages(self._event_handle, level.encode('utf-8'))
def command(self, name, *args):
"""Execute a raw command."""
args = [name.encode('utf-8')] + [ (arg if type(arg) is bytes else str(arg).encode('utf-8'))
for arg in args if arg is not None ] + [None]
_mpv_command(self.handle, (c_char_p*len(args))(*args))
def node_command(self, name, *args, decoder=strict_decoder):
_1, _2, _3, pointer = _make_node_str_list([name, *args])
out = cast(create_string_buffer(sizeof(MpvNode)), POINTER(MpvNode))
ppointer = cast(pointer, POINTER(MpvNode))
_mpv_command_node(self.handle, ppointer, out)
rv = out.contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
def seek(self, amount, reference="relative", precision="default-precise"):
"""Mapped mpv seek command, see man mpv(1)."""
self.command('seek', amount, reference, precision)
def revert_seek(self):
"""Mapped mpv revert_seek command, see man mpv(1)."""
self.command('revert_seek');
def frame_step(self):
"""Mapped mpv frame_step command, see man mpv(1)."""
self.command('frame_step')
def frame_back_step(self):
"""Mapped mpv frame_back_step command, see man mpv(1)."""
self.command('frame_back_step')
def property_add(self, name, value=1):
"""Add the given value to the property's value. On overflow or underflow, clamp the property to the maximum. If
``value`` is omitted, assume ``1``.
"""
self.command('add', name, value)
def property_multiply(self, name, factor):
"""Multiply the value of a property with a numeric factor."""
self.command('multiply', name, factor)
def cycle(self, name, direction='up'):
"""Cycle the given property. ``up`` and ``down`` set the cycle direction. On overflow, set the property back to
the minimum, on underflow set it to the maximum. If ``up`` or ``down`` is omitted, assume ``up``.
"""
self.command('cycle', name, direction)
def screenshot(self, includes='subtitles', mode='single'):
"""Mapped mpv screenshot command, see man mpv(1)."""
self.command('screenshot', includes, mode)
def screenshot_to_file(self, filename, includes='subtitles'):
"""Mapped mpv screenshot_to_file command, see man mpv(1)."""
self.command('screenshot_to_file', filename.encode(fs_enc), includes)
def screenshot_raw(self, includes='subtitles'):
"""Mapped mpv screenshot_raw command, see man mpv(1). Returns a pillow Image object."""
from PIL import Image
res = self.node_command('screenshot-raw', includes)
if res['format'] != 'bgr0':
raise ValueError('Screenshot in unknown format "{}". Currently, only bgr0 is supported.'
.format(res['format']))
img = Image.frombytes('RGBA', (res['w'], res['h']), res['data'])
b,g,r,a = img.split()
return Image.merge('RGB', (r,g,b))
def playlist_next(self, mode='weak'):
"""Mapped mpv playlist_next command, see man mpv(1)."""
self.command('playlist_next', mode)
def playlist_prev(self, mode='weak'):
"""Mapped mpv playlist_prev command, see man mpv(1)."""
self.command('playlist_prev', mode)
@staticmethod
def _encode_options(options):
return ','.join('{}={}'.format(str(key), str(val)) for key, val in options.items())
def loadfile(self, filename, mode='replace', **options):
"""Mapped mpv loadfile command, see man mpv(1)."""
self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode_options(options))
def loadlist(self, playlist, mode='replace'):
"""Mapped mpv loadlist command, see man mpv(1)."""
self.command('loadlist', playlist.encode(fs_enc), mode)
def playlist_clear(self):
"""Mapped mpv playlist_clear command, see man mpv(1)."""
self.command('playlist_clear')
def playlist_remove(self, index='current'):
"""Mapped mpv playlist_remove command, see man mpv(1)."""
self.command('playlist_remove', index)
def playlist_move(self, index1, index2):
"""Mapped mpv playlist_move command, see man mpv(1)."""
self.command('playlist_move', index1, index2)
def run(self, command, *args):
"""Mapped mpv run command, see man mpv(1)."""
self.command('run', command, *args)
def quit(self, code=None):
"""Mapped mpv quit command, see man mpv(1)."""
self.command('quit', code)
def quit_watch_later(self, code=None):
"""Mapped mpv quit_watch_later command, see man mpv(1)."""
self.command('quit_watch_later', code)
def sub_add(self, filename):
"""Mapped mpv sub_add command, see man mpv(1)."""
self.command('sub_add', filename.encode(fs_enc))
def sub_remove(self, sub_id=None):
"""Mapped mpv sub_remove command, see man mpv(1)."""
self.command('sub_remove', sub_id)
def sub_reload(self, sub_id=None):
"""Mapped mpv sub_reload command, see man mpv(1)."""
self.command('sub_reload', sub_id)
def sub_step(self, skip):
"""Mapped mpv sub_step command, see man mpv(1)."""
self.command('sub_step', skip)
def sub_seek(self, skip):
"""Mapped mpv sub_seek command, see man mpv(1)."""
self.command('sub_seek', skip)
def toggle_osd(self):
"""Mapped mpv osd command, see man mpv(1)."""
self.command('osd')
def show_text(self, string, duration='-1', level=None):
"""Mapped mpv show_text command, see man mpv(1)."""
self.command('show_text', string, duration, level)
def show_progress(self):
"""Mapped mpv show_progress command, see man mpv(1)."""
self.command('show_progress')
def discnav(self, command):
"""Mapped mpv discnav command, see man mpv(1)."""
self.command('discnav', command)
def write_watch_later_config(self):
"""Mapped mpv write_watch_later_config command, see man mpv(1)."""
self.command('write_watch_later_config')
def overlay_add(self, overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride):
"""Mapped mpv overlay_add command, see man mpv(1)."""
self.command('overlay_add', overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride)
def overlay_remove(self, overlay_id):
"""Mapped mpv overlay_remove command, see man mpv(1)."""
self.command('overlay_remove', overlay_id)
def script_message(self, *args):
"""Mapped mpv script_message command, see man mpv(1)."""
self.command('script_message', *args)
def script_message_to(self, target, *args):
"""Mapped mpv script_message_to command, see man mpv(1)."""
self.command('script_message_to', target, *args)
def observe_property(self, name, handler):
"""Register an observer on the named property. An observer is a function that is called with the new property
value every time the property's value is changed. The basic function signature is ``fun(property_name,
new_value)`` with new_value being the decoded property value as a python object. This function can be used as a
function decorator if no handler is given.
To unregister the observer, call either of ``mpv.unobserve_property(name, handler)``,
``mpv.unobserve_all_properties(handler)`` or the handler's ``unregister_mpv_properties`` attribute::
@player.observe_property('volume')
def my_handler(new_volume, *):
print("It's loud!", volume)
my_handler.unregister_mpv_properties()
"""
self._property_handlers[name].append(handler)
_mpv_observe_property(self._event_handle, hash(name)&0xffffffffffffffff, name.encode('utf-8'), MpvFormat.NODE)
def property_observer(self, name):
"""Function decorator to register a property observer. See ``MPV.observe_property`` for details."""
def wrapper(fun):
self.observe_property(name, fun)
fun.unobserve_mpv_properties = lambda: self.unobserve_property(name, fun)
return fun
return wrapper
def unobserve_all_properties(self, handler):
"""Unregister a property observer from *all* observed properties."""
for name in self._property_handlers:
self.unobserve_property(name, handler)
def register_message_handler(self, target, handler=None):
"""Register a mpv script message handler. This can be used to communicate with embedded lua scripts. Pass the
script message target name this handler should be listening to and the handler function.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
self._register_message_handler_internal(target, handler)
def _register_message_handler_internal(self, target, handler):
self._message_handlers[target] = handler
def unregister_message_handler(self, target_or_handler):
"""Unregister a mpv script message handler for the given script message target name.
You can also call the ``unregister_mpv_messages`` function attribute set on the handler function when it is
registered.
"""
if isinstance(target_or_handler, str):
del self._message_handlers[target_or_handler]
else:
for key, val in self._message_handlers.items():
if val == target_or_handler:
del self._message_handlers[key]
def message_handler(self, target):
"""Decorator to register a mpv script message handler.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
def register(handler):
self._register_message_handler_internal(target, handler)
handler.unregister_mpv_messages = lambda: self.unregister_message_handler(handler)
return handler
return register
def register_event_callback(self, callback):
"""Register a blanket event callback receiving all event types.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
self._event_callbacks.append(callback)
def unregister_event_callback(self, callback):
"""Unregiser an event callback."""
self._event_callbacks.remove(callback)
def event_callback(self, *event_types):
"""Function decorator to register a blanket event callback for the given event types. Event types can be given
as str (e.g. 'start-file'), integer or MpvEventID object.
WARNING: Due to the way this is filtering events, this decorator cannot be chained with itself.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
def register(callback):
types = [MpvEventID.from_str(t) if isinstance(t, str) else t for t in event_types] or MpvEventID.ANY
@wraps(callback)
def wrapper(event, *args, **kwargs):
if event['event_id'] in types:
callback(event, *args, **kwargs)
self._event_callbacks.append(wrapper)
wrapper.unregister_mpv_events = partial(self.unregister_event_callback, wrapper)
return wrapper
return register
@staticmethod
def _binding_name(callback_or_cmd):
return 'py_kb_{:016x}'.format(hash(callback_or_cmd)&0xffffffffffffffff)
def on_key_press(self, keydef, mode='force'):
"""Function decorator to register a simplified key binding. The callback is called whenever the key given is
*pressed*.
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.on_key_press('Q')
def binding():
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
The BIG FAT WARNING regarding untrusted keydefs from the key_binding method applies here as well.
"""
def register(fun):
@self.key_binding(keydef, mode)
@wraps(fun)
def wrapper(state='p-', name=None):
if state[0] in ('d', 'p'):
fun()
return wrapper
return register
def key_binding(self, keydef, mode='force'):
"""Function decorator to register a low-level key binding.
The callback function signature is ``fun(key_state, key_name)`` where ``key_state`` is either ``'U'`` for "key
up" or ``'D'`` for "key down".
The keydef format is: ``[Shift+][Ctrl+][Alt+][Meta+]<key>`` where ``<key>`` is either the literal character the
key produces (ASCII or Unicode character), or a symbolic name (as printed by ``mpv --input-keylist``).
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.key_binding('Q')
def binding(state, name):
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
BIG FAT WARNING: mpv's key binding mechanism is pretty powerful. This means, you essentially get arbitrary code
exectution through key bindings. This interface makes some limited effort to sanitize the keydef given in the
first parameter, but YOU SHOULD NOT RELY ON THIS IN FOR SECURITY. If your input comes from config files, this is
completely fine--but, if you are about to pass untrusted input into this parameter, better double-check whether
this is secure in your case.
"""
def register(fun):
fun.mpv_key_bindings = getattr(fun, 'mpv_key_bindings', []) + [keydef]
def unregister_all():
for keydef in fun.mpv_key_bindings:
self.unregister_key_binding(keydef)
fun.unregister_mpv_key_bindings = unregister_all
self.register_key_binding(keydef, fun, mode)
return fun
return register
def register_key_binding(self, keydef, callback_or_cmd, mode='force'):
"""Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python
callback function. See ``MPV.key_binding`` for details.
"""
if not re.match(r'(Shift+)?(Ctrl+)?(Alt+)?(Meta+)?(.|\w+)', keydef):
raise ValueError('Invalid keydef. Expected format: [Shift+][Ctrl+][Alt+][Meta+]<key>\n'
'<key> is either the literal character the key produces (ASCII or Unicode character), or a '
'symbolic name (as printed by --input-keylist')
binding_name = MPV._binding_name(keydef)
if callable(callback_or_cmd):
self._key_binding_handlers[binding_name] = callback_or_cmd
self.register_message_handler('key-binding', self._handle_key_binding_message)
self.command('define-section',
binding_name, '{} script-binding py_event_handler/{}'.format(keydef, binding_name), mode)
elif isinstance(callback_or_cmd, str):
self.command('define-section', binding_name, '{} {}'.format(keydef, callback_or_cmd), mode)
else:
raise TypeError('register_key_binding expects either an str with an mpv command or a python callable.')
self.command('enable-section', binding_name, 'allow-hide-cursor+allow-vo-dragging')
def _handle_key_binding_message(self, binding_name, key_state, key_name=None):
self._key_binding_handlers[binding_name](key_state, key_name)
def unregister_key_binding(self, keydef):
"""Unregister a key binding by keydef."""
binding_name = MPV._binding_name(keydef)
self.command('disable-section', binding_name)
self.command('define-section', binding_name, '')
if binding_name in self._key_binding_handlers:
del self._key_binding_handlers[binding_name]
if not self._key_binding_handlers:
self.unregister_message_handler('key-binding')
# Convenience functions
def play(self, filename):
"""Play a path or URL (requires ``ytdl`` option to be set)."""
self.loadfile(filename)
@property
def playlist_filenames(self):
"""Return all playlist item file names/URLs as a list of strs."""
return [element['filename'] for element in self.playlist]
def playlist_append(self, filename, **options):
"""Append a path or URL to the playlist. This does not start playing the file automatically. To do that, use
``MPV.loadfile(filename, 'append-play')``."""
self.loadfile(filename, 'append', **options)
# Property accessors
def _get_property(self, name, decoder=strict_decoder, fmt=MpvFormat.NODE):
out = create_string_buffer(sizeof(MpvNode))
try:
cval = _mpv_get_property(self.handle, name.encode('utf-8'), fmt, out)
if fmt is MpvFormat.OSD_STRING:
return cast(out, POINTER(c_char_p)).contents.value.decode('utf-8')
elif fmt is MpvFormat.NODE:
rv = cast(out, POINTER(MpvNode)).contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
else:
raise TypeError('_get_property only supports NODE and OSD_STRING formats.')
except PropertyUnavailableError as ex:
return None
def _set_property(self, name, value):
ename = name.encode('utf-8')
if isinstance(value, (list, set, dict)):
_1, _2, _3, pointer = _make_node_str_list(value)
_mpv_set_property(self.handle, ename, MpvFormat.NODE, pointer)
else:
_mpv_set_property_string(self.handle, ename, _mpv_coax_proptype(value))
def __getattr__(self, name):
return self._get_property(_py_to_mpv(name), lazy_decoder)
def __setattr__(self, name, value):
try:
if name != 'handle' and not name.startswith('_'):
self._set_property(_py_to_mpv(name), value)
else:
super().__setattr__(name, value)
except AttributeError:
super().__setattr__(name, value)
def __dir__(self):
return super().__dir__() + [ name.replace('-', '_') for name in self.property_list ]
@property
def properties(self):
return { name: self.option_info(name) for name in self.property_list }
# Dict-like option access
def __getitem__(self, name, file_local=False):
"""Get an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._get_property(prefix+name, lazy_decoder)
def __setitem__(self, name, value, file_local=False):
"""Set an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._set_property(prefix+name, value)
def __iter__(self):
"""Iterate over all option names."""
return iter(self.options)
def option_info(self, name):
"""Get information on the given option."""
try:
return self._get_property('option-info/'+name)
except AttributeError:
return None
|
jaseg/python-mpv | mpv.py | MPV.unobserve_all_properties | python | def unobserve_all_properties(self, handler):
for name in self._property_handlers:
self.unobserve_property(name, handler) | Unregister a property observer from *all* observed properties. | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L825-L828 | null | class MPV(object):
"""See man mpv(1) for the details of the implemented commands. All mpv properties can be accessed as
``my_mpv.some_property`` and all mpv options can be accessed as ``my_mpv['some-option']``.
By default, properties are returned as decoded ``str`` and an error is thrown if the value does not contain valid
utf-8. To get a decoded ``str`` if possibly but ``bytes`` instead of an error if not, use
``my_mpv.lazy.some_property``. To always get raw ``bytes``, use ``my_mpv.raw.some_property``. To access a
property's decoded OSD value, use ``my_mpv.osd.some_property``.
To get API information on an option, use ``my_mpv.option_info('option-name')``. To get API information on a
property, use ``my_mpv.properties['property-name']``. Take care to use mpv's dashed-names instead of the
underscore_names exposed on the python object.
To make your program not barf hard the first time its used on a weird file system **always** access properties
containing file names or file tags through ``MPV.raw``. """
def __init__(self, *extra_mpv_flags, log_handler=None, start_event_thread=True, loglevel=None, **extra_mpv_opts):
"""Create an MPV instance.
Extra arguments and extra keyword arguments will be passed to mpv as options.
"""
self.handle = _mpv_create()
self._event_thread = None
_mpv_set_option_string(self.handle, b'audio-display', b'no')
istr = lambda o: ('yes' if o else 'no') if type(o) is bool else str(o)
try:
for flag in extra_mpv_flags:
_mpv_set_option_string(self.handle, flag.encode('utf-8'), b'')
for k,v in extra_mpv_opts.items():
_mpv_set_option_string(self.handle, k.replace('_', '-').encode('utf-8'), istr(v).encode('utf-8'))
finally:
_mpv_initialize(self.handle)
self.osd = _OSDPropertyProxy(self)
self.file_local = _FileLocalProxy(self)
self.raw = _DecoderPropertyProxy(self, identity_decoder)
self.strict = _DecoderPropertyProxy(self, strict_decoder)
self.lazy = _DecoderPropertyProxy(self, lazy_decoder)
self._event_callbacks = []
self._property_handlers = collections.defaultdict(lambda: [])
self._message_handlers = {}
self._key_binding_handlers = {}
self._playback_cond = threading.Condition()
self._event_handle = _mpv_create_client(self.handle, b'py_event_handler')
self._loop = partial(_event_loop, self._event_handle, self._playback_cond, self._event_callbacks,
self._message_handlers, self._property_handlers, log_handler)
if loglevel is not None or log_handler is not None:
self.set_loglevel(loglevel or 'terminal-default')
if start_event_thread:
self._event_thread = threading.Thread(target=self._loop, name='MPVEventHandlerThread')
self._event_thread.setDaemon(True)
self._event_thread.start()
else:
self._event_thread = None
def wait_for_playback(self):
"""Waits until playback of the current title is paused or done."""
with self._playback_cond:
self._playback_cond.wait()
def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True):
"""Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for
properties such as ``idle_active`` indicating the player is done with regular playback and just idling around
"""
sema = threading.Semaphore(value=0)
def observer(name, val):
if cond(val):
sema.release()
self.observe_property(name, observer)
if not level_sensitive or not cond(getattr(self, name.replace('-', '_'))):
sema.acquire()
self.unobserve_property(name, observer)
def __del__(self):
if self.handle:
self.terminate()
def terminate(self):
"""Properly terminates this player instance. Preferably use this instead of relying on python's garbage
collector to cause this to be called from the object's destructor.
"""
self.handle, handle = None, self.handle
if threading.current_thread() is self._event_thread:
# Handle special case to allow event handle to be detached.
# This is necessary since otherwise the event thread would deadlock itself.
grim_reaper = threading.Thread(target=lambda: _mpv_terminate_destroy(handle))
grim_reaper.start()
else:
_mpv_terminate_destroy(handle)
if self._event_thread:
self._event_thread.join()
def set_loglevel(self, level):
"""Set MPV's log level. This adjusts which output will be sent to this object's log handlers. If you just want
mpv's regular terminal output, you don't need to adjust this but just need to pass a log handler to the MPV
constructur such as ``MPV(log_handler=print)``.
Valid log levels are "no", "fatal", "error", "warn", "info", "v" "debug" and "trace". For details see your mpv's
client.h header file.
"""
_mpv_request_log_messages(self._event_handle, level.encode('utf-8'))
def command(self, name, *args):
"""Execute a raw command."""
args = [name.encode('utf-8')] + [ (arg if type(arg) is bytes else str(arg).encode('utf-8'))
for arg in args if arg is not None ] + [None]
_mpv_command(self.handle, (c_char_p*len(args))(*args))
def node_command(self, name, *args, decoder=strict_decoder):
_1, _2, _3, pointer = _make_node_str_list([name, *args])
out = cast(create_string_buffer(sizeof(MpvNode)), POINTER(MpvNode))
ppointer = cast(pointer, POINTER(MpvNode))
_mpv_command_node(self.handle, ppointer, out)
rv = out.contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
def seek(self, amount, reference="relative", precision="default-precise"):
"""Mapped mpv seek command, see man mpv(1)."""
self.command('seek', amount, reference, precision)
def revert_seek(self):
"""Mapped mpv revert_seek command, see man mpv(1)."""
self.command('revert_seek');
def frame_step(self):
"""Mapped mpv frame_step command, see man mpv(1)."""
self.command('frame_step')
def frame_back_step(self):
"""Mapped mpv frame_back_step command, see man mpv(1)."""
self.command('frame_back_step')
def property_add(self, name, value=1):
"""Add the given value to the property's value. On overflow or underflow, clamp the property to the maximum. If
``value`` is omitted, assume ``1``.
"""
self.command('add', name, value)
def property_multiply(self, name, factor):
"""Multiply the value of a property with a numeric factor."""
self.command('multiply', name, factor)
def cycle(self, name, direction='up'):
"""Cycle the given property. ``up`` and ``down`` set the cycle direction. On overflow, set the property back to
the minimum, on underflow set it to the maximum. If ``up`` or ``down`` is omitted, assume ``up``.
"""
self.command('cycle', name, direction)
def screenshot(self, includes='subtitles', mode='single'):
"""Mapped mpv screenshot command, see man mpv(1)."""
self.command('screenshot', includes, mode)
def screenshot_to_file(self, filename, includes='subtitles'):
"""Mapped mpv screenshot_to_file command, see man mpv(1)."""
self.command('screenshot_to_file', filename.encode(fs_enc), includes)
def screenshot_raw(self, includes='subtitles'):
"""Mapped mpv screenshot_raw command, see man mpv(1). Returns a pillow Image object."""
from PIL import Image
res = self.node_command('screenshot-raw', includes)
if res['format'] != 'bgr0':
raise ValueError('Screenshot in unknown format "{}". Currently, only bgr0 is supported.'
.format(res['format']))
img = Image.frombytes('RGBA', (res['w'], res['h']), res['data'])
b,g,r,a = img.split()
return Image.merge('RGB', (r,g,b))
def playlist_next(self, mode='weak'):
"""Mapped mpv playlist_next command, see man mpv(1)."""
self.command('playlist_next', mode)
def playlist_prev(self, mode='weak'):
"""Mapped mpv playlist_prev command, see man mpv(1)."""
self.command('playlist_prev', mode)
@staticmethod
def _encode_options(options):
return ','.join('{}={}'.format(str(key), str(val)) for key, val in options.items())
def loadfile(self, filename, mode='replace', **options):
"""Mapped mpv loadfile command, see man mpv(1)."""
self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode_options(options))
def loadlist(self, playlist, mode='replace'):
"""Mapped mpv loadlist command, see man mpv(1)."""
self.command('loadlist', playlist.encode(fs_enc), mode)
def playlist_clear(self):
"""Mapped mpv playlist_clear command, see man mpv(1)."""
self.command('playlist_clear')
def playlist_remove(self, index='current'):
"""Mapped mpv playlist_remove command, see man mpv(1)."""
self.command('playlist_remove', index)
def playlist_move(self, index1, index2):
"""Mapped mpv playlist_move command, see man mpv(1)."""
self.command('playlist_move', index1, index2)
def run(self, command, *args):
"""Mapped mpv run command, see man mpv(1)."""
self.command('run', command, *args)
def quit(self, code=None):
"""Mapped mpv quit command, see man mpv(1)."""
self.command('quit', code)
def quit_watch_later(self, code=None):
"""Mapped mpv quit_watch_later command, see man mpv(1)."""
self.command('quit_watch_later', code)
def sub_add(self, filename):
"""Mapped mpv sub_add command, see man mpv(1)."""
self.command('sub_add', filename.encode(fs_enc))
def sub_remove(self, sub_id=None):
"""Mapped mpv sub_remove command, see man mpv(1)."""
self.command('sub_remove', sub_id)
def sub_reload(self, sub_id=None):
"""Mapped mpv sub_reload command, see man mpv(1)."""
self.command('sub_reload', sub_id)
def sub_step(self, skip):
"""Mapped mpv sub_step command, see man mpv(1)."""
self.command('sub_step', skip)
def sub_seek(self, skip):
"""Mapped mpv sub_seek command, see man mpv(1)."""
self.command('sub_seek', skip)
def toggle_osd(self):
"""Mapped mpv osd command, see man mpv(1)."""
self.command('osd')
def show_text(self, string, duration='-1', level=None):
"""Mapped mpv show_text command, see man mpv(1)."""
self.command('show_text', string, duration, level)
def show_progress(self):
"""Mapped mpv show_progress command, see man mpv(1)."""
self.command('show_progress')
def discnav(self, command):
"""Mapped mpv discnav command, see man mpv(1)."""
self.command('discnav', command)
def write_watch_later_config(self):
"""Mapped mpv write_watch_later_config command, see man mpv(1)."""
self.command('write_watch_later_config')
def overlay_add(self, overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride):
"""Mapped mpv overlay_add command, see man mpv(1)."""
self.command('overlay_add', overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride)
def overlay_remove(self, overlay_id):
"""Mapped mpv overlay_remove command, see man mpv(1)."""
self.command('overlay_remove', overlay_id)
def script_message(self, *args):
"""Mapped mpv script_message command, see man mpv(1)."""
self.command('script_message', *args)
def script_message_to(self, target, *args):
"""Mapped mpv script_message_to command, see man mpv(1)."""
self.command('script_message_to', target, *args)
def observe_property(self, name, handler):
"""Register an observer on the named property. An observer is a function that is called with the new property
value every time the property's value is changed. The basic function signature is ``fun(property_name,
new_value)`` with new_value being the decoded property value as a python object. This function can be used as a
function decorator if no handler is given.
To unregister the observer, call either of ``mpv.unobserve_property(name, handler)``,
``mpv.unobserve_all_properties(handler)`` or the handler's ``unregister_mpv_properties`` attribute::
@player.observe_property('volume')
def my_handler(new_volume, *):
print("It's loud!", volume)
my_handler.unregister_mpv_properties()
"""
self._property_handlers[name].append(handler)
_mpv_observe_property(self._event_handle, hash(name)&0xffffffffffffffff, name.encode('utf-8'), MpvFormat.NODE)
def property_observer(self, name):
"""Function decorator to register a property observer. See ``MPV.observe_property`` for details."""
def wrapper(fun):
self.observe_property(name, fun)
fun.unobserve_mpv_properties = lambda: self.unobserve_property(name, fun)
return fun
return wrapper
def unobserve_property(self, name, handler):
"""Unregister a property observer. This requires both the observed property's name and the handler function that
was originally registered as one handler could be registered for several properties. To unregister a handler
from *all* observed properties see ``unobserve_all_properties``.
"""
self._property_handlers[name].remove(handler)
if not self._property_handlers[name]:
_mpv_unobserve_property(self._event_handle, hash(name)&0xffffffffffffffff)
def register_message_handler(self, target, handler=None):
"""Register a mpv script message handler. This can be used to communicate with embedded lua scripts. Pass the
script message target name this handler should be listening to and the handler function.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
self._register_message_handler_internal(target, handler)
def _register_message_handler_internal(self, target, handler):
self._message_handlers[target] = handler
def unregister_message_handler(self, target_or_handler):
"""Unregister a mpv script message handler for the given script message target name.
You can also call the ``unregister_mpv_messages`` function attribute set on the handler function when it is
registered.
"""
if isinstance(target_or_handler, str):
del self._message_handlers[target_or_handler]
else:
for key, val in self._message_handlers.items():
if val == target_or_handler:
del self._message_handlers[key]
def message_handler(self, target):
"""Decorator to register a mpv script message handler.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
def register(handler):
self._register_message_handler_internal(target, handler)
handler.unregister_mpv_messages = lambda: self.unregister_message_handler(handler)
return handler
return register
def register_event_callback(self, callback):
"""Register a blanket event callback receiving all event types.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
self._event_callbacks.append(callback)
def unregister_event_callback(self, callback):
"""Unregiser an event callback."""
self._event_callbacks.remove(callback)
def event_callback(self, *event_types):
"""Function decorator to register a blanket event callback for the given event types. Event types can be given
as str (e.g. 'start-file'), integer or MpvEventID object.
WARNING: Due to the way this is filtering events, this decorator cannot be chained with itself.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
def register(callback):
types = [MpvEventID.from_str(t) if isinstance(t, str) else t for t in event_types] or MpvEventID.ANY
@wraps(callback)
def wrapper(event, *args, **kwargs):
if event['event_id'] in types:
callback(event, *args, **kwargs)
self._event_callbacks.append(wrapper)
wrapper.unregister_mpv_events = partial(self.unregister_event_callback, wrapper)
return wrapper
return register
@staticmethod
def _binding_name(callback_or_cmd):
return 'py_kb_{:016x}'.format(hash(callback_or_cmd)&0xffffffffffffffff)
def on_key_press(self, keydef, mode='force'):
"""Function decorator to register a simplified key binding. The callback is called whenever the key given is
*pressed*.
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.on_key_press('Q')
def binding():
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
The BIG FAT WARNING regarding untrusted keydefs from the key_binding method applies here as well.
"""
def register(fun):
@self.key_binding(keydef, mode)
@wraps(fun)
def wrapper(state='p-', name=None):
if state[0] in ('d', 'p'):
fun()
return wrapper
return register
def key_binding(self, keydef, mode='force'):
"""Function decorator to register a low-level key binding.
The callback function signature is ``fun(key_state, key_name)`` where ``key_state`` is either ``'U'`` for "key
up" or ``'D'`` for "key down".
The keydef format is: ``[Shift+][Ctrl+][Alt+][Meta+]<key>`` where ``<key>`` is either the literal character the
key produces (ASCII or Unicode character), or a symbolic name (as printed by ``mpv --input-keylist``).
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.key_binding('Q')
def binding(state, name):
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
BIG FAT WARNING: mpv's key binding mechanism is pretty powerful. This means, you essentially get arbitrary code
exectution through key bindings. This interface makes some limited effort to sanitize the keydef given in the
first parameter, but YOU SHOULD NOT RELY ON THIS IN FOR SECURITY. If your input comes from config files, this is
completely fine--but, if you are about to pass untrusted input into this parameter, better double-check whether
this is secure in your case.
"""
def register(fun):
fun.mpv_key_bindings = getattr(fun, 'mpv_key_bindings', []) + [keydef]
def unregister_all():
for keydef in fun.mpv_key_bindings:
self.unregister_key_binding(keydef)
fun.unregister_mpv_key_bindings = unregister_all
self.register_key_binding(keydef, fun, mode)
return fun
return register
def register_key_binding(self, keydef, callback_or_cmd, mode='force'):
"""Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python
callback function. See ``MPV.key_binding`` for details.
"""
if not re.match(r'(Shift+)?(Ctrl+)?(Alt+)?(Meta+)?(.|\w+)', keydef):
raise ValueError('Invalid keydef. Expected format: [Shift+][Ctrl+][Alt+][Meta+]<key>\n'
'<key> is either the literal character the key produces (ASCII or Unicode character), or a '
'symbolic name (as printed by --input-keylist')
binding_name = MPV._binding_name(keydef)
if callable(callback_or_cmd):
self._key_binding_handlers[binding_name] = callback_or_cmd
self.register_message_handler('key-binding', self._handle_key_binding_message)
self.command('define-section',
binding_name, '{} script-binding py_event_handler/{}'.format(keydef, binding_name), mode)
elif isinstance(callback_or_cmd, str):
self.command('define-section', binding_name, '{} {}'.format(keydef, callback_or_cmd), mode)
else:
raise TypeError('register_key_binding expects either an str with an mpv command or a python callable.')
self.command('enable-section', binding_name, 'allow-hide-cursor+allow-vo-dragging')
def _handle_key_binding_message(self, binding_name, key_state, key_name=None):
self._key_binding_handlers[binding_name](key_state, key_name)
def unregister_key_binding(self, keydef):
"""Unregister a key binding by keydef."""
binding_name = MPV._binding_name(keydef)
self.command('disable-section', binding_name)
self.command('define-section', binding_name, '')
if binding_name in self._key_binding_handlers:
del self._key_binding_handlers[binding_name]
if not self._key_binding_handlers:
self.unregister_message_handler('key-binding')
# Convenience functions
def play(self, filename):
"""Play a path or URL (requires ``ytdl`` option to be set)."""
self.loadfile(filename)
@property
def playlist_filenames(self):
"""Return all playlist item file names/URLs as a list of strs."""
return [element['filename'] for element in self.playlist]
def playlist_append(self, filename, **options):
"""Append a path or URL to the playlist. This does not start playing the file automatically. To do that, use
``MPV.loadfile(filename, 'append-play')``."""
self.loadfile(filename, 'append', **options)
# Property accessors
def _get_property(self, name, decoder=strict_decoder, fmt=MpvFormat.NODE):
out = create_string_buffer(sizeof(MpvNode))
try:
cval = _mpv_get_property(self.handle, name.encode('utf-8'), fmt, out)
if fmt is MpvFormat.OSD_STRING:
return cast(out, POINTER(c_char_p)).contents.value.decode('utf-8')
elif fmt is MpvFormat.NODE:
rv = cast(out, POINTER(MpvNode)).contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
else:
raise TypeError('_get_property only supports NODE and OSD_STRING formats.')
except PropertyUnavailableError as ex:
return None
def _set_property(self, name, value):
ename = name.encode('utf-8')
if isinstance(value, (list, set, dict)):
_1, _2, _3, pointer = _make_node_str_list(value)
_mpv_set_property(self.handle, ename, MpvFormat.NODE, pointer)
else:
_mpv_set_property_string(self.handle, ename, _mpv_coax_proptype(value))
def __getattr__(self, name):
return self._get_property(_py_to_mpv(name), lazy_decoder)
def __setattr__(self, name, value):
try:
if name != 'handle' and not name.startswith('_'):
self._set_property(_py_to_mpv(name), value)
else:
super().__setattr__(name, value)
except AttributeError:
super().__setattr__(name, value)
def __dir__(self):
return super().__dir__() + [ name.replace('-', '_') for name in self.property_list ]
@property
def properties(self):
return { name: self.option_info(name) for name in self.property_list }
# Dict-like option access
def __getitem__(self, name, file_local=False):
"""Get an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._get_property(prefix+name, lazy_decoder)
def __setitem__(self, name, value, file_local=False):
"""Set an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._set_property(prefix+name, value)
def __iter__(self):
"""Iterate over all option names."""
return iter(self.options)
def option_info(self, name):
"""Get information on the given option."""
try:
return self._get_property('option-info/'+name)
except AttributeError:
return None
|
jaseg/python-mpv | mpv.py | MPV.unregister_message_handler | python | def unregister_message_handler(self, target_or_handler):
if isinstance(target_or_handler, str):
del self._message_handlers[target_or_handler]
else:
for key, val in self._message_handlers.items():
if val == target_or_handler:
del self._message_handlers[key] | Unregister a mpv script message handler for the given script message target name.
You can also call the ``unregister_mpv_messages`` function attribute set on the handler function when it is
registered. | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L850-L861 | null | class MPV(object):
"""See man mpv(1) for the details of the implemented commands. All mpv properties can be accessed as
``my_mpv.some_property`` and all mpv options can be accessed as ``my_mpv['some-option']``.
By default, properties are returned as decoded ``str`` and an error is thrown if the value does not contain valid
utf-8. To get a decoded ``str`` if possibly but ``bytes`` instead of an error if not, use
``my_mpv.lazy.some_property``. To always get raw ``bytes``, use ``my_mpv.raw.some_property``. To access a
property's decoded OSD value, use ``my_mpv.osd.some_property``.
To get API information on an option, use ``my_mpv.option_info('option-name')``. To get API information on a
property, use ``my_mpv.properties['property-name']``. Take care to use mpv's dashed-names instead of the
underscore_names exposed on the python object.
To make your program not barf hard the first time its used on a weird file system **always** access properties
containing file names or file tags through ``MPV.raw``. """
def __init__(self, *extra_mpv_flags, log_handler=None, start_event_thread=True, loglevel=None, **extra_mpv_opts):
"""Create an MPV instance.
Extra arguments and extra keyword arguments will be passed to mpv as options.
"""
self.handle = _mpv_create()
self._event_thread = None
_mpv_set_option_string(self.handle, b'audio-display', b'no')
istr = lambda o: ('yes' if o else 'no') if type(o) is bool else str(o)
try:
for flag in extra_mpv_flags:
_mpv_set_option_string(self.handle, flag.encode('utf-8'), b'')
for k,v in extra_mpv_opts.items():
_mpv_set_option_string(self.handle, k.replace('_', '-').encode('utf-8'), istr(v).encode('utf-8'))
finally:
_mpv_initialize(self.handle)
self.osd = _OSDPropertyProxy(self)
self.file_local = _FileLocalProxy(self)
self.raw = _DecoderPropertyProxy(self, identity_decoder)
self.strict = _DecoderPropertyProxy(self, strict_decoder)
self.lazy = _DecoderPropertyProxy(self, lazy_decoder)
self._event_callbacks = []
self._property_handlers = collections.defaultdict(lambda: [])
self._message_handlers = {}
self._key_binding_handlers = {}
self._playback_cond = threading.Condition()
self._event_handle = _mpv_create_client(self.handle, b'py_event_handler')
self._loop = partial(_event_loop, self._event_handle, self._playback_cond, self._event_callbacks,
self._message_handlers, self._property_handlers, log_handler)
if loglevel is not None or log_handler is not None:
self.set_loglevel(loglevel or 'terminal-default')
if start_event_thread:
self._event_thread = threading.Thread(target=self._loop, name='MPVEventHandlerThread')
self._event_thread.setDaemon(True)
self._event_thread.start()
else:
self._event_thread = None
def wait_for_playback(self):
"""Waits until playback of the current title is paused or done."""
with self._playback_cond:
self._playback_cond.wait()
def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True):
"""Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for
properties such as ``idle_active`` indicating the player is done with regular playback and just idling around
"""
sema = threading.Semaphore(value=0)
def observer(name, val):
if cond(val):
sema.release()
self.observe_property(name, observer)
if not level_sensitive or not cond(getattr(self, name.replace('-', '_'))):
sema.acquire()
self.unobserve_property(name, observer)
def __del__(self):
if self.handle:
self.terminate()
def terminate(self):
"""Properly terminates this player instance. Preferably use this instead of relying on python's garbage
collector to cause this to be called from the object's destructor.
"""
self.handle, handle = None, self.handle
if threading.current_thread() is self._event_thread:
# Handle special case to allow event handle to be detached.
# This is necessary since otherwise the event thread would deadlock itself.
grim_reaper = threading.Thread(target=lambda: _mpv_terminate_destroy(handle))
grim_reaper.start()
else:
_mpv_terminate_destroy(handle)
if self._event_thread:
self._event_thread.join()
def set_loglevel(self, level):
"""Set MPV's log level. This adjusts which output will be sent to this object's log handlers. If you just want
mpv's regular terminal output, you don't need to adjust this but just need to pass a log handler to the MPV
constructur such as ``MPV(log_handler=print)``.
Valid log levels are "no", "fatal", "error", "warn", "info", "v" "debug" and "trace". For details see your mpv's
client.h header file.
"""
_mpv_request_log_messages(self._event_handle, level.encode('utf-8'))
def command(self, name, *args):
"""Execute a raw command."""
args = [name.encode('utf-8')] + [ (arg if type(arg) is bytes else str(arg).encode('utf-8'))
for arg in args if arg is not None ] + [None]
_mpv_command(self.handle, (c_char_p*len(args))(*args))
def node_command(self, name, *args, decoder=strict_decoder):
_1, _2, _3, pointer = _make_node_str_list([name, *args])
out = cast(create_string_buffer(sizeof(MpvNode)), POINTER(MpvNode))
ppointer = cast(pointer, POINTER(MpvNode))
_mpv_command_node(self.handle, ppointer, out)
rv = out.contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
def seek(self, amount, reference="relative", precision="default-precise"):
"""Mapped mpv seek command, see man mpv(1)."""
self.command('seek', amount, reference, precision)
def revert_seek(self):
"""Mapped mpv revert_seek command, see man mpv(1)."""
self.command('revert_seek');
def frame_step(self):
"""Mapped mpv frame_step command, see man mpv(1)."""
self.command('frame_step')
def frame_back_step(self):
"""Mapped mpv frame_back_step command, see man mpv(1)."""
self.command('frame_back_step')
def property_add(self, name, value=1):
"""Add the given value to the property's value. On overflow or underflow, clamp the property to the maximum. If
``value`` is omitted, assume ``1``.
"""
self.command('add', name, value)
def property_multiply(self, name, factor):
"""Multiply the value of a property with a numeric factor."""
self.command('multiply', name, factor)
def cycle(self, name, direction='up'):
"""Cycle the given property. ``up`` and ``down`` set the cycle direction. On overflow, set the property back to
the minimum, on underflow set it to the maximum. If ``up`` or ``down`` is omitted, assume ``up``.
"""
self.command('cycle', name, direction)
def screenshot(self, includes='subtitles', mode='single'):
"""Mapped mpv screenshot command, see man mpv(1)."""
self.command('screenshot', includes, mode)
def screenshot_to_file(self, filename, includes='subtitles'):
"""Mapped mpv screenshot_to_file command, see man mpv(1)."""
self.command('screenshot_to_file', filename.encode(fs_enc), includes)
def screenshot_raw(self, includes='subtitles'):
"""Mapped mpv screenshot_raw command, see man mpv(1). Returns a pillow Image object."""
from PIL import Image
res = self.node_command('screenshot-raw', includes)
if res['format'] != 'bgr0':
raise ValueError('Screenshot in unknown format "{}". Currently, only bgr0 is supported.'
.format(res['format']))
img = Image.frombytes('RGBA', (res['w'], res['h']), res['data'])
b,g,r,a = img.split()
return Image.merge('RGB', (r,g,b))
def playlist_next(self, mode='weak'):
"""Mapped mpv playlist_next command, see man mpv(1)."""
self.command('playlist_next', mode)
def playlist_prev(self, mode='weak'):
"""Mapped mpv playlist_prev command, see man mpv(1)."""
self.command('playlist_prev', mode)
@staticmethod
def _encode_options(options):
return ','.join('{}={}'.format(str(key), str(val)) for key, val in options.items())
def loadfile(self, filename, mode='replace', **options):
"""Mapped mpv loadfile command, see man mpv(1)."""
self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode_options(options))
def loadlist(self, playlist, mode='replace'):
"""Mapped mpv loadlist command, see man mpv(1)."""
self.command('loadlist', playlist.encode(fs_enc), mode)
def playlist_clear(self):
"""Mapped mpv playlist_clear command, see man mpv(1)."""
self.command('playlist_clear')
def playlist_remove(self, index='current'):
"""Mapped mpv playlist_remove command, see man mpv(1)."""
self.command('playlist_remove', index)
def playlist_move(self, index1, index2):
"""Mapped mpv playlist_move command, see man mpv(1)."""
self.command('playlist_move', index1, index2)
def run(self, command, *args):
"""Mapped mpv run command, see man mpv(1)."""
self.command('run', command, *args)
def quit(self, code=None):
"""Mapped mpv quit command, see man mpv(1)."""
self.command('quit', code)
def quit_watch_later(self, code=None):
"""Mapped mpv quit_watch_later command, see man mpv(1)."""
self.command('quit_watch_later', code)
def sub_add(self, filename):
"""Mapped mpv sub_add command, see man mpv(1)."""
self.command('sub_add', filename.encode(fs_enc))
def sub_remove(self, sub_id=None):
"""Mapped mpv sub_remove command, see man mpv(1)."""
self.command('sub_remove', sub_id)
def sub_reload(self, sub_id=None):
"""Mapped mpv sub_reload command, see man mpv(1)."""
self.command('sub_reload', sub_id)
def sub_step(self, skip):
"""Mapped mpv sub_step command, see man mpv(1)."""
self.command('sub_step', skip)
def sub_seek(self, skip):
"""Mapped mpv sub_seek command, see man mpv(1)."""
self.command('sub_seek', skip)
def toggle_osd(self):
"""Mapped mpv osd command, see man mpv(1)."""
self.command('osd')
def show_text(self, string, duration='-1', level=None):
"""Mapped mpv show_text command, see man mpv(1)."""
self.command('show_text', string, duration, level)
def show_progress(self):
"""Mapped mpv show_progress command, see man mpv(1)."""
self.command('show_progress')
def discnav(self, command):
"""Mapped mpv discnav command, see man mpv(1)."""
self.command('discnav', command)
def write_watch_later_config(self):
"""Mapped mpv write_watch_later_config command, see man mpv(1)."""
self.command('write_watch_later_config')
def overlay_add(self, overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride):
"""Mapped mpv overlay_add command, see man mpv(1)."""
self.command('overlay_add', overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride)
def overlay_remove(self, overlay_id):
"""Mapped mpv overlay_remove command, see man mpv(1)."""
self.command('overlay_remove', overlay_id)
def script_message(self, *args):
"""Mapped mpv script_message command, see man mpv(1)."""
self.command('script_message', *args)
def script_message_to(self, target, *args):
"""Mapped mpv script_message_to command, see man mpv(1)."""
self.command('script_message_to', target, *args)
def observe_property(self, name, handler):
"""Register an observer on the named property. An observer is a function that is called with the new property
value every time the property's value is changed. The basic function signature is ``fun(property_name,
new_value)`` with new_value being the decoded property value as a python object. This function can be used as a
function decorator if no handler is given.
To unregister the observer, call either of ``mpv.unobserve_property(name, handler)``,
``mpv.unobserve_all_properties(handler)`` or the handler's ``unregister_mpv_properties`` attribute::
@player.observe_property('volume')
def my_handler(new_volume, *):
print("It's loud!", volume)
my_handler.unregister_mpv_properties()
"""
self._property_handlers[name].append(handler)
_mpv_observe_property(self._event_handle, hash(name)&0xffffffffffffffff, name.encode('utf-8'), MpvFormat.NODE)
def property_observer(self, name):
"""Function decorator to register a property observer. See ``MPV.observe_property`` for details."""
def wrapper(fun):
self.observe_property(name, fun)
fun.unobserve_mpv_properties = lambda: self.unobserve_property(name, fun)
return fun
return wrapper
def unobserve_property(self, name, handler):
"""Unregister a property observer. This requires both the observed property's name and the handler function that
was originally registered as one handler could be registered for several properties. To unregister a handler
from *all* observed properties see ``unobserve_all_properties``.
"""
self._property_handlers[name].remove(handler)
if not self._property_handlers[name]:
_mpv_unobserve_property(self._event_handle, hash(name)&0xffffffffffffffff)
def unobserve_all_properties(self, handler):
"""Unregister a property observer from *all* observed properties."""
for name in self._property_handlers:
self.unobserve_property(name, handler)
def register_message_handler(self, target, handler=None):
"""Register a mpv script message handler. This can be used to communicate with embedded lua scripts. Pass the
script message target name this handler should be listening to and the handler function.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
self._register_message_handler_internal(target, handler)
def _register_message_handler_internal(self, target, handler):
self._message_handlers[target] = handler
def message_handler(self, target):
"""Decorator to register a mpv script message handler.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
def register(handler):
self._register_message_handler_internal(target, handler)
handler.unregister_mpv_messages = lambda: self.unregister_message_handler(handler)
return handler
return register
def register_event_callback(self, callback):
"""Register a blanket event callback receiving all event types.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
self._event_callbacks.append(callback)
def unregister_event_callback(self, callback):
"""Unregiser an event callback."""
self._event_callbacks.remove(callback)
def event_callback(self, *event_types):
"""Function decorator to register a blanket event callback for the given event types. Event types can be given
as str (e.g. 'start-file'), integer or MpvEventID object.
WARNING: Due to the way this is filtering events, this decorator cannot be chained with itself.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
def register(callback):
types = [MpvEventID.from_str(t) if isinstance(t, str) else t for t in event_types] or MpvEventID.ANY
@wraps(callback)
def wrapper(event, *args, **kwargs):
if event['event_id'] in types:
callback(event, *args, **kwargs)
self._event_callbacks.append(wrapper)
wrapper.unregister_mpv_events = partial(self.unregister_event_callback, wrapper)
return wrapper
return register
@staticmethod
def _binding_name(callback_or_cmd):
return 'py_kb_{:016x}'.format(hash(callback_or_cmd)&0xffffffffffffffff)
def on_key_press(self, keydef, mode='force'):
"""Function decorator to register a simplified key binding. The callback is called whenever the key given is
*pressed*.
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.on_key_press('Q')
def binding():
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
The BIG FAT WARNING regarding untrusted keydefs from the key_binding method applies here as well.
"""
def register(fun):
@self.key_binding(keydef, mode)
@wraps(fun)
def wrapper(state='p-', name=None):
if state[0] in ('d', 'p'):
fun()
return wrapper
return register
def key_binding(self, keydef, mode='force'):
"""Function decorator to register a low-level key binding.
The callback function signature is ``fun(key_state, key_name)`` where ``key_state`` is either ``'U'`` for "key
up" or ``'D'`` for "key down".
The keydef format is: ``[Shift+][Ctrl+][Alt+][Meta+]<key>`` where ``<key>`` is either the literal character the
key produces (ASCII or Unicode character), or a symbolic name (as printed by ``mpv --input-keylist``).
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.key_binding('Q')
def binding(state, name):
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
BIG FAT WARNING: mpv's key binding mechanism is pretty powerful. This means, you essentially get arbitrary code
exectution through key bindings. This interface makes some limited effort to sanitize the keydef given in the
first parameter, but YOU SHOULD NOT RELY ON THIS IN FOR SECURITY. If your input comes from config files, this is
completely fine--but, if you are about to pass untrusted input into this parameter, better double-check whether
this is secure in your case.
"""
def register(fun):
fun.mpv_key_bindings = getattr(fun, 'mpv_key_bindings', []) + [keydef]
def unregister_all():
for keydef in fun.mpv_key_bindings:
self.unregister_key_binding(keydef)
fun.unregister_mpv_key_bindings = unregister_all
self.register_key_binding(keydef, fun, mode)
return fun
return register
def register_key_binding(self, keydef, callback_or_cmd, mode='force'):
"""Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python
callback function. See ``MPV.key_binding`` for details.
"""
if not re.match(r'(Shift+)?(Ctrl+)?(Alt+)?(Meta+)?(.|\w+)', keydef):
raise ValueError('Invalid keydef. Expected format: [Shift+][Ctrl+][Alt+][Meta+]<key>\n'
'<key> is either the literal character the key produces (ASCII or Unicode character), or a '
'symbolic name (as printed by --input-keylist')
binding_name = MPV._binding_name(keydef)
if callable(callback_or_cmd):
self._key_binding_handlers[binding_name] = callback_or_cmd
self.register_message_handler('key-binding', self._handle_key_binding_message)
self.command('define-section',
binding_name, '{} script-binding py_event_handler/{}'.format(keydef, binding_name), mode)
elif isinstance(callback_or_cmd, str):
self.command('define-section', binding_name, '{} {}'.format(keydef, callback_or_cmd), mode)
else:
raise TypeError('register_key_binding expects either an str with an mpv command or a python callable.')
self.command('enable-section', binding_name, 'allow-hide-cursor+allow-vo-dragging')
def _handle_key_binding_message(self, binding_name, key_state, key_name=None):
self._key_binding_handlers[binding_name](key_state, key_name)
def unregister_key_binding(self, keydef):
"""Unregister a key binding by keydef."""
binding_name = MPV._binding_name(keydef)
self.command('disable-section', binding_name)
self.command('define-section', binding_name, '')
if binding_name in self._key_binding_handlers:
del self._key_binding_handlers[binding_name]
if not self._key_binding_handlers:
self.unregister_message_handler('key-binding')
# Convenience functions
def play(self, filename):
"""Play a path or URL (requires ``ytdl`` option to be set)."""
self.loadfile(filename)
@property
def playlist_filenames(self):
"""Return all playlist item file names/URLs as a list of strs."""
return [element['filename'] for element in self.playlist]
def playlist_append(self, filename, **options):
"""Append a path or URL to the playlist. This does not start playing the file automatically. To do that, use
``MPV.loadfile(filename, 'append-play')``."""
self.loadfile(filename, 'append', **options)
# Property accessors
def _get_property(self, name, decoder=strict_decoder, fmt=MpvFormat.NODE):
out = create_string_buffer(sizeof(MpvNode))
try:
cval = _mpv_get_property(self.handle, name.encode('utf-8'), fmt, out)
if fmt is MpvFormat.OSD_STRING:
return cast(out, POINTER(c_char_p)).contents.value.decode('utf-8')
elif fmt is MpvFormat.NODE:
rv = cast(out, POINTER(MpvNode)).contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
else:
raise TypeError('_get_property only supports NODE and OSD_STRING formats.')
except PropertyUnavailableError as ex:
return None
def _set_property(self, name, value):
ename = name.encode('utf-8')
if isinstance(value, (list, set, dict)):
_1, _2, _3, pointer = _make_node_str_list(value)
_mpv_set_property(self.handle, ename, MpvFormat.NODE, pointer)
else:
_mpv_set_property_string(self.handle, ename, _mpv_coax_proptype(value))
def __getattr__(self, name):
return self._get_property(_py_to_mpv(name), lazy_decoder)
def __setattr__(self, name, value):
try:
if name != 'handle' and not name.startswith('_'):
self._set_property(_py_to_mpv(name), value)
else:
super().__setattr__(name, value)
except AttributeError:
super().__setattr__(name, value)
def __dir__(self):
return super().__dir__() + [ name.replace('-', '_') for name in self.property_list ]
@property
def properties(self):
return { name: self.option_info(name) for name in self.property_list }
# Dict-like option access
def __getitem__(self, name, file_local=False):
"""Get an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._get_property(prefix+name, lazy_decoder)
def __setitem__(self, name, value, file_local=False):
"""Set an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._set_property(prefix+name, value)
def __iter__(self):
"""Iterate over all option names."""
return iter(self.options)
def option_info(self, name):
"""Get information on the given option."""
try:
return self._get_property('option-info/'+name)
except AttributeError:
return None
|
jaseg/python-mpv | mpv.py | MPV.message_handler | python | def message_handler(self, target):
def register(handler):
self._register_message_handler_internal(target, handler)
handler.unregister_mpv_messages = lambda: self.unregister_message_handler(handler)
return handler
return register | Decorator to register a mpv script message handler.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages() | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L863-L881 | null | class MPV(object):
"""See man mpv(1) for the details of the implemented commands. All mpv properties can be accessed as
``my_mpv.some_property`` and all mpv options can be accessed as ``my_mpv['some-option']``.
By default, properties are returned as decoded ``str`` and an error is thrown if the value does not contain valid
utf-8. To get a decoded ``str`` if possibly but ``bytes`` instead of an error if not, use
``my_mpv.lazy.some_property``. To always get raw ``bytes``, use ``my_mpv.raw.some_property``. To access a
property's decoded OSD value, use ``my_mpv.osd.some_property``.
To get API information on an option, use ``my_mpv.option_info('option-name')``. To get API information on a
property, use ``my_mpv.properties['property-name']``. Take care to use mpv's dashed-names instead of the
underscore_names exposed on the python object.
To make your program not barf hard the first time its used on a weird file system **always** access properties
containing file names or file tags through ``MPV.raw``. """
def __init__(self, *extra_mpv_flags, log_handler=None, start_event_thread=True, loglevel=None, **extra_mpv_opts):
"""Create an MPV instance.
Extra arguments and extra keyword arguments will be passed to mpv as options.
"""
self.handle = _mpv_create()
self._event_thread = None
_mpv_set_option_string(self.handle, b'audio-display', b'no')
istr = lambda o: ('yes' if o else 'no') if type(o) is bool else str(o)
try:
for flag in extra_mpv_flags:
_mpv_set_option_string(self.handle, flag.encode('utf-8'), b'')
for k,v in extra_mpv_opts.items():
_mpv_set_option_string(self.handle, k.replace('_', '-').encode('utf-8'), istr(v).encode('utf-8'))
finally:
_mpv_initialize(self.handle)
self.osd = _OSDPropertyProxy(self)
self.file_local = _FileLocalProxy(self)
self.raw = _DecoderPropertyProxy(self, identity_decoder)
self.strict = _DecoderPropertyProxy(self, strict_decoder)
self.lazy = _DecoderPropertyProxy(self, lazy_decoder)
self._event_callbacks = []
self._property_handlers = collections.defaultdict(lambda: [])
self._message_handlers = {}
self._key_binding_handlers = {}
self._playback_cond = threading.Condition()
self._event_handle = _mpv_create_client(self.handle, b'py_event_handler')
self._loop = partial(_event_loop, self._event_handle, self._playback_cond, self._event_callbacks,
self._message_handlers, self._property_handlers, log_handler)
if loglevel is not None or log_handler is not None:
self.set_loglevel(loglevel or 'terminal-default')
if start_event_thread:
self._event_thread = threading.Thread(target=self._loop, name='MPVEventHandlerThread')
self._event_thread.setDaemon(True)
self._event_thread.start()
else:
self._event_thread = None
def wait_for_playback(self):
"""Waits until playback of the current title is paused or done."""
with self._playback_cond:
self._playback_cond.wait()
def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True):
"""Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for
properties such as ``idle_active`` indicating the player is done with regular playback and just idling around
"""
sema = threading.Semaphore(value=0)
def observer(name, val):
if cond(val):
sema.release()
self.observe_property(name, observer)
if not level_sensitive or not cond(getattr(self, name.replace('-', '_'))):
sema.acquire()
self.unobserve_property(name, observer)
def __del__(self):
if self.handle:
self.terminate()
def terminate(self):
"""Properly terminates this player instance. Preferably use this instead of relying on python's garbage
collector to cause this to be called from the object's destructor.
"""
self.handle, handle = None, self.handle
if threading.current_thread() is self._event_thread:
# Handle special case to allow event handle to be detached.
# This is necessary since otherwise the event thread would deadlock itself.
grim_reaper = threading.Thread(target=lambda: _mpv_terminate_destroy(handle))
grim_reaper.start()
else:
_mpv_terminate_destroy(handle)
if self._event_thread:
self._event_thread.join()
def set_loglevel(self, level):
"""Set MPV's log level. This adjusts which output will be sent to this object's log handlers. If you just want
mpv's regular terminal output, you don't need to adjust this but just need to pass a log handler to the MPV
constructur such as ``MPV(log_handler=print)``.
Valid log levels are "no", "fatal", "error", "warn", "info", "v" "debug" and "trace". For details see your mpv's
client.h header file.
"""
_mpv_request_log_messages(self._event_handle, level.encode('utf-8'))
def command(self, name, *args):
"""Execute a raw command."""
args = [name.encode('utf-8')] + [ (arg if type(arg) is bytes else str(arg).encode('utf-8'))
for arg in args if arg is not None ] + [None]
_mpv_command(self.handle, (c_char_p*len(args))(*args))
def node_command(self, name, *args, decoder=strict_decoder):
_1, _2, _3, pointer = _make_node_str_list([name, *args])
out = cast(create_string_buffer(sizeof(MpvNode)), POINTER(MpvNode))
ppointer = cast(pointer, POINTER(MpvNode))
_mpv_command_node(self.handle, ppointer, out)
rv = out.contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
def seek(self, amount, reference="relative", precision="default-precise"):
"""Mapped mpv seek command, see man mpv(1)."""
self.command('seek', amount, reference, precision)
def revert_seek(self):
"""Mapped mpv revert_seek command, see man mpv(1)."""
self.command('revert_seek');
def frame_step(self):
"""Mapped mpv frame_step command, see man mpv(1)."""
self.command('frame_step')
def frame_back_step(self):
"""Mapped mpv frame_back_step command, see man mpv(1)."""
self.command('frame_back_step')
def property_add(self, name, value=1):
"""Add the given value to the property's value. On overflow or underflow, clamp the property to the maximum. If
``value`` is omitted, assume ``1``.
"""
self.command('add', name, value)
def property_multiply(self, name, factor):
"""Multiply the value of a property with a numeric factor."""
self.command('multiply', name, factor)
def cycle(self, name, direction='up'):
"""Cycle the given property. ``up`` and ``down`` set the cycle direction. On overflow, set the property back to
the minimum, on underflow set it to the maximum. If ``up`` or ``down`` is omitted, assume ``up``.
"""
self.command('cycle', name, direction)
def screenshot(self, includes='subtitles', mode='single'):
"""Mapped mpv screenshot command, see man mpv(1)."""
self.command('screenshot', includes, mode)
def screenshot_to_file(self, filename, includes='subtitles'):
"""Mapped mpv screenshot_to_file command, see man mpv(1)."""
self.command('screenshot_to_file', filename.encode(fs_enc), includes)
def screenshot_raw(self, includes='subtitles'):
"""Mapped mpv screenshot_raw command, see man mpv(1). Returns a pillow Image object."""
from PIL import Image
res = self.node_command('screenshot-raw', includes)
if res['format'] != 'bgr0':
raise ValueError('Screenshot in unknown format "{}". Currently, only bgr0 is supported.'
.format(res['format']))
img = Image.frombytes('RGBA', (res['w'], res['h']), res['data'])
b,g,r,a = img.split()
return Image.merge('RGB', (r,g,b))
def playlist_next(self, mode='weak'):
"""Mapped mpv playlist_next command, see man mpv(1)."""
self.command('playlist_next', mode)
def playlist_prev(self, mode='weak'):
"""Mapped mpv playlist_prev command, see man mpv(1)."""
self.command('playlist_prev', mode)
@staticmethod
def _encode_options(options):
return ','.join('{}={}'.format(str(key), str(val)) for key, val in options.items())
def loadfile(self, filename, mode='replace', **options):
"""Mapped mpv loadfile command, see man mpv(1)."""
self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode_options(options))
def loadlist(self, playlist, mode='replace'):
"""Mapped mpv loadlist command, see man mpv(1)."""
self.command('loadlist', playlist.encode(fs_enc), mode)
def playlist_clear(self):
"""Mapped mpv playlist_clear command, see man mpv(1)."""
self.command('playlist_clear')
def playlist_remove(self, index='current'):
"""Mapped mpv playlist_remove command, see man mpv(1)."""
self.command('playlist_remove', index)
def playlist_move(self, index1, index2):
"""Mapped mpv playlist_move command, see man mpv(1)."""
self.command('playlist_move', index1, index2)
def run(self, command, *args):
"""Mapped mpv run command, see man mpv(1)."""
self.command('run', command, *args)
def quit(self, code=None):
"""Mapped mpv quit command, see man mpv(1)."""
self.command('quit', code)
def quit_watch_later(self, code=None):
"""Mapped mpv quit_watch_later command, see man mpv(1)."""
self.command('quit_watch_later', code)
def sub_add(self, filename):
"""Mapped mpv sub_add command, see man mpv(1)."""
self.command('sub_add', filename.encode(fs_enc))
def sub_remove(self, sub_id=None):
"""Mapped mpv sub_remove command, see man mpv(1)."""
self.command('sub_remove', sub_id)
def sub_reload(self, sub_id=None):
"""Mapped mpv sub_reload command, see man mpv(1)."""
self.command('sub_reload', sub_id)
def sub_step(self, skip):
"""Mapped mpv sub_step command, see man mpv(1)."""
self.command('sub_step', skip)
def sub_seek(self, skip):
"""Mapped mpv sub_seek command, see man mpv(1)."""
self.command('sub_seek', skip)
def toggle_osd(self):
"""Mapped mpv osd command, see man mpv(1)."""
self.command('osd')
def show_text(self, string, duration='-1', level=None):
"""Mapped mpv show_text command, see man mpv(1)."""
self.command('show_text', string, duration, level)
def show_progress(self):
"""Mapped mpv show_progress command, see man mpv(1)."""
self.command('show_progress')
def discnav(self, command):
"""Mapped mpv discnav command, see man mpv(1)."""
self.command('discnav', command)
def write_watch_later_config(self):
"""Mapped mpv write_watch_later_config command, see man mpv(1)."""
self.command('write_watch_later_config')
def overlay_add(self, overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride):
"""Mapped mpv overlay_add command, see man mpv(1)."""
self.command('overlay_add', overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride)
def overlay_remove(self, overlay_id):
"""Mapped mpv overlay_remove command, see man mpv(1)."""
self.command('overlay_remove', overlay_id)
def script_message(self, *args):
"""Mapped mpv script_message command, see man mpv(1)."""
self.command('script_message', *args)
def script_message_to(self, target, *args):
"""Mapped mpv script_message_to command, see man mpv(1)."""
self.command('script_message_to', target, *args)
def observe_property(self, name, handler):
"""Register an observer on the named property. An observer is a function that is called with the new property
value every time the property's value is changed. The basic function signature is ``fun(property_name,
new_value)`` with new_value being the decoded property value as a python object. This function can be used as a
function decorator if no handler is given.
To unregister the observer, call either of ``mpv.unobserve_property(name, handler)``,
``mpv.unobserve_all_properties(handler)`` or the handler's ``unregister_mpv_properties`` attribute::
@player.observe_property('volume')
def my_handler(new_volume, *):
print("It's loud!", volume)
my_handler.unregister_mpv_properties()
"""
self._property_handlers[name].append(handler)
_mpv_observe_property(self._event_handle, hash(name)&0xffffffffffffffff, name.encode('utf-8'), MpvFormat.NODE)
def property_observer(self, name):
"""Function decorator to register a property observer. See ``MPV.observe_property`` for details."""
def wrapper(fun):
self.observe_property(name, fun)
fun.unobserve_mpv_properties = lambda: self.unobserve_property(name, fun)
return fun
return wrapper
def unobserve_property(self, name, handler):
"""Unregister a property observer. This requires both the observed property's name and the handler function that
was originally registered as one handler could be registered for several properties. To unregister a handler
from *all* observed properties see ``unobserve_all_properties``.
"""
self._property_handlers[name].remove(handler)
if not self._property_handlers[name]:
_mpv_unobserve_property(self._event_handle, hash(name)&0xffffffffffffffff)
def unobserve_all_properties(self, handler):
"""Unregister a property observer from *all* observed properties."""
for name in self._property_handlers:
self.unobserve_property(name, handler)
def register_message_handler(self, target, handler=None):
"""Register a mpv script message handler. This can be used to communicate with embedded lua scripts. Pass the
script message target name this handler should be listening to and the handler function.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
self._register_message_handler_internal(target, handler)
def _register_message_handler_internal(self, target, handler):
self._message_handlers[target] = handler
def unregister_message_handler(self, target_or_handler):
"""Unregister a mpv script message handler for the given script message target name.
You can also call the ``unregister_mpv_messages`` function attribute set on the handler function when it is
registered.
"""
if isinstance(target_or_handler, str):
del self._message_handlers[target_or_handler]
else:
for key, val in self._message_handlers.items():
if val == target_or_handler:
del self._message_handlers[key]
def register_event_callback(self, callback):
"""Register a blanket event callback receiving all event types.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
self._event_callbacks.append(callback)
def unregister_event_callback(self, callback):
"""Unregiser an event callback."""
self._event_callbacks.remove(callback)
def event_callback(self, *event_types):
"""Function decorator to register a blanket event callback for the given event types. Event types can be given
as str (e.g. 'start-file'), integer or MpvEventID object.
WARNING: Due to the way this is filtering events, this decorator cannot be chained with itself.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
def register(callback):
types = [MpvEventID.from_str(t) if isinstance(t, str) else t for t in event_types] or MpvEventID.ANY
@wraps(callback)
def wrapper(event, *args, **kwargs):
if event['event_id'] in types:
callback(event, *args, **kwargs)
self._event_callbacks.append(wrapper)
wrapper.unregister_mpv_events = partial(self.unregister_event_callback, wrapper)
return wrapper
return register
@staticmethod
def _binding_name(callback_or_cmd):
return 'py_kb_{:016x}'.format(hash(callback_or_cmd)&0xffffffffffffffff)
def on_key_press(self, keydef, mode='force'):
"""Function decorator to register a simplified key binding. The callback is called whenever the key given is
*pressed*.
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.on_key_press('Q')
def binding():
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
The BIG FAT WARNING regarding untrusted keydefs from the key_binding method applies here as well.
"""
def register(fun):
@self.key_binding(keydef, mode)
@wraps(fun)
def wrapper(state='p-', name=None):
if state[0] in ('d', 'p'):
fun()
return wrapper
return register
def key_binding(self, keydef, mode='force'):
"""Function decorator to register a low-level key binding.
The callback function signature is ``fun(key_state, key_name)`` where ``key_state`` is either ``'U'`` for "key
up" or ``'D'`` for "key down".
The keydef format is: ``[Shift+][Ctrl+][Alt+][Meta+]<key>`` where ``<key>`` is either the literal character the
key produces (ASCII or Unicode character), or a symbolic name (as printed by ``mpv --input-keylist``).
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.key_binding('Q')
def binding(state, name):
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
BIG FAT WARNING: mpv's key binding mechanism is pretty powerful. This means, you essentially get arbitrary code
exectution through key bindings. This interface makes some limited effort to sanitize the keydef given in the
first parameter, but YOU SHOULD NOT RELY ON THIS IN FOR SECURITY. If your input comes from config files, this is
completely fine--but, if you are about to pass untrusted input into this parameter, better double-check whether
this is secure in your case.
"""
def register(fun):
fun.mpv_key_bindings = getattr(fun, 'mpv_key_bindings', []) + [keydef]
def unregister_all():
for keydef in fun.mpv_key_bindings:
self.unregister_key_binding(keydef)
fun.unregister_mpv_key_bindings = unregister_all
self.register_key_binding(keydef, fun, mode)
return fun
return register
def register_key_binding(self, keydef, callback_or_cmd, mode='force'):
"""Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python
callback function. See ``MPV.key_binding`` for details.
"""
if not re.match(r'(Shift+)?(Ctrl+)?(Alt+)?(Meta+)?(.|\w+)', keydef):
raise ValueError('Invalid keydef. Expected format: [Shift+][Ctrl+][Alt+][Meta+]<key>\n'
'<key> is either the literal character the key produces (ASCII or Unicode character), or a '
'symbolic name (as printed by --input-keylist')
binding_name = MPV._binding_name(keydef)
if callable(callback_or_cmd):
self._key_binding_handlers[binding_name] = callback_or_cmd
self.register_message_handler('key-binding', self._handle_key_binding_message)
self.command('define-section',
binding_name, '{} script-binding py_event_handler/{}'.format(keydef, binding_name), mode)
elif isinstance(callback_or_cmd, str):
self.command('define-section', binding_name, '{} {}'.format(keydef, callback_or_cmd), mode)
else:
raise TypeError('register_key_binding expects either an str with an mpv command or a python callable.')
self.command('enable-section', binding_name, 'allow-hide-cursor+allow-vo-dragging')
def _handle_key_binding_message(self, binding_name, key_state, key_name=None):
self._key_binding_handlers[binding_name](key_state, key_name)
def unregister_key_binding(self, keydef):
"""Unregister a key binding by keydef."""
binding_name = MPV._binding_name(keydef)
self.command('disable-section', binding_name)
self.command('define-section', binding_name, '')
if binding_name in self._key_binding_handlers:
del self._key_binding_handlers[binding_name]
if not self._key_binding_handlers:
self.unregister_message_handler('key-binding')
# Convenience functions
def play(self, filename):
"""Play a path or URL (requires ``ytdl`` option to be set)."""
self.loadfile(filename)
@property
def playlist_filenames(self):
"""Return all playlist item file names/URLs as a list of strs."""
return [element['filename'] for element in self.playlist]
def playlist_append(self, filename, **options):
"""Append a path or URL to the playlist. This does not start playing the file automatically. To do that, use
``MPV.loadfile(filename, 'append-play')``."""
self.loadfile(filename, 'append', **options)
# Property accessors
def _get_property(self, name, decoder=strict_decoder, fmt=MpvFormat.NODE):
out = create_string_buffer(sizeof(MpvNode))
try:
cval = _mpv_get_property(self.handle, name.encode('utf-8'), fmt, out)
if fmt is MpvFormat.OSD_STRING:
return cast(out, POINTER(c_char_p)).contents.value.decode('utf-8')
elif fmt is MpvFormat.NODE:
rv = cast(out, POINTER(MpvNode)).contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
else:
raise TypeError('_get_property only supports NODE and OSD_STRING formats.')
except PropertyUnavailableError as ex:
return None
def _set_property(self, name, value):
ename = name.encode('utf-8')
if isinstance(value, (list, set, dict)):
_1, _2, _3, pointer = _make_node_str_list(value)
_mpv_set_property(self.handle, ename, MpvFormat.NODE, pointer)
else:
_mpv_set_property_string(self.handle, ename, _mpv_coax_proptype(value))
def __getattr__(self, name):
return self._get_property(_py_to_mpv(name), lazy_decoder)
def __setattr__(self, name, value):
try:
if name != 'handle' and not name.startswith('_'):
self._set_property(_py_to_mpv(name), value)
else:
super().__setattr__(name, value)
except AttributeError:
super().__setattr__(name, value)
def __dir__(self):
return super().__dir__() + [ name.replace('-', '_') for name in self.property_list ]
@property
def properties(self):
return { name: self.option_info(name) for name in self.property_list }
# Dict-like option access
def __getitem__(self, name, file_local=False):
"""Get an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._get_property(prefix+name, lazy_decoder)
def __setitem__(self, name, value, file_local=False):
"""Set an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._set_property(prefix+name, value)
def __iter__(self):
"""Iterate over all option names."""
return iter(self.options)
def option_info(self, name):
"""Get information on the given option."""
try:
return self._get_property('option-info/'+name)
except AttributeError:
return None
|
jaseg/python-mpv | mpv.py | MPV.event_callback | python | def event_callback(self, *event_types):
def register(callback):
types = [MpvEventID.from_str(t) if isinstance(t, str) else t for t in event_types] or MpvEventID.ANY
@wraps(callback)
def wrapper(event, *args, **kwargs):
if event['event_id'] in types:
callback(event, *args, **kwargs)
self._event_callbacks.append(wrapper)
wrapper.unregister_mpv_events = partial(self.unregister_event_callback, wrapper)
return wrapper
return register | Function decorator to register a blanket event callback for the given event types. Event types can be given
as str (e.g. 'start-file'), integer or MpvEventID object.
WARNING: Due to the way this is filtering events, this decorator cannot be chained with itself.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events() | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L901-L925 | null | class MPV(object):
"""See man mpv(1) for the details of the implemented commands. All mpv properties can be accessed as
``my_mpv.some_property`` and all mpv options can be accessed as ``my_mpv['some-option']``.
By default, properties are returned as decoded ``str`` and an error is thrown if the value does not contain valid
utf-8. To get a decoded ``str`` if possibly but ``bytes`` instead of an error if not, use
``my_mpv.lazy.some_property``. To always get raw ``bytes``, use ``my_mpv.raw.some_property``. To access a
property's decoded OSD value, use ``my_mpv.osd.some_property``.
To get API information on an option, use ``my_mpv.option_info('option-name')``. To get API information on a
property, use ``my_mpv.properties['property-name']``. Take care to use mpv's dashed-names instead of the
underscore_names exposed on the python object.
To make your program not barf hard the first time its used on a weird file system **always** access properties
containing file names or file tags through ``MPV.raw``. """
def __init__(self, *extra_mpv_flags, log_handler=None, start_event_thread=True, loglevel=None, **extra_mpv_opts):
"""Create an MPV instance.
Extra arguments and extra keyword arguments will be passed to mpv as options.
"""
self.handle = _mpv_create()
self._event_thread = None
_mpv_set_option_string(self.handle, b'audio-display', b'no')
istr = lambda o: ('yes' if o else 'no') if type(o) is bool else str(o)
try:
for flag in extra_mpv_flags:
_mpv_set_option_string(self.handle, flag.encode('utf-8'), b'')
for k,v in extra_mpv_opts.items():
_mpv_set_option_string(self.handle, k.replace('_', '-').encode('utf-8'), istr(v).encode('utf-8'))
finally:
_mpv_initialize(self.handle)
self.osd = _OSDPropertyProxy(self)
self.file_local = _FileLocalProxy(self)
self.raw = _DecoderPropertyProxy(self, identity_decoder)
self.strict = _DecoderPropertyProxy(self, strict_decoder)
self.lazy = _DecoderPropertyProxy(self, lazy_decoder)
self._event_callbacks = []
self._property_handlers = collections.defaultdict(lambda: [])
self._message_handlers = {}
self._key_binding_handlers = {}
self._playback_cond = threading.Condition()
self._event_handle = _mpv_create_client(self.handle, b'py_event_handler')
self._loop = partial(_event_loop, self._event_handle, self._playback_cond, self._event_callbacks,
self._message_handlers, self._property_handlers, log_handler)
if loglevel is not None or log_handler is not None:
self.set_loglevel(loglevel or 'terminal-default')
if start_event_thread:
self._event_thread = threading.Thread(target=self._loop, name='MPVEventHandlerThread')
self._event_thread.setDaemon(True)
self._event_thread.start()
else:
self._event_thread = None
def wait_for_playback(self):
"""Waits until playback of the current title is paused or done."""
with self._playback_cond:
self._playback_cond.wait()
def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True):
"""Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for
properties such as ``idle_active`` indicating the player is done with regular playback and just idling around
"""
sema = threading.Semaphore(value=0)
def observer(name, val):
if cond(val):
sema.release()
self.observe_property(name, observer)
if not level_sensitive or not cond(getattr(self, name.replace('-', '_'))):
sema.acquire()
self.unobserve_property(name, observer)
def __del__(self):
if self.handle:
self.terminate()
def terminate(self):
"""Properly terminates this player instance. Preferably use this instead of relying on python's garbage
collector to cause this to be called from the object's destructor.
"""
self.handle, handle = None, self.handle
if threading.current_thread() is self._event_thread:
# Handle special case to allow event handle to be detached.
# This is necessary since otherwise the event thread would deadlock itself.
grim_reaper = threading.Thread(target=lambda: _mpv_terminate_destroy(handle))
grim_reaper.start()
else:
_mpv_terminate_destroy(handle)
if self._event_thread:
self._event_thread.join()
def set_loglevel(self, level):
"""Set MPV's log level. This adjusts which output will be sent to this object's log handlers. If you just want
mpv's regular terminal output, you don't need to adjust this but just need to pass a log handler to the MPV
constructur such as ``MPV(log_handler=print)``.
Valid log levels are "no", "fatal", "error", "warn", "info", "v" "debug" and "trace". For details see your mpv's
client.h header file.
"""
_mpv_request_log_messages(self._event_handle, level.encode('utf-8'))
def command(self, name, *args):
"""Execute a raw command."""
args = [name.encode('utf-8')] + [ (arg if type(arg) is bytes else str(arg).encode('utf-8'))
for arg in args if arg is not None ] + [None]
_mpv_command(self.handle, (c_char_p*len(args))(*args))
def node_command(self, name, *args, decoder=strict_decoder):
_1, _2, _3, pointer = _make_node_str_list([name, *args])
out = cast(create_string_buffer(sizeof(MpvNode)), POINTER(MpvNode))
ppointer = cast(pointer, POINTER(MpvNode))
_mpv_command_node(self.handle, ppointer, out)
rv = out.contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
def seek(self, amount, reference="relative", precision="default-precise"):
"""Mapped mpv seek command, see man mpv(1)."""
self.command('seek', amount, reference, precision)
def revert_seek(self):
"""Mapped mpv revert_seek command, see man mpv(1)."""
self.command('revert_seek');
def frame_step(self):
"""Mapped mpv frame_step command, see man mpv(1)."""
self.command('frame_step')
def frame_back_step(self):
"""Mapped mpv frame_back_step command, see man mpv(1)."""
self.command('frame_back_step')
def property_add(self, name, value=1):
"""Add the given value to the property's value. On overflow or underflow, clamp the property to the maximum. If
``value`` is omitted, assume ``1``.
"""
self.command('add', name, value)
def property_multiply(self, name, factor):
"""Multiply the value of a property with a numeric factor."""
self.command('multiply', name, factor)
def cycle(self, name, direction='up'):
"""Cycle the given property. ``up`` and ``down`` set the cycle direction. On overflow, set the property back to
the minimum, on underflow set it to the maximum. If ``up`` or ``down`` is omitted, assume ``up``.
"""
self.command('cycle', name, direction)
def screenshot(self, includes='subtitles', mode='single'):
"""Mapped mpv screenshot command, see man mpv(1)."""
self.command('screenshot', includes, mode)
def screenshot_to_file(self, filename, includes='subtitles'):
"""Mapped mpv screenshot_to_file command, see man mpv(1)."""
self.command('screenshot_to_file', filename.encode(fs_enc), includes)
def screenshot_raw(self, includes='subtitles'):
"""Mapped mpv screenshot_raw command, see man mpv(1). Returns a pillow Image object."""
from PIL import Image
res = self.node_command('screenshot-raw', includes)
if res['format'] != 'bgr0':
raise ValueError('Screenshot in unknown format "{}". Currently, only bgr0 is supported.'
.format(res['format']))
img = Image.frombytes('RGBA', (res['w'], res['h']), res['data'])
b,g,r,a = img.split()
return Image.merge('RGB', (r,g,b))
def playlist_next(self, mode='weak'):
"""Mapped mpv playlist_next command, see man mpv(1)."""
self.command('playlist_next', mode)
def playlist_prev(self, mode='weak'):
"""Mapped mpv playlist_prev command, see man mpv(1)."""
self.command('playlist_prev', mode)
@staticmethod
def _encode_options(options):
return ','.join('{}={}'.format(str(key), str(val)) for key, val in options.items())
def loadfile(self, filename, mode='replace', **options):
"""Mapped mpv loadfile command, see man mpv(1)."""
self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode_options(options))
def loadlist(self, playlist, mode='replace'):
"""Mapped mpv loadlist command, see man mpv(1)."""
self.command('loadlist', playlist.encode(fs_enc), mode)
def playlist_clear(self):
"""Mapped mpv playlist_clear command, see man mpv(1)."""
self.command('playlist_clear')
def playlist_remove(self, index='current'):
"""Mapped mpv playlist_remove command, see man mpv(1)."""
self.command('playlist_remove', index)
def playlist_move(self, index1, index2):
"""Mapped mpv playlist_move command, see man mpv(1)."""
self.command('playlist_move', index1, index2)
def run(self, command, *args):
"""Mapped mpv run command, see man mpv(1)."""
self.command('run', command, *args)
def quit(self, code=None):
"""Mapped mpv quit command, see man mpv(1)."""
self.command('quit', code)
def quit_watch_later(self, code=None):
"""Mapped mpv quit_watch_later command, see man mpv(1)."""
self.command('quit_watch_later', code)
def sub_add(self, filename):
"""Mapped mpv sub_add command, see man mpv(1)."""
self.command('sub_add', filename.encode(fs_enc))
def sub_remove(self, sub_id=None):
"""Mapped mpv sub_remove command, see man mpv(1)."""
self.command('sub_remove', sub_id)
def sub_reload(self, sub_id=None):
"""Mapped mpv sub_reload command, see man mpv(1)."""
self.command('sub_reload', sub_id)
def sub_step(self, skip):
"""Mapped mpv sub_step command, see man mpv(1)."""
self.command('sub_step', skip)
def sub_seek(self, skip):
"""Mapped mpv sub_seek command, see man mpv(1)."""
self.command('sub_seek', skip)
def toggle_osd(self):
"""Mapped mpv osd command, see man mpv(1)."""
self.command('osd')
def show_text(self, string, duration='-1', level=None):
"""Mapped mpv show_text command, see man mpv(1)."""
self.command('show_text', string, duration, level)
def show_progress(self):
"""Mapped mpv show_progress command, see man mpv(1)."""
self.command('show_progress')
def discnav(self, command):
"""Mapped mpv discnav command, see man mpv(1)."""
self.command('discnav', command)
def write_watch_later_config(self):
"""Mapped mpv write_watch_later_config command, see man mpv(1)."""
self.command('write_watch_later_config')
def overlay_add(self, overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride):
"""Mapped mpv overlay_add command, see man mpv(1)."""
self.command('overlay_add', overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride)
def overlay_remove(self, overlay_id):
"""Mapped mpv overlay_remove command, see man mpv(1)."""
self.command('overlay_remove', overlay_id)
def script_message(self, *args):
"""Mapped mpv script_message command, see man mpv(1)."""
self.command('script_message', *args)
def script_message_to(self, target, *args):
"""Mapped mpv script_message_to command, see man mpv(1)."""
self.command('script_message_to', target, *args)
def observe_property(self, name, handler):
"""Register an observer on the named property. An observer is a function that is called with the new property
value every time the property's value is changed. The basic function signature is ``fun(property_name,
new_value)`` with new_value being the decoded property value as a python object. This function can be used as a
function decorator if no handler is given.
To unregister the observer, call either of ``mpv.unobserve_property(name, handler)``,
``mpv.unobserve_all_properties(handler)`` or the handler's ``unregister_mpv_properties`` attribute::
@player.observe_property('volume')
def my_handler(new_volume, *):
print("It's loud!", volume)
my_handler.unregister_mpv_properties()
"""
self._property_handlers[name].append(handler)
_mpv_observe_property(self._event_handle, hash(name)&0xffffffffffffffff, name.encode('utf-8'), MpvFormat.NODE)
def property_observer(self, name):
"""Function decorator to register a property observer. See ``MPV.observe_property`` for details."""
def wrapper(fun):
self.observe_property(name, fun)
fun.unobserve_mpv_properties = lambda: self.unobserve_property(name, fun)
return fun
return wrapper
def unobserve_property(self, name, handler):
"""Unregister a property observer. This requires both the observed property's name and the handler function that
was originally registered as one handler could be registered for several properties. To unregister a handler
from *all* observed properties see ``unobserve_all_properties``.
"""
self._property_handlers[name].remove(handler)
if not self._property_handlers[name]:
_mpv_unobserve_property(self._event_handle, hash(name)&0xffffffffffffffff)
def unobserve_all_properties(self, handler):
"""Unregister a property observer from *all* observed properties."""
for name in self._property_handlers:
self.unobserve_property(name, handler)
def register_message_handler(self, target, handler=None):
"""Register a mpv script message handler. This can be used to communicate with embedded lua scripts. Pass the
script message target name this handler should be listening to and the handler function.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
self._register_message_handler_internal(target, handler)
def _register_message_handler_internal(self, target, handler):
self._message_handlers[target] = handler
def unregister_message_handler(self, target_or_handler):
"""Unregister a mpv script message handler for the given script message target name.
You can also call the ``unregister_mpv_messages`` function attribute set on the handler function when it is
registered.
"""
if isinstance(target_or_handler, str):
del self._message_handlers[target_or_handler]
else:
for key, val in self._message_handlers.items():
if val == target_or_handler:
del self._message_handlers[key]
def message_handler(self, target):
"""Decorator to register a mpv script message handler.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
def register(handler):
self._register_message_handler_internal(target, handler)
handler.unregister_mpv_messages = lambda: self.unregister_message_handler(handler)
return handler
return register
def register_event_callback(self, callback):
"""Register a blanket event callback receiving all event types.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
self._event_callbacks.append(callback)
def unregister_event_callback(self, callback):
"""Unregiser an event callback."""
self._event_callbacks.remove(callback)
@staticmethod
def _binding_name(callback_or_cmd):
return 'py_kb_{:016x}'.format(hash(callback_or_cmd)&0xffffffffffffffff)
def on_key_press(self, keydef, mode='force'):
"""Function decorator to register a simplified key binding. The callback is called whenever the key given is
*pressed*.
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.on_key_press('Q')
def binding():
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
The BIG FAT WARNING regarding untrusted keydefs from the key_binding method applies here as well.
"""
def register(fun):
@self.key_binding(keydef, mode)
@wraps(fun)
def wrapper(state='p-', name=None):
if state[0] in ('d', 'p'):
fun()
return wrapper
return register
def key_binding(self, keydef, mode='force'):
"""Function decorator to register a low-level key binding.
The callback function signature is ``fun(key_state, key_name)`` where ``key_state`` is either ``'U'`` for "key
up" or ``'D'`` for "key down".
The keydef format is: ``[Shift+][Ctrl+][Alt+][Meta+]<key>`` where ``<key>`` is either the literal character the
key produces (ASCII or Unicode character), or a symbolic name (as printed by ``mpv --input-keylist``).
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.key_binding('Q')
def binding(state, name):
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
BIG FAT WARNING: mpv's key binding mechanism is pretty powerful. This means, you essentially get arbitrary code
exectution through key bindings. This interface makes some limited effort to sanitize the keydef given in the
first parameter, but YOU SHOULD NOT RELY ON THIS IN FOR SECURITY. If your input comes from config files, this is
completely fine--but, if you are about to pass untrusted input into this parameter, better double-check whether
this is secure in your case.
"""
def register(fun):
fun.mpv_key_bindings = getattr(fun, 'mpv_key_bindings', []) + [keydef]
def unregister_all():
for keydef in fun.mpv_key_bindings:
self.unregister_key_binding(keydef)
fun.unregister_mpv_key_bindings = unregister_all
self.register_key_binding(keydef, fun, mode)
return fun
return register
def register_key_binding(self, keydef, callback_or_cmd, mode='force'):
"""Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python
callback function. See ``MPV.key_binding`` for details.
"""
if not re.match(r'(Shift+)?(Ctrl+)?(Alt+)?(Meta+)?(.|\w+)', keydef):
raise ValueError('Invalid keydef. Expected format: [Shift+][Ctrl+][Alt+][Meta+]<key>\n'
'<key> is either the literal character the key produces (ASCII or Unicode character), or a '
'symbolic name (as printed by --input-keylist')
binding_name = MPV._binding_name(keydef)
if callable(callback_or_cmd):
self._key_binding_handlers[binding_name] = callback_or_cmd
self.register_message_handler('key-binding', self._handle_key_binding_message)
self.command('define-section',
binding_name, '{} script-binding py_event_handler/{}'.format(keydef, binding_name), mode)
elif isinstance(callback_or_cmd, str):
self.command('define-section', binding_name, '{} {}'.format(keydef, callback_or_cmd), mode)
else:
raise TypeError('register_key_binding expects either an str with an mpv command or a python callable.')
self.command('enable-section', binding_name, 'allow-hide-cursor+allow-vo-dragging')
def _handle_key_binding_message(self, binding_name, key_state, key_name=None):
self._key_binding_handlers[binding_name](key_state, key_name)
def unregister_key_binding(self, keydef):
"""Unregister a key binding by keydef."""
binding_name = MPV._binding_name(keydef)
self.command('disable-section', binding_name)
self.command('define-section', binding_name, '')
if binding_name in self._key_binding_handlers:
del self._key_binding_handlers[binding_name]
if not self._key_binding_handlers:
self.unregister_message_handler('key-binding')
# Convenience functions
def play(self, filename):
"""Play a path or URL (requires ``ytdl`` option to be set)."""
self.loadfile(filename)
@property
def playlist_filenames(self):
"""Return all playlist item file names/URLs as a list of strs."""
return [element['filename'] for element in self.playlist]
def playlist_append(self, filename, **options):
"""Append a path or URL to the playlist. This does not start playing the file automatically. To do that, use
``MPV.loadfile(filename, 'append-play')``."""
self.loadfile(filename, 'append', **options)
# Property accessors
def _get_property(self, name, decoder=strict_decoder, fmt=MpvFormat.NODE):
out = create_string_buffer(sizeof(MpvNode))
try:
cval = _mpv_get_property(self.handle, name.encode('utf-8'), fmt, out)
if fmt is MpvFormat.OSD_STRING:
return cast(out, POINTER(c_char_p)).contents.value.decode('utf-8')
elif fmt is MpvFormat.NODE:
rv = cast(out, POINTER(MpvNode)).contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
else:
raise TypeError('_get_property only supports NODE and OSD_STRING formats.')
except PropertyUnavailableError as ex:
return None
def _set_property(self, name, value):
ename = name.encode('utf-8')
if isinstance(value, (list, set, dict)):
_1, _2, _3, pointer = _make_node_str_list(value)
_mpv_set_property(self.handle, ename, MpvFormat.NODE, pointer)
else:
_mpv_set_property_string(self.handle, ename, _mpv_coax_proptype(value))
def __getattr__(self, name):
return self._get_property(_py_to_mpv(name), lazy_decoder)
def __setattr__(self, name, value):
try:
if name != 'handle' and not name.startswith('_'):
self._set_property(_py_to_mpv(name), value)
else:
super().__setattr__(name, value)
except AttributeError:
super().__setattr__(name, value)
def __dir__(self):
return super().__dir__() + [ name.replace('-', '_') for name in self.property_list ]
@property
def properties(self):
return { name: self.option_info(name) for name in self.property_list }
# Dict-like option access
def __getitem__(self, name, file_local=False):
"""Get an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._get_property(prefix+name, lazy_decoder)
def __setitem__(self, name, value, file_local=False):
"""Set an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._set_property(prefix+name, value)
def __iter__(self):
"""Iterate over all option names."""
return iter(self.options)
def option_info(self, name):
"""Get information on the given option."""
try:
return self._get_property('option-info/'+name)
except AttributeError:
return None
|
jaseg/python-mpv | mpv.py | MPV.on_key_press | python | def on_key_press(self, keydef, mode='force'):
def register(fun):
@self.key_binding(keydef, mode)
@wraps(fun)
def wrapper(state='p-', name=None):
if state[0] in ('d', 'p'):
fun()
return wrapper
return register | Function decorator to register a simplified key binding. The callback is called whenever the key given is
*pressed*.
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.on_key_press('Q')
def binding():
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
The BIG FAT WARNING regarding untrusted keydefs from the key_binding method applies here as well. | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L931-L957 | null | class MPV(object):
"""See man mpv(1) for the details of the implemented commands. All mpv properties can be accessed as
``my_mpv.some_property`` and all mpv options can be accessed as ``my_mpv['some-option']``.
By default, properties are returned as decoded ``str`` and an error is thrown if the value does not contain valid
utf-8. To get a decoded ``str`` if possibly but ``bytes`` instead of an error if not, use
``my_mpv.lazy.some_property``. To always get raw ``bytes``, use ``my_mpv.raw.some_property``. To access a
property's decoded OSD value, use ``my_mpv.osd.some_property``.
To get API information on an option, use ``my_mpv.option_info('option-name')``. To get API information on a
property, use ``my_mpv.properties['property-name']``. Take care to use mpv's dashed-names instead of the
underscore_names exposed on the python object.
To make your program not barf hard the first time its used on a weird file system **always** access properties
containing file names or file tags through ``MPV.raw``. """
def __init__(self, *extra_mpv_flags, log_handler=None, start_event_thread=True, loglevel=None, **extra_mpv_opts):
"""Create an MPV instance.
Extra arguments and extra keyword arguments will be passed to mpv as options.
"""
self.handle = _mpv_create()
self._event_thread = None
_mpv_set_option_string(self.handle, b'audio-display', b'no')
istr = lambda o: ('yes' if o else 'no') if type(o) is bool else str(o)
try:
for flag in extra_mpv_flags:
_mpv_set_option_string(self.handle, flag.encode('utf-8'), b'')
for k,v in extra_mpv_opts.items():
_mpv_set_option_string(self.handle, k.replace('_', '-').encode('utf-8'), istr(v).encode('utf-8'))
finally:
_mpv_initialize(self.handle)
self.osd = _OSDPropertyProxy(self)
self.file_local = _FileLocalProxy(self)
self.raw = _DecoderPropertyProxy(self, identity_decoder)
self.strict = _DecoderPropertyProxy(self, strict_decoder)
self.lazy = _DecoderPropertyProxy(self, lazy_decoder)
self._event_callbacks = []
self._property_handlers = collections.defaultdict(lambda: [])
self._message_handlers = {}
self._key_binding_handlers = {}
self._playback_cond = threading.Condition()
self._event_handle = _mpv_create_client(self.handle, b'py_event_handler')
self._loop = partial(_event_loop, self._event_handle, self._playback_cond, self._event_callbacks,
self._message_handlers, self._property_handlers, log_handler)
if loglevel is not None or log_handler is not None:
self.set_loglevel(loglevel or 'terminal-default')
if start_event_thread:
self._event_thread = threading.Thread(target=self._loop, name='MPVEventHandlerThread')
self._event_thread.setDaemon(True)
self._event_thread.start()
else:
self._event_thread = None
def wait_for_playback(self):
"""Waits until playback of the current title is paused or done."""
with self._playback_cond:
self._playback_cond.wait()
def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True):
"""Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for
properties such as ``idle_active`` indicating the player is done with regular playback and just idling around
"""
sema = threading.Semaphore(value=0)
def observer(name, val):
if cond(val):
sema.release()
self.observe_property(name, observer)
if not level_sensitive or not cond(getattr(self, name.replace('-', '_'))):
sema.acquire()
self.unobserve_property(name, observer)
def __del__(self):
if self.handle:
self.terminate()
def terminate(self):
"""Properly terminates this player instance. Preferably use this instead of relying on python's garbage
collector to cause this to be called from the object's destructor.
"""
self.handle, handle = None, self.handle
if threading.current_thread() is self._event_thread:
# Handle special case to allow event handle to be detached.
# This is necessary since otherwise the event thread would deadlock itself.
grim_reaper = threading.Thread(target=lambda: _mpv_terminate_destroy(handle))
grim_reaper.start()
else:
_mpv_terminate_destroy(handle)
if self._event_thread:
self._event_thread.join()
def set_loglevel(self, level):
"""Set MPV's log level. This adjusts which output will be sent to this object's log handlers. If you just want
mpv's regular terminal output, you don't need to adjust this but just need to pass a log handler to the MPV
constructur such as ``MPV(log_handler=print)``.
Valid log levels are "no", "fatal", "error", "warn", "info", "v" "debug" and "trace". For details see your mpv's
client.h header file.
"""
_mpv_request_log_messages(self._event_handle, level.encode('utf-8'))
def command(self, name, *args):
"""Execute a raw command."""
args = [name.encode('utf-8')] + [ (arg if type(arg) is bytes else str(arg).encode('utf-8'))
for arg in args if arg is not None ] + [None]
_mpv_command(self.handle, (c_char_p*len(args))(*args))
def node_command(self, name, *args, decoder=strict_decoder):
_1, _2, _3, pointer = _make_node_str_list([name, *args])
out = cast(create_string_buffer(sizeof(MpvNode)), POINTER(MpvNode))
ppointer = cast(pointer, POINTER(MpvNode))
_mpv_command_node(self.handle, ppointer, out)
rv = out.contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
def seek(self, amount, reference="relative", precision="default-precise"):
"""Mapped mpv seek command, see man mpv(1)."""
self.command('seek', amount, reference, precision)
def revert_seek(self):
"""Mapped mpv revert_seek command, see man mpv(1)."""
self.command('revert_seek');
def frame_step(self):
"""Mapped mpv frame_step command, see man mpv(1)."""
self.command('frame_step')
def frame_back_step(self):
"""Mapped mpv frame_back_step command, see man mpv(1)."""
self.command('frame_back_step')
def property_add(self, name, value=1):
"""Add the given value to the property's value. On overflow or underflow, clamp the property to the maximum. If
``value`` is omitted, assume ``1``.
"""
self.command('add', name, value)
def property_multiply(self, name, factor):
"""Multiply the value of a property with a numeric factor."""
self.command('multiply', name, factor)
def cycle(self, name, direction='up'):
"""Cycle the given property. ``up`` and ``down`` set the cycle direction. On overflow, set the property back to
the minimum, on underflow set it to the maximum. If ``up`` or ``down`` is omitted, assume ``up``.
"""
self.command('cycle', name, direction)
def screenshot(self, includes='subtitles', mode='single'):
"""Mapped mpv screenshot command, see man mpv(1)."""
self.command('screenshot', includes, mode)
def screenshot_to_file(self, filename, includes='subtitles'):
"""Mapped mpv screenshot_to_file command, see man mpv(1)."""
self.command('screenshot_to_file', filename.encode(fs_enc), includes)
def screenshot_raw(self, includes='subtitles'):
"""Mapped mpv screenshot_raw command, see man mpv(1). Returns a pillow Image object."""
from PIL import Image
res = self.node_command('screenshot-raw', includes)
if res['format'] != 'bgr0':
raise ValueError('Screenshot in unknown format "{}". Currently, only bgr0 is supported.'
.format(res['format']))
img = Image.frombytes('RGBA', (res['w'], res['h']), res['data'])
b,g,r,a = img.split()
return Image.merge('RGB', (r,g,b))
def playlist_next(self, mode='weak'):
"""Mapped mpv playlist_next command, see man mpv(1)."""
self.command('playlist_next', mode)
def playlist_prev(self, mode='weak'):
"""Mapped mpv playlist_prev command, see man mpv(1)."""
self.command('playlist_prev', mode)
@staticmethod
def _encode_options(options):
return ','.join('{}={}'.format(str(key), str(val)) for key, val in options.items())
def loadfile(self, filename, mode='replace', **options):
"""Mapped mpv loadfile command, see man mpv(1)."""
self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode_options(options))
def loadlist(self, playlist, mode='replace'):
"""Mapped mpv loadlist command, see man mpv(1)."""
self.command('loadlist', playlist.encode(fs_enc), mode)
def playlist_clear(self):
"""Mapped mpv playlist_clear command, see man mpv(1)."""
self.command('playlist_clear')
def playlist_remove(self, index='current'):
"""Mapped mpv playlist_remove command, see man mpv(1)."""
self.command('playlist_remove', index)
def playlist_move(self, index1, index2):
"""Mapped mpv playlist_move command, see man mpv(1)."""
self.command('playlist_move', index1, index2)
def run(self, command, *args):
"""Mapped mpv run command, see man mpv(1)."""
self.command('run', command, *args)
def quit(self, code=None):
"""Mapped mpv quit command, see man mpv(1)."""
self.command('quit', code)
def quit_watch_later(self, code=None):
"""Mapped mpv quit_watch_later command, see man mpv(1)."""
self.command('quit_watch_later', code)
def sub_add(self, filename):
"""Mapped mpv sub_add command, see man mpv(1)."""
self.command('sub_add', filename.encode(fs_enc))
def sub_remove(self, sub_id=None):
"""Mapped mpv sub_remove command, see man mpv(1)."""
self.command('sub_remove', sub_id)
def sub_reload(self, sub_id=None):
"""Mapped mpv sub_reload command, see man mpv(1)."""
self.command('sub_reload', sub_id)
def sub_step(self, skip):
"""Mapped mpv sub_step command, see man mpv(1)."""
self.command('sub_step', skip)
def sub_seek(self, skip):
"""Mapped mpv sub_seek command, see man mpv(1)."""
self.command('sub_seek', skip)
def toggle_osd(self):
"""Mapped mpv osd command, see man mpv(1)."""
self.command('osd')
def show_text(self, string, duration='-1', level=None):
"""Mapped mpv show_text command, see man mpv(1)."""
self.command('show_text', string, duration, level)
def show_progress(self):
"""Mapped mpv show_progress command, see man mpv(1)."""
self.command('show_progress')
def discnav(self, command):
"""Mapped mpv discnav command, see man mpv(1)."""
self.command('discnav', command)
def write_watch_later_config(self):
"""Mapped mpv write_watch_later_config command, see man mpv(1)."""
self.command('write_watch_later_config')
def overlay_add(self, overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride):
"""Mapped mpv overlay_add command, see man mpv(1)."""
self.command('overlay_add', overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride)
def overlay_remove(self, overlay_id):
"""Mapped mpv overlay_remove command, see man mpv(1)."""
self.command('overlay_remove', overlay_id)
def script_message(self, *args):
"""Mapped mpv script_message command, see man mpv(1)."""
self.command('script_message', *args)
def script_message_to(self, target, *args):
"""Mapped mpv script_message_to command, see man mpv(1)."""
self.command('script_message_to', target, *args)
def observe_property(self, name, handler):
"""Register an observer on the named property. An observer is a function that is called with the new property
value every time the property's value is changed. The basic function signature is ``fun(property_name,
new_value)`` with new_value being the decoded property value as a python object. This function can be used as a
function decorator if no handler is given.
To unregister the observer, call either of ``mpv.unobserve_property(name, handler)``,
``mpv.unobserve_all_properties(handler)`` or the handler's ``unregister_mpv_properties`` attribute::
@player.observe_property('volume')
def my_handler(new_volume, *):
print("It's loud!", volume)
my_handler.unregister_mpv_properties()
"""
self._property_handlers[name].append(handler)
_mpv_observe_property(self._event_handle, hash(name)&0xffffffffffffffff, name.encode('utf-8'), MpvFormat.NODE)
def property_observer(self, name):
"""Function decorator to register a property observer. See ``MPV.observe_property`` for details."""
def wrapper(fun):
self.observe_property(name, fun)
fun.unobserve_mpv_properties = lambda: self.unobserve_property(name, fun)
return fun
return wrapper
def unobserve_property(self, name, handler):
"""Unregister a property observer. This requires both the observed property's name and the handler function that
was originally registered as one handler could be registered for several properties. To unregister a handler
from *all* observed properties see ``unobserve_all_properties``.
"""
self._property_handlers[name].remove(handler)
if not self._property_handlers[name]:
_mpv_unobserve_property(self._event_handle, hash(name)&0xffffffffffffffff)
def unobserve_all_properties(self, handler):
"""Unregister a property observer from *all* observed properties."""
for name in self._property_handlers:
self.unobserve_property(name, handler)
def register_message_handler(self, target, handler=None):
"""Register a mpv script message handler. This can be used to communicate with embedded lua scripts. Pass the
script message target name this handler should be listening to and the handler function.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
self._register_message_handler_internal(target, handler)
def _register_message_handler_internal(self, target, handler):
self._message_handlers[target] = handler
def unregister_message_handler(self, target_or_handler):
"""Unregister a mpv script message handler for the given script message target name.
You can also call the ``unregister_mpv_messages`` function attribute set on the handler function when it is
registered.
"""
if isinstance(target_or_handler, str):
del self._message_handlers[target_or_handler]
else:
for key, val in self._message_handlers.items():
if val == target_or_handler:
del self._message_handlers[key]
def message_handler(self, target):
"""Decorator to register a mpv script message handler.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
def register(handler):
self._register_message_handler_internal(target, handler)
handler.unregister_mpv_messages = lambda: self.unregister_message_handler(handler)
return handler
return register
def register_event_callback(self, callback):
"""Register a blanket event callback receiving all event types.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
self._event_callbacks.append(callback)
def unregister_event_callback(self, callback):
"""Unregiser an event callback."""
self._event_callbacks.remove(callback)
def event_callback(self, *event_types):
"""Function decorator to register a blanket event callback for the given event types. Event types can be given
as str (e.g. 'start-file'), integer or MpvEventID object.
WARNING: Due to the way this is filtering events, this decorator cannot be chained with itself.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
def register(callback):
types = [MpvEventID.from_str(t) if isinstance(t, str) else t for t in event_types] or MpvEventID.ANY
@wraps(callback)
def wrapper(event, *args, **kwargs):
if event['event_id'] in types:
callback(event, *args, **kwargs)
self._event_callbacks.append(wrapper)
wrapper.unregister_mpv_events = partial(self.unregister_event_callback, wrapper)
return wrapper
return register
@staticmethod
def _binding_name(callback_or_cmd):
return 'py_kb_{:016x}'.format(hash(callback_or_cmd)&0xffffffffffffffff)
def key_binding(self, keydef, mode='force'):
"""Function decorator to register a low-level key binding.
The callback function signature is ``fun(key_state, key_name)`` where ``key_state`` is either ``'U'`` for "key
up" or ``'D'`` for "key down".
The keydef format is: ``[Shift+][Ctrl+][Alt+][Meta+]<key>`` where ``<key>`` is either the literal character the
key produces (ASCII or Unicode character), or a symbolic name (as printed by ``mpv --input-keylist``).
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.key_binding('Q')
def binding(state, name):
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
BIG FAT WARNING: mpv's key binding mechanism is pretty powerful. This means, you essentially get arbitrary code
exectution through key bindings. This interface makes some limited effort to sanitize the keydef given in the
first parameter, but YOU SHOULD NOT RELY ON THIS IN FOR SECURITY. If your input comes from config files, this is
completely fine--but, if you are about to pass untrusted input into this parameter, better double-check whether
this is secure in your case.
"""
def register(fun):
fun.mpv_key_bindings = getattr(fun, 'mpv_key_bindings', []) + [keydef]
def unregister_all():
for keydef in fun.mpv_key_bindings:
self.unregister_key_binding(keydef)
fun.unregister_mpv_key_bindings = unregister_all
self.register_key_binding(keydef, fun, mode)
return fun
return register
def register_key_binding(self, keydef, callback_or_cmd, mode='force'):
"""Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python
callback function. See ``MPV.key_binding`` for details.
"""
if not re.match(r'(Shift+)?(Ctrl+)?(Alt+)?(Meta+)?(.|\w+)', keydef):
raise ValueError('Invalid keydef. Expected format: [Shift+][Ctrl+][Alt+][Meta+]<key>\n'
'<key> is either the literal character the key produces (ASCII or Unicode character), or a '
'symbolic name (as printed by --input-keylist')
binding_name = MPV._binding_name(keydef)
if callable(callback_or_cmd):
self._key_binding_handlers[binding_name] = callback_or_cmd
self.register_message_handler('key-binding', self._handle_key_binding_message)
self.command('define-section',
binding_name, '{} script-binding py_event_handler/{}'.format(keydef, binding_name), mode)
elif isinstance(callback_or_cmd, str):
self.command('define-section', binding_name, '{} {}'.format(keydef, callback_or_cmd), mode)
else:
raise TypeError('register_key_binding expects either an str with an mpv command or a python callable.')
self.command('enable-section', binding_name, 'allow-hide-cursor+allow-vo-dragging')
def _handle_key_binding_message(self, binding_name, key_state, key_name=None):
self._key_binding_handlers[binding_name](key_state, key_name)
def unregister_key_binding(self, keydef):
"""Unregister a key binding by keydef."""
binding_name = MPV._binding_name(keydef)
self.command('disable-section', binding_name)
self.command('define-section', binding_name, '')
if binding_name in self._key_binding_handlers:
del self._key_binding_handlers[binding_name]
if not self._key_binding_handlers:
self.unregister_message_handler('key-binding')
# Convenience functions
def play(self, filename):
"""Play a path or URL (requires ``ytdl`` option to be set)."""
self.loadfile(filename)
@property
def playlist_filenames(self):
"""Return all playlist item file names/URLs as a list of strs."""
return [element['filename'] for element in self.playlist]
def playlist_append(self, filename, **options):
"""Append a path or URL to the playlist. This does not start playing the file automatically. To do that, use
``MPV.loadfile(filename, 'append-play')``."""
self.loadfile(filename, 'append', **options)
# Property accessors
def _get_property(self, name, decoder=strict_decoder, fmt=MpvFormat.NODE):
out = create_string_buffer(sizeof(MpvNode))
try:
cval = _mpv_get_property(self.handle, name.encode('utf-8'), fmt, out)
if fmt is MpvFormat.OSD_STRING:
return cast(out, POINTER(c_char_p)).contents.value.decode('utf-8')
elif fmt is MpvFormat.NODE:
rv = cast(out, POINTER(MpvNode)).contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
else:
raise TypeError('_get_property only supports NODE and OSD_STRING formats.')
except PropertyUnavailableError as ex:
return None
def _set_property(self, name, value):
ename = name.encode('utf-8')
if isinstance(value, (list, set, dict)):
_1, _2, _3, pointer = _make_node_str_list(value)
_mpv_set_property(self.handle, ename, MpvFormat.NODE, pointer)
else:
_mpv_set_property_string(self.handle, ename, _mpv_coax_proptype(value))
def __getattr__(self, name):
return self._get_property(_py_to_mpv(name), lazy_decoder)
def __setattr__(self, name, value):
try:
if name != 'handle' and not name.startswith('_'):
self._set_property(_py_to_mpv(name), value)
else:
super().__setattr__(name, value)
except AttributeError:
super().__setattr__(name, value)
def __dir__(self):
return super().__dir__() + [ name.replace('-', '_') for name in self.property_list ]
@property
def properties(self):
return { name: self.option_info(name) for name in self.property_list }
# Dict-like option access
def __getitem__(self, name, file_local=False):
"""Get an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._get_property(prefix+name, lazy_decoder)
def __setitem__(self, name, value, file_local=False):
"""Set an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._set_property(prefix+name, value)
def __iter__(self):
"""Iterate over all option names."""
return iter(self.options)
def option_info(self, name):
"""Get information on the given option."""
try:
return self._get_property('option-info/'+name)
except AttributeError:
return None
|
jaseg/python-mpv | mpv.py | MPV.key_binding | python | def key_binding(self, keydef, mode='force'):
def register(fun):
fun.mpv_key_bindings = getattr(fun, 'mpv_key_bindings', []) + [keydef]
def unregister_all():
for keydef in fun.mpv_key_bindings:
self.unregister_key_binding(keydef)
fun.unregister_mpv_key_bindings = unregister_all
self.register_key_binding(keydef, fun, mode)
return fun
return register | Function decorator to register a low-level key binding.
The callback function signature is ``fun(key_state, key_name)`` where ``key_state`` is either ``'U'`` for "key
up" or ``'D'`` for "key down".
The keydef format is: ``[Shift+][Ctrl+][Alt+][Meta+]<key>`` where ``<key>`` is either the literal character the
key produces (ASCII or Unicode character), or a symbolic name (as printed by ``mpv --input-keylist``).
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.key_binding('Q')
def binding(state, name):
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
BIG FAT WARNING: mpv's key binding mechanism is pretty powerful. This means, you essentially get arbitrary code
exectution through key bindings. This interface makes some limited effort to sanitize the keydef given in the
first parameter, but YOU SHOULD NOT RELY ON THIS IN FOR SECURITY. If your input comes from config files, this is
completely fine--but, if you are about to pass untrusted input into this parameter, better double-check whether
this is secure in your case. | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L959-L996 | null | class MPV(object):
"""See man mpv(1) for the details of the implemented commands. All mpv properties can be accessed as
``my_mpv.some_property`` and all mpv options can be accessed as ``my_mpv['some-option']``.
By default, properties are returned as decoded ``str`` and an error is thrown if the value does not contain valid
utf-8. To get a decoded ``str`` if possibly but ``bytes`` instead of an error if not, use
``my_mpv.lazy.some_property``. To always get raw ``bytes``, use ``my_mpv.raw.some_property``. To access a
property's decoded OSD value, use ``my_mpv.osd.some_property``.
To get API information on an option, use ``my_mpv.option_info('option-name')``. To get API information on a
property, use ``my_mpv.properties['property-name']``. Take care to use mpv's dashed-names instead of the
underscore_names exposed on the python object.
To make your program not barf hard the first time its used on a weird file system **always** access properties
containing file names or file tags through ``MPV.raw``. """
def __init__(self, *extra_mpv_flags, log_handler=None, start_event_thread=True, loglevel=None, **extra_mpv_opts):
"""Create an MPV instance.
Extra arguments and extra keyword arguments will be passed to mpv as options.
"""
self.handle = _mpv_create()
self._event_thread = None
_mpv_set_option_string(self.handle, b'audio-display', b'no')
istr = lambda o: ('yes' if o else 'no') if type(o) is bool else str(o)
try:
for flag in extra_mpv_flags:
_mpv_set_option_string(self.handle, flag.encode('utf-8'), b'')
for k,v in extra_mpv_opts.items():
_mpv_set_option_string(self.handle, k.replace('_', '-').encode('utf-8'), istr(v).encode('utf-8'))
finally:
_mpv_initialize(self.handle)
self.osd = _OSDPropertyProxy(self)
self.file_local = _FileLocalProxy(self)
self.raw = _DecoderPropertyProxy(self, identity_decoder)
self.strict = _DecoderPropertyProxy(self, strict_decoder)
self.lazy = _DecoderPropertyProxy(self, lazy_decoder)
self._event_callbacks = []
self._property_handlers = collections.defaultdict(lambda: [])
self._message_handlers = {}
self._key_binding_handlers = {}
self._playback_cond = threading.Condition()
self._event_handle = _mpv_create_client(self.handle, b'py_event_handler')
self._loop = partial(_event_loop, self._event_handle, self._playback_cond, self._event_callbacks,
self._message_handlers, self._property_handlers, log_handler)
if loglevel is not None or log_handler is not None:
self.set_loglevel(loglevel or 'terminal-default')
if start_event_thread:
self._event_thread = threading.Thread(target=self._loop, name='MPVEventHandlerThread')
self._event_thread.setDaemon(True)
self._event_thread.start()
else:
self._event_thread = None
def wait_for_playback(self):
"""Waits until playback of the current title is paused or done."""
with self._playback_cond:
self._playback_cond.wait()
def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True):
"""Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for
properties such as ``idle_active`` indicating the player is done with regular playback and just idling around
"""
sema = threading.Semaphore(value=0)
def observer(name, val):
if cond(val):
sema.release()
self.observe_property(name, observer)
if not level_sensitive or not cond(getattr(self, name.replace('-', '_'))):
sema.acquire()
self.unobserve_property(name, observer)
def __del__(self):
if self.handle:
self.terminate()
def terminate(self):
"""Properly terminates this player instance. Preferably use this instead of relying on python's garbage
collector to cause this to be called from the object's destructor.
"""
self.handle, handle = None, self.handle
if threading.current_thread() is self._event_thread:
# Handle special case to allow event handle to be detached.
# This is necessary since otherwise the event thread would deadlock itself.
grim_reaper = threading.Thread(target=lambda: _mpv_terminate_destroy(handle))
grim_reaper.start()
else:
_mpv_terminate_destroy(handle)
if self._event_thread:
self._event_thread.join()
def set_loglevel(self, level):
"""Set MPV's log level. This adjusts which output will be sent to this object's log handlers. If you just want
mpv's regular terminal output, you don't need to adjust this but just need to pass a log handler to the MPV
constructur such as ``MPV(log_handler=print)``.
Valid log levels are "no", "fatal", "error", "warn", "info", "v" "debug" and "trace". For details see your mpv's
client.h header file.
"""
_mpv_request_log_messages(self._event_handle, level.encode('utf-8'))
def command(self, name, *args):
"""Execute a raw command."""
args = [name.encode('utf-8')] + [ (arg if type(arg) is bytes else str(arg).encode('utf-8'))
for arg in args if arg is not None ] + [None]
_mpv_command(self.handle, (c_char_p*len(args))(*args))
def node_command(self, name, *args, decoder=strict_decoder):
_1, _2, _3, pointer = _make_node_str_list([name, *args])
out = cast(create_string_buffer(sizeof(MpvNode)), POINTER(MpvNode))
ppointer = cast(pointer, POINTER(MpvNode))
_mpv_command_node(self.handle, ppointer, out)
rv = out.contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
def seek(self, amount, reference="relative", precision="default-precise"):
"""Mapped mpv seek command, see man mpv(1)."""
self.command('seek', amount, reference, precision)
def revert_seek(self):
"""Mapped mpv revert_seek command, see man mpv(1)."""
self.command('revert_seek');
def frame_step(self):
"""Mapped mpv frame_step command, see man mpv(1)."""
self.command('frame_step')
def frame_back_step(self):
"""Mapped mpv frame_back_step command, see man mpv(1)."""
self.command('frame_back_step')
def property_add(self, name, value=1):
"""Add the given value to the property's value. On overflow or underflow, clamp the property to the maximum. If
``value`` is omitted, assume ``1``.
"""
self.command('add', name, value)
def property_multiply(self, name, factor):
"""Multiply the value of a property with a numeric factor."""
self.command('multiply', name, factor)
def cycle(self, name, direction='up'):
"""Cycle the given property. ``up`` and ``down`` set the cycle direction. On overflow, set the property back to
the minimum, on underflow set it to the maximum. If ``up`` or ``down`` is omitted, assume ``up``.
"""
self.command('cycle', name, direction)
def screenshot(self, includes='subtitles', mode='single'):
"""Mapped mpv screenshot command, see man mpv(1)."""
self.command('screenshot', includes, mode)
def screenshot_to_file(self, filename, includes='subtitles'):
"""Mapped mpv screenshot_to_file command, see man mpv(1)."""
self.command('screenshot_to_file', filename.encode(fs_enc), includes)
def screenshot_raw(self, includes='subtitles'):
"""Mapped mpv screenshot_raw command, see man mpv(1). Returns a pillow Image object."""
from PIL import Image
res = self.node_command('screenshot-raw', includes)
if res['format'] != 'bgr0':
raise ValueError('Screenshot in unknown format "{}". Currently, only bgr0 is supported.'
.format(res['format']))
img = Image.frombytes('RGBA', (res['w'], res['h']), res['data'])
b,g,r,a = img.split()
return Image.merge('RGB', (r,g,b))
def playlist_next(self, mode='weak'):
"""Mapped mpv playlist_next command, see man mpv(1)."""
self.command('playlist_next', mode)
def playlist_prev(self, mode='weak'):
"""Mapped mpv playlist_prev command, see man mpv(1)."""
self.command('playlist_prev', mode)
@staticmethod
def _encode_options(options):
return ','.join('{}={}'.format(str(key), str(val)) for key, val in options.items())
def loadfile(self, filename, mode='replace', **options):
"""Mapped mpv loadfile command, see man mpv(1)."""
self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode_options(options))
def loadlist(self, playlist, mode='replace'):
"""Mapped mpv loadlist command, see man mpv(1)."""
self.command('loadlist', playlist.encode(fs_enc), mode)
def playlist_clear(self):
"""Mapped mpv playlist_clear command, see man mpv(1)."""
self.command('playlist_clear')
def playlist_remove(self, index='current'):
"""Mapped mpv playlist_remove command, see man mpv(1)."""
self.command('playlist_remove', index)
def playlist_move(self, index1, index2):
"""Mapped mpv playlist_move command, see man mpv(1)."""
self.command('playlist_move', index1, index2)
def run(self, command, *args):
"""Mapped mpv run command, see man mpv(1)."""
self.command('run', command, *args)
def quit(self, code=None):
"""Mapped mpv quit command, see man mpv(1)."""
self.command('quit', code)
def quit_watch_later(self, code=None):
"""Mapped mpv quit_watch_later command, see man mpv(1)."""
self.command('quit_watch_later', code)
def sub_add(self, filename):
"""Mapped mpv sub_add command, see man mpv(1)."""
self.command('sub_add', filename.encode(fs_enc))
def sub_remove(self, sub_id=None):
"""Mapped mpv sub_remove command, see man mpv(1)."""
self.command('sub_remove', sub_id)
def sub_reload(self, sub_id=None):
"""Mapped mpv sub_reload command, see man mpv(1)."""
self.command('sub_reload', sub_id)
def sub_step(self, skip):
"""Mapped mpv sub_step command, see man mpv(1)."""
self.command('sub_step', skip)
def sub_seek(self, skip):
"""Mapped mpv sub_seek command, see man mpv(1)."""
self.command('sub_seek', skip)
def toggle_osd(self):
"""Mapped mpv osd command, see man mpv(1)."""
self.command('osd')
def show_text(self, string, duration='-1', level=None):
"""Mapped mpv show_text command, see man mpv(1)."""
self.command('show_text', string, duration, level)
def show_progress(self):
"""Mapped mpv show_progress command, see man mpv(1)."""
self.command('show_progress')
def discnav(self, command):
"""Mapped mpv discnav command, see man mpv(1)."""
self.command('discnav', command)
def write_watch_later_config(self):
"""Mapped mpv write_watch_later_config command, see man mpv(1)."""
self.command('write_watch_later_config')
def overlay_add(self, overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride):
"""Mapped mpv overlay_add command, see man mpv(1)."""
self.command('overlay_add', overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride)
def overlay_remove(self, overlay_id):
"""Mapped mpv overlay_remove command, see man mpv(1)."""
self.command('overlay_remove', overlay_id)
def script_message(self, *args):
"""Mapped mpv script_message command, see man mpv(1)."""
self.command('script_message', *args)
def script_message_to(self, target, *args):
"""Mapped mpv script_message_to command, see man mpv(1)."""
self.command('script_message_to', target, *args)
def observe_property(self, name, handler):
"""Register an observer on the named property. An observer is a function that is called with the new property
value every time the property's value is changed. The basic function signature is ``fun(property_name,
new_value)`` with new_value being the decoded property value as a python object. This function can be used as a
function decorator if no handler is given.
To unregister the observer, call either of ``mpv.unobserve_property(name, handler)``,
``mpv.unobserve_all_properties(handler)`` or the handler's ``unregister_mpv_properties`` attribute::
@player.observe_property('volume')
def my_handler(new_volume, *):
print("It's loud!", volume)
my_handler.unregister_mpv_properties()
"""
self._property_handlers[name].append(handler)
_mpv_observe_property(self._event_handle, hash(name)&0xffffffffffffffff, name.encode('utf-8'), MpvFormat.NODE)
def property_observer(self, name):
"""Function decorator to register a property observer. See ``MPV.observe_property`` for details."""
def wrapper(fun):
self.observe_property(name, fun)
fun.unobserve_mpv_properties = lambda: self.unobserve_property(name, fun)
return fun
return wrapper
def unobserve_property(self, name, handler):
"""Unregister a property observer. This requires both the observed property's name and the handler function that
was originally registered as one handler could be registered for several properties. To unregister a handler
from *all* observed properties see ``unobserve_all_properties``.
"""
self._property_handlers[name].remove(handler)
if not self._property_handlers[name]:
_mpv_unobserve_property(self._event_handle, hash(name)&0xffffffffffffffff)
def unobserve_all_properties(self, handler):
"""Unregister a property observer from *all* observed properties."""
for name in self._property_handlers:
self.unobserve_property(name, handler)
def register_message_handler(self, target, handler=None):
"""Register a mpv script message handler. This can be used to communicate with embedded lua scripts. Pass the
script message target name this handler should be listening to and the handler function.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
self._register_message_handler_internal(target, handler)
def _register_message_handler_internal(self, target, handler):
self._message_handlers[target] = handler
def unregister_message_handler(self, target_or_handler):
"""Unregister a mpv script message handler for the given script message target name.
You can also call the ``unregister_mpv_messages`` function attribute set on the handler function when it is
registered.
"""
if isinstance(target_or_handler, str):
del self._message_handlers[target_or_handler]
else:
for key, val in self._message_handlers.items():
if val == target_or_handler:
del self._message_handlers[key]
def message_handler(self, target):
"""Decorator to register a mpv script message handler.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
def register(handler):
self._register_message_handler_internal(target, handler)
handler.unregister_mpv_messages = lambda: self.unregister_message_handler(handler)
return handler
return register
def register_event_callback(self, callback):
"""Register a blanket event callback receiving all event types.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
self._event_callbacks.append(callback)
def unregister_event_callback(self, callback):
"""Unregiser an event callback."""
self._event_callbacks.remove(callback)
def event_callback(self, *event_types):
"""Function decorator to register a blanket event callback for the given event types. Event types can be given
as str (e.g. 'start-file'), integer or MpvEventID object.
WARNING: Due to the way this is filtering events, this decorator cannot be chained with itself.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
def register(callback):
types = [MpvEventID.from_str(t) if isinstance(t, str) else t for t in event_types] or MpvEventID.ANY
@wraps(callback)
def wrapper(event, *args, **kwargs):
if event['event_id'] in types:
callback(event, *args, **kwargs)
self._event_callbacks.append(wrapper)
wrapper.unregister_mpv_events = partial(self.unregister_event_callback, wrapper)
return wrapper
return register
@staticmethod
def _binding_name(callback_or_cmd):
return 'py_kb_{:016x}'.format(hash(callback_or_cmd)&0xffffffffffffffff)
def on_key_press(self, keydef, mode='force'):
"""Function decorator to register a simplified key binding. The callback is called whenever the key given is
*pressed*.
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.on_key_press('Q')
def binding():
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
The BIG FAT WARNING regarding untrusted keydefs from the key_binding method applies here as well.
"""
def register(fun):
@self.key_binding(keydef, mode)
@wraps(fun)
def wrapper(state='p-', name=None):
if state[0] in ('d', 'p'):
fun()
return wrapper
return register
def register_key_binding(self, keydef, callback_or_cmd, mode='force'):
"""Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python
callback function. See ``MPV.key_binding`` for details.
"""
if not re.match(r'(Shift+)?(Ctrl+)?(Alt+)?(Meta+)?(.|\w+)', keydef):
raise ValueError('Invalid keydef. Expected format: [Shift+][Ctrl+][Alt+][Meta+]<key>\n'
'<key> is either the literal character the key produces (ASCII or Unicode character), or a '
'symbolic name (as printed by --input-keylist')
binding_name = MPV._binding_name(keydef)
if callable(callback_or_cmd):
self._key_binding_handlers[binding_name] = callback_or_cmd
self.register_message_handler('key-binding', self._handle_key_binding_message)
self.command('define-section',
binding_name, '{} script-binding py_event_handler/{}'.format(keydef, binding_name), mode)
elif isinstance(callback_or_cmd, str):
self.command('define-section', binding_name, '{} {}'.format(keydef, callback_or_cmd), mode)
else:
raise TypeError('register_key_binding expects either an str with an mpv command or a python callable.')
self.command('enable-section', binding_name, 'allow-hide-cursor+allow-vo-dragging')
def _handle_key_binding_message(self, binding_name, key_state, key_name=None):
self._key_binding_handlers[binding_name](key_state, key_name)
def unregister_key_binding(self, keydef):
"""Unregister a key binding by keydef."""
binding_name = MPV._binding_name(keydef)
self.command('disable-section', binding_name)
self.command('define-section', binding_name, '')
if binding_name in self._key_binding_handlers:
del self._key_binding_handlers[binding_name]
if not self._key_binding_handlers:
self.unregister_message_handler('key-binding')
# Convenience functions
def play(self, filename):
"""Play a path or URL (requires ``ytdl`` option to be set)."""
self.loadfile(filename)
@property
def playlist_filenames(self):
"""Return all playlist item file names/URLs as a list of strs."""
return [element['filename'] for element in self.playlist]
def playlist_append(self, filename, **options):
"""Append a path or URL to the playlist. This does not start playing the file automatically. To do that, use
``MPV.loadfile(filename, 'append-play')``."""
self.loadfile(filename, 'append', **options)
# Property accessors
def _get_property(self, name, decoder=strict_decoder, fmt=MpvFormat.NODE):
out = create_string_buffer(sizeof(MpvNode))
try:
cval = _mpv_get_property(self.handle, name.encode('utf-8'), fmt, out)
if fmt is MpvFormat.OSD_STRING:
return cast(out, POINTER(c_char_p)).contents.value.decode('utf-8')
elif fmt is MpvFormat.NODE:
rv = cast(out, POINTER(MpvNode)).contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
else:
raise TypeError('_get_property only supports NODE and OSD_STRING formats.')
except PropertyUnavailableError as ex:
return None
def _set_property(self, name, value):
ename = name.encode('utf-8')
if isinstance(value, (list, set, dict)):
_1, _2, _3, pointer = _make_node_str_list(value)
_mpv_set_property(self.handle, ename, MpvFormat.NODE, pointer)
else:
_mpv_set_property_string(self.handle, ename, _mpv_coax_proptype(value))
def __getattr__(self, name):
return self._get_property(_py_to_mpv(name), lazy_decoder)
def __setattr__(self, name, value):
try:
if name != 'handle' and not name.startswith('_'):
self._set_property(_py_to_mpv(name), value)
else:
super().__setattr__(name, value)
except AttributeError:
super().__setattr__(name, value)
def __dir__(self):
return super().__dir__() + [ name.replace('-', '_') for name in self.property_list ]
@property
def properties(self):
return { name: self.option_info(name) for name in self.property_list }
# Dict-like option access
def __getitem__(self, name, file_local=False):
"""Get an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._get_property(prefix+name, lazy_decoder)
def __setitem__(self, name, value, file_local=False):
"""Set an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._set_property(prefix+name, value)
def __iter__(self):
"""Iterate over all option names."""
return iter(self.options)
def option_info(self, name):
"""Get information on the given option."""
try:
return self._get_property('option-info/'+name)
except AttributeError:
return None
|
jaseg/python-mpv | mpv.py | MPV.register_key_binding | python | def register_key_binding(self, keydef, callback_or_cmd, mode='force'):
if not re.match(r'(Shift+)?(Ctrl+)?(Alt+)?(Meta+)?(.|\w+)', keydef):
raise ValueError('Invalid keydef. Expected format: [Shift+][Ctrl+][Alt+][Meta+]<key>\n'
'<key> is either the literal character the key produces (ASCII or Unicode character), or a '
'symbolic name (as printed by --input-keylist')
binding_name = MPV._binding_name(keydef)
if callable(callback_or_cmd):
self._key_binding_handlers[binding_name] = callback_or_cmd
self.register_message_handler('key-binding', self._handle_key_binding_message)
self.command('define-section',
binding_name, '{} script-binding py_event_handler/{}'.format(keydef, binding_name), mode)
elif isinstance(callback_or_cmd, str):
self.command('define-section', binding_name, '{} {}'.format(keydef, callback_or_cmd), mode)
else:
raise TypeError('register_key_binding expects either an str with an mpv command or a python callable.')
self.command('enable-section', binding_name, 'allow-hide-cursor+allow-vo-dragging') | Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python
callback function. See ``MPV.key_binding`` for details. | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L998-L1016 | null | class MPV(object):
"""See man mpv(1) for the details of the implemented commands. All mpv properties can be accessed as
``my_mpv.some_property`` and all mpv options can be accessed as ``my_mpv['some-option']``.
By default, properties are returned as decoded ``str`` and an error is thrown if the value does not contain valid
utf-8. To get a decoded ``str`` if possibly but ``bytes`` instead of an error if not, use
``my_mpv.lazy.some_property``. To always get raw ``bytes``, use ``my_mpv.raw.some_property``. To access a
property's decoded OSD value, use ``my_mpv.osd.some_property``.
To get API information on an option, use ``my_mpv.option_info('option-name')``. To get API information on a
property, use ``my_mpv.properties['property-name']``. Take care to use mpv's dashed-names instead of the
underscore_names exposed on the python object.
To make your program not barf hard the first time its used on a weird file system **always** access properties
containing file names or file tags through ``MPV.raw``. """
def __init__(self, *extra_mpv_flags, log_handler=None, start_event_thread=True, loglevel=None, **extra_mpv_opts):
"""Create an MPV instance.
Extra arguments and extra keyword arguments will be passed to mpv as options.
"""
self.handle = _mpv_create()
self._event_thread = None
_mpv_set_option_string(self.handle, b'audio-display', b'no')
istr = lambda o: ('yes' if o else 'no') if type(o) is bool else str(o)
try:
for flag in extra_mpv_flags:
_mpv_set_option_string(self.handle, flag.encode('utf-8'), b'')
for k,v in extra_mpv_opts.items():
_mpv_set_option_string(self.handle, k.replace('_', '-').encode('utf-8'), istr(v).encode('utf-8'))
finally:
_mpv_initialize(self.handle)
self.osd = _OSDPropertyProxy(self)
self.file_local = _FileLocalProxy(self)
self.raw = _DecoderPropertyProxy(self, identity_decoder)
self.strict = _DecoderPropertyProxy(self, strict_decoder)
self.lazy = _DecoderPropertyProxy(self, lazy_decoder)
self._event_callbacks = []
self._property_handlers = collections.defaultdict(lambda: [])
self._message_handlers = {}
self._key_binding_handlers = {}
self._playback_cond = threading.Condition()
self._event_handle = _mpv_create_client(self.handle, b'py_event_handler')
self._loop = partial(_event_loop, self._event_handle, self._playback_cond, self._event_callbacks,
self._message_handlers, self._property_handlers, log_handler)
if loglevel is not None or log_handler is not None:
self.set_loglevel(loglevel or 'terminal-default')
if start_event_thread:
self._event_thread = threading.Thread(target=self._loop, name='MPVEventHandlerThread')
self._event_thread.setDaemon(True)
self._event_thread.start()
else:
self._event_thread = None
def wait_for_playback(self):
"""Waits until playback of the current title is paused or done."""
with self._playback_cond:
self._playback_cond.wait()
def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True):
"""Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for
properties such as ``idle_active`` indicating the player is done with regular playback and just idling around
"""
sema = threading.Semaphore(value=0)
def observer(name, val):
if cond(val):
sema.release()
self.observe_property(name, observer)
if not level_sensitive or not cond(getattr(self, name.replace('-', '_'))):
sema.acquire()
self.unobserve_property(name, observer)
def __del__(self):
if self.handle:
self.terminate()
def terminate(self):
"""Properly terminates this player instance. Preferably use this instead of relying on python's garbage
collector to cause this to be called from the object's destructor.
"""
self.handle, handle = None, self.handle
if threading.current_thread() is self._event_thread:
# Handle special case to allow event handle to be detached.
# This is necessary since otherwise the event thread would deadlock itself.
grim_reaper = threading.Thread(target=lambda: _mpv_terminate_destroy(handle))
grim_reaper.start()
else:
_mpv_terminate_destroy(handle)
if self._event_thread:
self._event_thread.join()
def set_loglevel(self, level):
"""Set MPV's log level. This adjusts which output will be sent to this object's log handlers. If you just want
mpv's regular terminal output, you don't need to adjust this but just need to pass a log handler to the MPV
constructur such as ``MPV(log_handler=print)``.
Valid log levels are "no", "fatal", "error", "warn", "info", "v" "debug" and "trace". For details see your mpv's
client.h header file.
"""
_mpv_request_log_messages(self._event_handle, level.encode('utf-8'))
def command(self, name, *args):
"""Execute a raw command."""
args = [name.encode('utf-8')] + [ (arg if type(arg) is bytes else str(arg).encode('utf-8'))
for arg in args if arg is not None ] + [None]
_mpv_command(self.handle, (c_char_p*len(args))(*args))
def node_command(self, name, *args, decoder=strict_decoder):
_1, _2, _3, pointer = _make_node_str_list([name, *args])
out = cast(create_string_buffer(sizeof(MpvNode)), POINTER(MpvNode))
ppointer = cast(pointer, POINTER(MpvNode))
_mpv_command_node(self.handle, ppointer, out)
rv = out.contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
def seek(self, amount, reference="relative", precision="default-precise"):
"""Mapped mpv seek command, see man mpv(1)."""
self.command('seek', amount, reference, precision)
def revert_seek(self):
"""Mapped mpv revert_seek command, see man mpv(1)."""
self.command('revert_seek');
def frame_step(self):
"""Mapped mpv frame_step command, see man mpv(1)."""
self.command('frame_step')
def frame_back_step(self):
"""Mapped mpv frame_back_step command, see man mpv(1)."""
self.command('frame_back_step')
def property_add(self, name, value=1):
"""Add the given value to the property's value. On overflow or underflow, clamp the property to the maximum. If
``value`` is omitted, assume ``1``.
"""
self.command('add', name, value)
def property_multiply(self, name, factor):
"""Multiply the value of a property with a numeric factor."""
self.command('multiply', name, factor)
def cycle(self, name, direction='up'):
"""Cycle the given property. ``up`` and ``down`` set the cycle direction. On overflow, set the property back to
the minimum, on underflow set it to the maximum. If ``up`` or ``down`` is omitted, assume ``up``.
"""
self.command('cycle', name, direction)
def screenshot(self, includes='subtitles', mode='single'):
"""Mapped mpv screenshot command, see man mpv(1)."""
self.command('screenshot', includes, mode)
def screenshot_to_file(self, filename, includes='subtitles'):
"""Mapped mpv screenshot_to_file command, see man mpv(1)."""
self.command('screenshot_to_file', filename.encode(fs_enc), includes)
def screenshot_raw(self, includes='subtitles'):
"""Mapped mpv screenshot_raw command, see man mpv(1). Returns a pillow Image object."""
from PIL import Image
res = self.node_command('screenshot-raw', includes)
if res['format'] != 'bgr0':
raise ValueError('Screenshot in unknown format "{}". Currently, only bgr0 is supported.'
.format(res['format']))
img = Image.frombytes('RGBA', (res['w'], res['h']), res['data'])
b,g,r,a = img.split()
return Image.merge('RGB', (r,g,b))
def playlist_next(self, mode='weak'):
"""Mapped mpv playlist_next command, see man mpv(1)."""
self.command('playlist_next', mode)
def playlist_prev(self, mode='weak'):
"""Mapped mpv playlist_prev command, see man mpv(1)."""
self.command('playlist_prev', mode)
@staticmethod
def _encode_options(options):
return ','.join('{}={}'.format(str(key), str(val)) for key, val in options.items())
def loadfile(self, filename, mode='replace', **options):
"""Mapped mpv loadfile command, see man mpv(1)."""
self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode_options(options))
def loadlist(self, playlist, mode='replace'):
"""Mapped mpv loadlist command, see man mpv(1)."""
self.command('loadlist', playlist.encode(fs_enc), mode)
def playlist_clear(self):
"""Mapped mpv playlist_clear command, see man mpv(1)."""
self.command('playlist_clear')
def playlist_remove(self, index='current'):
"""Mapped mpv playlist_remove command, see man mpv(1)."""
self.command('playlist_remove', index)
def playlist_move(self, index1, index2):
"""Mapped mpv playlist_move command, see man mpv(1)."""
self.command('playlist_move', index1, index2)
def run(self, command, *args):
"""Mapped mpv run command, see man mpv(1)."""
self.command('run', command, *args)
def quit(self, code=None):
"""Mapped mpv quit command, see man mpv(1)."""
self.command('quit', code)
def quit_watch_later(self, code=None):
"""Mapped mpv quit_watch_later command, see man mpv(1)."""
self.command('quit_watch_later', code)
def sub_add(self, filename):
"""Mapped mpv sub_add command, see man mpv(1)."""
self.command('sub_add', filename.encode(fs_enc))
def sub_remove(self, sub_id=None):
"""Mapped mpv sub_remove command, see man mpv(1)."""
self.command('sub_remove', sub_id)
def sub_reload(self, sub_id=None):
"""Mapped mpv sub_reload command, see man mpv(1)."""
self.command('sub_reload', sub_id)
def sub_step(self, skip):
"""Mapped mpv sub_step command, see man mpv(1)."""
self.command('sub_step', skip)
def sub_seek(self, skip):
"""Mapped mpv sub_seek command, see man mpv(1)."""
self.command('sub_seek', skip)
def toggle_osd(self):
"""Mapped mpv osd command, see man mpv(1)."""
self.command('osd')
def show_text(self, string, duration='-1', level=None):
"""Mapped mpv show_text command, see man mpv(1)."""
self.command('show_text', string, duration, level)
def show_progress(self):
"""Mapped mpv show_progress command, see man mpv(1)."""
self.command('show_progress')
def discnav(self, command):
"""Mapped mpv discnav command, see man mpv(1)."""
self.command('discnav', command)
def write_watch_later_config(self):
"""Mapped mpv write_watch_later_config command, see man mpv(1)."""
self.command('write_watch_later_config')
def overlay_add(self, overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride):
"""Mapped mpv overlay_add command, see man mpv(1)."""
self.command('overlay_add', overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride)
def overlay_remove(self, overlay_id):
"""Mapped mpv overlay_remove command, see man mpv(1)."""
self.command('overlay_remove', overlay_id)
def script_message(self, *args):
"""Mapped mpv script_message command, see man mpv(1)."""
self.command('script_message', *args)
def script_message_to(self, target, *args):
"""Mapped mpv script_message_to command, see man mpv(1)."""
self.command('script_message_to', target, *args)
def observe_property(self, name, handler):
"""Register an observer on the named property. An observer is a function that is called with the new property
value every time the property's value is changed. The basic function signature is ``fun(property_name,
new_value)`` with new_value being the decoded property value as a python object. This function can be used as a
function decorator if no handler is given.
To unregister the observer, call either of ``mpv.unobserve_property(name, handler)``,
``mpv.unobserve_all_properties(handler)`` or the handler's ``unregister_mpv_properties`` attribute::
@player.observe_property('volume')
def my_handler(new_volume, *):
print("It's loud!", volume)
my_handler.unregister_mpv_properties()
"""
self._property_handlers[name].append(handler)
_mpv_observe_property(self._event_handle, hash(name)&0xffffffffffffffff, name.encode('utf-8'), MpvFormat.NODE)
def property_observer(self, name):
"""Function decorator to register a property observer. See ``MPV.observe_property`` for details."""
def wrapper(fun):
self.observe_property(name, fun)
fun.unobserve_mpv_properties = lambda: self.unobserve_property(name, fun)
return fun
return wrapper
def unobserve_property(self, name, handler):
"""Unregister a property observer. This requires both the observed property's name and the handler function that
was originally registered as one handler could be registered for several properties. To unregister a handler
from *all* observed properties see ``unobserve_all_properties``.
"""
self._property_handlers[name].remove(handler)
if not self._property_handlers[name]:
_mpv_unobserve_property(self._event_handle, hash(name)&0xffffffffffffffff)
def unobserve_all_properties(self, handler):
"""Unregister a property observer from *all* observed properties."""
for name in self._property_handlers:
self.unobserve_property(name, handler)
def register_message_handler(self, target, handler=None):
"""Register a mpv script message handler. This can be used to communicate with embedded lua scripts. Pass the
script message target name this handler should be listening to and the handler function.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
self._register_message_handler_internal(target, handler)
def _register_message_handler_internal(self, target, handler):
self._message_handlers[target] = handler
def unregister_message_handler(self, target_or_handler):
"""Unregister a mpv script message handler for the given script message target name.
You can also call the ``unregister_mpv_messages`` function attribute set on the handler function when it is
registered.
"""
if isinstance(target_or_handler, str):
del self._message_handlers[target_or_handler]
else:
for key, val in self._message_handlers.items():
if val == target_or_handler:
del self._message_handlers[key]
def message_handler(self, target):
"""Decorator to register a mpv script message handler.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
def register(handler):
self._register_message_handler_internal(target, handler)
handler.unregister_mpv_messages = lambda: self.unregister_message_handler(handler)
return handler
return register
def register_event_callback(self, callback):
"""Register a blanket event callback receiving all event types.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
self._event_callbacks.append(callback)
def unregister_event_callback(self, callback):
"""Unregiser an event callback."""
self._event_callbacks.remove(callback)
def event_callback(self, *event_types):
"""Function decorator to register a blanket event callback for the given event types. Event types can be given
as str (e.g. 'start-file'), integer or MpvEventID object.
WARNING: Due to the way this is filtering events, this decorator cannot be chained with itself.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
def register(callback):
types = [MpvEventID.from_str(t) if isinstance(t, str) else t for t in event_types] or MpvEventID.ANY
@wraps(callback)
def wrapper(event, *args, **kwargs):
if event['event_id'] in types:
callback(event, *args, **kwargs)
self._event_callbacks.append(wrapper)
wrapper.unregister_mpv_events = partial(self.unregister_event_callback, wrapper)
return wrapper
return register
@staticmethod
def _binding_name(callback_or_cmd):
return 'py_kb_{:016x}'.format(hash(callback_or_cmd)&0xffffffffffffffff)
def on_key_press(self, keydef, mode='force'):
"""Function decorator to register a simplified key binding. The callback is called whenever the key given is
*pressed*.
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.on_key_press('Q')
def binding():
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
The BIG FAT WARNING regarding untrusted keydefs from the key_binding method applies here as well.
"""
def register(fun):
@self.key_binding(keydef, mode)
@wraps(fun)
def wrapper(state='p-', name=None):
if state[0] in ('d', 'p'):
fun()
return wrapper
return register
def key_binding(self, keydef, mode='force'):
"""Function decorator to register a low-level key binding.
The callback function signature is ``fun(key_state, key_name)`` where ``key_state`` is either ``'U'`` for "key
up" or ``'D'`` for "key down".
The keydef format is: ``[Shift+][Ctrl+][Alt+][Meta+]<key>`` where ``<key>`` is either the literal character the
key produces (ASCII or Unicode character), or a symbolic name (as printed by ``mpv --input-keylist``).
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.key_binding('Q')
def binding(state, name):
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
BIG FAT WARNING: mpv's key binding mechanism is pretty powerful. This means, you essentially get arbitrary code
exectution through key bindings. This interface makes some limited effort to sanitize the keydef given in the
first parameter, but YOU SHOULD NOT RELY ON THIS IN FOR SECURITY. If your input comes from config files, this is
completely fine--but, if you are about to pass untrusted input into this parameter, better double-check whether
this is secure in your case.
"""
def register(fun):
fun.mpv_key_bindings = getattr(fun, 'mpv_key_bindings', []) + [keydef]
def unregister_all():
for keydef in fun.mpv_key_bindings:
self.unregister_key_binding(keydef)
fun.unregister_mpv_key_bindings = unregister_all
self.register_key_binding(keydef, fun, mode)
return fun
return register
def _handle_key_binding_message(self, binding_name, key_state, key_name=None):
self._key_binding_handlers[binding_name](key_state, key_name)
def unregister_key_binding(self, keydef):
"""Unregister a key binding by keydef."""
binding_name = MPV._binding_name(keydef)
self.command('disable-section', binding_name)
self.command('define-section', binding_name, '')
if binding_name in self._key_binding_handlers:
del self._key_binding_handlers[binding_name]
if not self._key_binding_handlers:
self.unregister_message_handler('key-binding')
# Convenience functions
def play(self, filename):
"""Play a path or URL (requires ``ytdl`` option to be set)."""
self.loadfile(filename)
@property
def playlist_filenames(self):
"""Return all playlist item file names/URLs as a list of strs."""
return [element['filename'] for element in self.playlist]
def playlist_append(self, filename, **options):
"""Append a path or URL to the playlist. This does not start playing the file automatically. To do that, use
``MPV.loadfile(filename, 'append-play')``."""
self.loadfile(filename, 'append', **options)
# Property accessors
def _get_property(self, name, decoder=strict_decoder, fmt=MpvFormat.NODE):
out = create_string_buffer(sizeof(MpvNode))
try:
cval = _mpv_get_property(self.handle, name.encode('utf-8'), fmt, out)
if fmt is MpvFormat.OSD_STRING:
return cast(out, POINTER(c_char_p)).contents.value.decode('utf-8')
elif fmt is MpvFormat.NODE:
rv = cast(out, POINTER(MpvNode)).contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
else:
raise TypeError('_get_property only supports NODE and OSD_STRING formats.')
except PropertyUnavailableError as ex:
return None
def _set_property(self, name, value):
ename = name.encode('utf-8')
if isinstance(value, (list, set, dict)):
_1, _2, _3, pointer = _make_node_str_list(value)
_mpv_set_property(self.handle, ename, MpvFormat.NODE, pointer)
else:
_mpv_set_property_string(self.handle, ename, _mpv_coax_proptype(value))
def __getattr__(self, name):
return self._get_property(_py_to_mpv(name), lazy_decoder)
def __setattr__(self, name, value):
try:
if name != 'handle' and not name.startswith('_'):
self._set_property(_py_to_mpv(name), value)
else:
super().__setattr__(name, value)
except AttributeError:
super().__setattr__(name, value)
def __dir__(self):
return super().__dir__() + [ name.replace('-', '_') for name in self.property_list ]
@property
def properties(self):
return { name: self.option_info(name) for name in self.property_list }
# Dict-like option access
def __getitem__(self, name, file_local=False):
"""Get an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._get_property(prefix+name, lazy_decoder)
def __setitem__(self, name, value, file_local=False):
"""Set an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._set_property(prefix+name, value)
def __iter__(self):
"""Iterate over all option names."""
return iter(self.options)
def option_info(self, name):
"""Get information on the given option."""
try:
return self._get_property('option-info/'+name)
except AttributeError:
return None
|
jaseg/python-mpv | mpv.py | MPV.unregister_key_binding | python | def unregister_key_binding(self, keydef):
binding_name = MPV._binding_name(keydef)
self.command('disable-section', binding_name)
self.command('define-section', binding_name, '')
if binding_name in self._key_binding_handlers:
del self._key_binding_handlers[binding_name]
if not self._key_binding_handlers:
self.unregister_message_handler('key-binding') | Unregister a key binding by keydef. | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L1021-L1029 | null | class MPV(object):
"""See man mpv(1) for the details of the implemented commands. All mpv properties can be accessed as
``my_mpv.some_property`` and all mpv options can be accessed as ``my_mpv['some-option']``.
By default, properties are returned as decoded ``str`` and an error is thrown if the value does not contain valid
utf-8. To get a decoded ``str`` if possibly but ``bytes`` instead of an error if not, use
``my_mpv.lazy.some_property``. To always get raw ``bytes``, use ``my_mpv.raw.some_property``. To access a
property's decoded OSD value, use ``my_mpv.osd.some_property``.
To get API information on an option, use ``my_mpv.option_info('option-name')``. To get API information on a
property, use ``my_mpv.properties['property-name']``. Take care to use mpv's dashed-names instead of the
underscore_names exposed on the python object.
To make your program not barf hard the first time its used on a weird file system **always** access properties
containing file names or file tags through ``MPV.raw``. """
def __init__(self, *extra_mpv_flags, log_handler=None, start_event_thread=True, loglevel=None, **extra_mpv_opts):
"""Create an MPV instance.
Extra arguments and extra keyword arguments will be passed to mpv as options.
"""
self.handle = _mpv_create()
self._event_thread = None
_mpv_set_option_string(self.handle, b'audio-display', b'no')
istr = lambda o: ('yes' if o else 'no') if type(o) is bool else str(o)
try:
for flag in extra_mpv_flags:
_mpv_set_option_string(self.handle, flag.encode('utf-8'), b'')
for k,v in extra_mpv_opts.items():
_mpv_set_option_string(self.handle, k.replace('_', '-').encode('utf-8'), istr(v).encode('utf-8'))
finally:
_mpv_initialize(self.handle)
self.osd = _OSDPropertyProxy(self)
self.file_local = _FileLocalProxy(self)
self.raw = _DecoderPropertyProxy(self, identity_decoder)
self.strict = _DecoderPropertyProxy(self, strict_decoder)
self.lazy = _DecoderPropertyProxy(self, lazy_decoder)
self._event_callbacks = []
self._property_handlers = collections.defaultdict(lambda: [])
self._message_handlers = {}
self._key_binding_handlers = {}
self._playback_cond = threading.Condition()
self._event_handle = _mpv_create_client(self.handle, b'py_event_handler')
self._loop = partial(_event_loop, self._event_handle, self._playback_cond, self._event_callbacks,
self._message_handlers, self._property_handlers, log_handler)
if loglevel is not None or log_handler is not None:
self.set_loglevel(loglevel or 'terminal-default')
if start_event_thread:
self._event_thread = threading.Thread(target=self._loop, name='MPVEventHandlerThread')
self._event_thread.setDaemon(True)
self._event_thread.start()
else:
self._event_thread = None
def wait_for_playback(self):
"""Waits until playback of the current title is paused or done."""
with self._playback_cond:
self._playback_cond.wait()
def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True):
"""Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for
properties such as ``idle_active`` indicating the player is done with regular playback and just idling around
"""
sema = threading.Semaphore(value=0)
def observer(name, val):
if cond(val):
sema.release()
self.observe_property(name, observer)
if not level_sensitive or not cond(getattr(self, name.replace('-', '_'))):
sema.acquire()
self.unobserve_property(name, observer)
def __del__(self):
if self.handle:
self.terminate()
def terminate(self):
"""Properly terminates this player instance. Preferably use this instead of relying on python's garbage
collector to cause this to be called from the object's destructor.
"""
self.handle, handle = None, self.handle
if threading.current_thread() is self._event_thread:
# Handle special case to allow event handle to be detached.
# This is necessary since otherwise the event thread would deadlock itself.
grim_reaper = threading.Thread(target=lambda: _mpv_terminate_destroy(handle))
grim_reaper.start()
else:
_mpv_terminate_destroy(handle)
if self._event_thread:
self._event_thread.join()
def set_loglevel(self, level):
"""Set MPV's log level. This adjusts which output will be sent to this object's log handlers. If you just want
mpv's regular terminal output, you don't need to adjust this but just need to pass a log handler to the MPV
constructur such as ``MPV(log_handler=print)``.
Valid log levels are "no", "fatal", "error", "warn", "info", "v" "debug" and "trace". For details see your mpv's
client.h header file.
"""
_mpv_request_log_messages(self._event_handle, level.encode('utf-8'))
def command(self, name, *args):
"""Execute a raw command."""
args = [name.encode('utf-8')] + [ (arg if type(arg) is bytes else str(arg).encode('utf-8'))
for arg in args if arg is not None ] + [None]
_mpv_command(self.handle, (c_char_p*len(args))(*args))
def node_command(self, name, *args, decoder=strict_decoder):
_1, _2, _3, pointer = _make_node_str_list([name, *args])
out = cast(create_string_buffer(sizeof(MpvNode)), POINTER(MpvNode))
ppointer = cast(pointer, POINTER(MpvNode))
_mpv_command_node(self.handle, ppointer, out)
rv = out.contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
def seek(self, amount, reference="relative", precision="default-precise"):
"""Mapped mpv seek command, see man mpv(1)."""
self.command('seek', amount, reference, precision)
def revert_seek(self):
"""Mapped mpv revert_seek command, see man mpv(1)."""
self.command('revert_seek');
def frame_step(self):
"""Mapped mpv frame_step command, see man mpv(1)."""
self.command('frame_step')
def frame_back_step(self):
"""Mapped mpv frame_back_step command, see man mpv(1)."""
self.command('frame_back_step')
def property_add(self, name, value=1):
"""Add the given value to the property's value. On overflow or underflow, clamp the property to the maximum. If
``value`` is omitted, assume ``1``.
"""
self.command('add', name, value)
def property_multiply(self, name, factor):
"""Multiply the value of a property with a numeric factor."""
self.command('multiply', name, factor)
def cycle(self, name, direction='up'):
"""Cycle the given property. ``up`` and ``down`` set the cycle direction. On overflow, set the property back to
the minimum, on underflow set it to the maximum. If ``up`` or ``down`` is omitted, assume ``up``.
"""
self.command('cycle', name, direction)
def screenshot(self, includes='subtitles', mode='single'):
"""Mapped mpv screenshot command, see man mpv(1)."""
self.command('screenshot', includes, mode)
def screenshot_to_file(self, filename, includes='subtitles'):
"""Mapped mpv screenshot_to_file command, see man mpv(1)."""
self.command('screenshot_to_file', filename.encode(fs_enc), includes)
def screenshot_raw(self, includes='subtitles'):
"""Mapped mpv screenshot_raw command, see man mpv(1). Returns a pillow Image object."""
from PIL import Image
res = self.node_command('screenshot-raw', includes)
if res['format'] != 'bgr0':
raise ValueError('Screenshot in unknown format "{}". Currently, only bgr0 is supported.'
.format(res['format']))
img = Image.frombytes('RGBA', (res['w'], res['h']), res['data'])
b,g,r,a = img.split()
return Image.merge('RGB', (r,g,b))
def playlist_next(self, mode='weak'):
"""Mapped mpv playlist_next command, see man mpv(1)."""
self.command('playlist_next', mode)
def playlist_prev(self, mode='weak'):
"""Mapped mpv playlist_prev command, see man mpv(1)."""
self.command('playlist_prev', mode)
@staticmethod
def _encode_options(options):
return ','.join('{}={}'.format(str(key), str(val)) for key, val in options.items())
def loadfile(self, filename, mode='replace', **options):
"""Mapped mpv loadfile command, see man mpv(1)."""
self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode_options(options))
def loadlist(self, playlist, mode='replace'):
"""Mapped mpv loadlist command, see man mpv(1)."""
self.command('loadlist', playlist.encode(fs_enc), mode)
def playlist_clear(self):
"""Mapped mpv playlist_clear command, see man mpv(1)."""
self.command('playlist_clear')
def playlist_remove(self, index='current'):
"""Mapped mpv playlist_remove command, see man mpv(1)."""
self.command('playlist_remove', index)
def playlist_move(self, index1, index2):
"""Mapped mpv playlist_move command, see man mpv(1)."""
self.command('playlist_move', index1, index2)
def run(self, command, *args):
"""Mapped mpv run command, see man mpv(1)."""
self.command('run', command, *args)
def quit(self, code=None):
"""Mapped mpv quit command, see man mpv(1)."""
self.command('quit', code)
def quit_watch_later(self, code=None):
"""Mapped mpv quit_watch_later command, see man mpv(1)."""
self.command('quit_watch_later', code)
def sub_add(self, filename):
"""Mapped mpv sub_add command, see man mpv(1)."""
self.command('sub_add', filename.encode(fs_enc))
def sub_remove(self, sub_id=None):
"""Mapped mpv sub_remove command, see man mpv(1)."""
self.command('sub_remove', sub_id)
def sub_reload(self, sub_id=None):
"""Mapped mpv sub_reload command, see man mpv(1)."""
self.command('sub_reload', sub_id)
def sub_step(self, skip):
"""Mapped mpv sub_step command, see man mpv(1)."""
self.command('sub_step', skip)
def sub_seek(self, skip):
"""Mapped mpv sub_seek command, see man mpv(1)."""
self.command('sub_seek', skip)
def toggle_osd(self):
"""Mapped mpv osd command, see man mpv(1)."""
self.command('osd')
def show_text(self, string, duration='-1', level=None):
"""Mapped mpv show_text command, see man mpv(1)."""
self.command('show_text', string, duration, level)
def show_progress(self):
"""Mapped mpv show_progress command, see man mpv(1)."""
self.command('show_progress')
def discnav(self, command):
"""Mapped mpv discnav command, see man mpv(1)."""
self.command('discnav', command)
def write_watch_later_config(self):
"""Mapped mpv write_watch_later_config command, see man mpv(1)."""
self.command('write_watch_later_config')
def overlay_add(self, overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride):
"""Mapped mpv overlay_add command, see man mpv(1)."""
self.command('overlay_add', overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride)
def overlay_remove(self, overlay_id):
"""Mapped mpv overlay_remove command, see man mpv(1)."""
self.command('overlay_remove', overlay_id)
def script_message(self, *args):
"""Mapped mpv script_message command, see man mpv(1)."""
self.command('script_message', *args)
def script_message_to(self, target, *args):
"""Mapped mpv script_message_to command, see man mpv(1)."""
self.command('script_message_to', target, *args)
def observe_property(self, name, handler):
"""Register an observer on the named property. An observer is a function that is called with the new property
value every time the property's value is changed. The basic function signature is ``fun(property_name,
new_value)`` with new_value being the decoded property value as a python object. This function can be used as a
function decorator if no handler is given.
To unregister the observer, call either of ``mpv.unobserve_property(name, handler)``,
``mpv.unobserve_all_properties(handler)`` or the handler's ``unregister_mpv_properties`` attribute::
@player.observe_property('volume')
def my_handler(new_volume, *):
print("It's loud!", volume)
my_handler.unregister_mpv_properties()
"""
self._property_handlers[name].append(handler)
_mpv_observe_property(self._event_handle, hash(name)&0xffffffffffffffff, name.encode('utf-8'), MpvFormat.NODE)
def property_observer(self, name):
"""Function decorator to register a property observer. See ``MPV.observe_property`` for details."""
def wrapper(fun):
self.observe_property(name, fun)
fun.unobserve_mpv_properties = lambda: self.unobserve_property(name, fun)
return fun
return wrapper
def unobserve_property(self, name, handler):
"""Unregister a property observer. This requires both the observed property's name and the handler function that
was originally registered as one handler could be registered for several properties. To unregister a handler
from *all* observed properties see ``unobserve_all_properties``.
"""
self._property_handlers[name].remove(handler)
if not self._property_handlers[name]:
_mpv_unobserve_property(self._event_handle, hash(name)&0xffffffffffffffff)
def unobserve_all_properties(self, handler):
"""Unregister a property observer from *all* observed properties."""
for name in self._property_handlers:
self.unobserve_property(name, handler)
def register_message_handler(self, target, handler=None):
"""Register a mpv script message handler. This can be used to communicate with embedded lua scripts. Pass the
script message target name this handler should be listening to and the handler function.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
self._register_message_handler_internal(target, handler)
def _register_message_handler_internal(self, target, handler):
self._message_handlers[target] = handler
def unregister_message_handler(self, target_or_handler):
"""Unregister a mpv script message handler for the given script message target name.
You can also call the ``unregister_mpv_messages`` function attribute set on the handler function when it is
registered.
"""
if isinstance(target_or_handler, str):
del self._message_handlers[target_or_handler]
else:
for key, val in self._message_handlers.items():
if val == target_or_handler:
del self._message_handlers[key]
def message_handler(self, target):
"""Decorator to register a mpv script message handler.
WARNING: Only one handler can be registered at a time for any given target.
To unregister the message handler, call its ``unregister_mpv_messages`` function::
player = mpv.MPV()
@player.message_handler('foo')
def my_handler(some, args):
print(args)
my_handler.unregister_mpv_messages()
"""
def register(handler):
self._register_message_handler_internal(target, handler)
handler.unregister_mpv_messages = lambda: self.unregister_message_handler(handler)
return handler
return register
def register_event_callback(self, callback):
"""Register a blanket event callback receiving all event types.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
self._event_callbacks.append(callback)
def unregister_event_callback(self, callback):
"""Unregiser an event callback."""
self._event_callbacks.remove(callback)
def event_callback(self, *event_types):
"""Function decorator to register a blanket event callback for the given event types. Event types can be given
as str (e.g. 'start-file'), integer or MpvEventID object.
WARNING: Due to the way this is filtering events, this decorator cannot be chained with itself.
To unregister the event callback, call its ``unregister_mpv_events`` function::
player = mpv.MPV()
@player.event_callback('shutdown')
def my_handler(event):
print('It ded.')
my_handler.unregister_mpv_events()
"""
def register(callback):
types = [MpvEventID.from_str(t) if isinstance(t, str) else t for t in event_types] or MpvEventID.ANY
@wraps(callback)
def wrapper(event, *args, **kwargs):
if event['event_id'] in types:
callback(event, *args, **kwargs)
self._event_callbacks.append(wrapper)
wrapper.unregister_mpv_events = partial(self.unregister_event_callback, wrapper)
return wrapper
return register
@staticmethod
def _binding_name(callback_or_cmd):
return 'py_kb_{:016x}'.format(hash(callback_or_cmd)&0xffffffffffffffff)
def on_key_press(self, keydef, mode='force'):
"""Function decorator to register a simplified key binding. The callback is called whenever the key given is
*pressed*.
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.on_key_press('Q')
def binding():
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
The BIG FAT WARNING regarding untrusted keydefs from the key_binding method applies here as well.
"""
def register(fun):
@self.key_binding(keydef, mode)
@wraps(fun)
def wrapper(state='p-', name=None):
if state[0] in ('d', 'p'):
fun()
return wrapper
return register
def key_binding(self, keydef, mode='force'):
"""Function decorator to register a low-level key binding.
The callback function signature is ``fun(key_state, key_name)`` where ``key_state`` is either ``'U'`` for "key
up" or ``'D'`` for "key down".
The keydef format is: ``[Shift+][Ctrl+][Alt+][Meta+]<key>`` where ``<key>`` is either the literal character the
key produces (ASCII or Unicode character), or a symbolic name (as printed by ``mpv --input-keylist``).
To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
player = mpv.MPV()
@player.key_binding('Q')
def binding(state, name):
print('blep')
binding.unregister_mpv_key_bindings()
WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
don't do that.
BIG FAT WARNING: mpv's key binding mechanism is pretty powerful. This means, you essentially get arbitrary code
exectution through key bindings. This interface makes some limited effort to sanitize the keydef given in the
first parameter, but YOU SHOULD NOT RELY ON THIS IN FOR SECURITY. If your input comes from config files, this is
completely fine--but, if you are about to pass untrusted input into this parameter, better double-check whether
this is secure in your case.
"""
def register(fun):
fun.mpv_key_bindings = getattr(fun, 'mpv_key_bindings', []) + [keydef]
def unregister_all():
for keydef in fun.mpv_key_bindings:
self.unregister_key_binding(keydef)
fun.unregister_mpv_key_bindings = unregister_all
self.register_key_binding(keydef, fun, mode)
return fun
return register
def register_key_binding(self, keydef, callback_or_cmd, mode='force'):
"""Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python
callback function. See ``MPV.key_binding`` for details.
"""
if not re.match(r'(Shift+)?(Ctrl+)?(Alt+)?(Meta+)?(.|\w+)', keydef):
raise ValueError('Invalid keydef. Expected format: [Shift+][Ctrl+][Alt+][Meta+]<key>\n'
'<key> is either the literal character the key produces (ASCII or Unicode character), or a '
'symbolic name (as printed by --input-keylist')
binding_name = MPV._binding_name(keydef)
if callable(callback_or_cmd):
self._key_binding_handlers[binding_name] = callback_or_cmd
self.register_message_handler('key-binding', self._handle_key_binding_message)
self.command('define-section',
binding_name, '{} script-binding py_event_handler/{}'.format(keydef, binding_name), mode)
elif isinstance(callback_or_cmd, str):
self.command('define-section', binding_name, '{} {}'.format(keydef, callback_or_cmd), mode)
else:
raise TypeError('register_key_binding expects either an str with an mpv command or a python callable.')
self.command('enable-section', binding_name, 'allow-hide-cursor+allow-vo-dragging')
def _handle_key_binding_message(self, binding_name, key_state, key_name=None):
self._key_binding_handlers[binding_name](key_state, key_name)
# Convenience functions
def play(self, filename):
"""Play a path or URL (requires ``ytdl`` option to be set)."""
self.loadfile(filename)
@property
def playlist_filenames(self):
"""Return all playlist item file names/URLs as a list of strs."""
return [element['filename'] for element in self.playlist]
def playlist_append(self, filename, **options):
"""Append a path or URL to the playlist. This does not start playing the file automatically. To do that, use
``MPV.loadfile(filename, 'append-play')``."""
self.loadfile(filename, 'append', **options)
# Property accessors
def _get_property(self, name, decoder=strict_decoder, fmt=MpvFormat.NODE):
out = create_string_buffer(sizeof(MpvNode))
try:
cval = _mpv_get_property(self.handle, name.encode('utf-8'), fmt, out)
if fmt is MpvFormat.OSD_STRING:
return cast(out, POINTER(c_char_p)).contents.value.decode('utf-8')
elif fmt is MpvFormat.NODE:
rv = cast(out, POINTER(MpvNode)).contents.node_value(decoder=decoder)
_mpv_free_node_contents(out)
return rv
else:
raise TypeError('_get_property only supports NODE and OSD_STRING formats.')
except PropertyUnavailableError as ex:
return None
def _set_property(self, name, value):
ename = name.encode('utf-8')
if isinstance(value, (list, set, dict)):
_1, _2, _3, pointer = _make_node_str_list(value)
_mpv_set_property(self.handle, ename, MpvFormat.NODE, pointer)
else:
_mpv_set_property_string(self.handle, ename, _mpv_coax_proptype(value))
def __getattr__(self, name):
return self._get_property(_py_to_mpv(name), lazy_decoder)
def __setattr__(self, name, value):
try:
if name != 'handle' and not name.startswith('_'):
self._set_property(_py_to_mpv(name), value)
else:
super().__setattr__(name, value)
except AttributeError:
super().__setattr__(name, value)
def __dir__(self):
return super().__dir__() + [ name.replace('-', '_') for name in self.property_list ]
@property
def properties(self):
return { name: self.option_info(name) for name in self.property_list }
# Dict-like option access
def __getitem__(self, name, file_local=False):
"""Get an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._get_property(prefix+name, lazy_decoder)
def __setitem__(self, name, value, file_local=False):
"""Set an option value."""
prefix = 'file-local-options/' if file_local else 'options/'
return self._set_property(prefix+name, value)
def __iter__(self):
"""Iterate over all option names."""
return iter(self.options)
def option_info(self, name):
"""Get information on the given option."""
try:
return self._get_property('option-info/'+name)
except AttributeError:
return None
|
takuti/flurs | flurs/utils/projection.py | RandomProjection.__create_proj_mat | python | def __create_proj_mat(self, size):
# [1]
# return np.random.choice([-np.sqrt(3), 0, np.sqrt(3)], size=size, p=[1 / 6, 2 / 3, 1 / 6])
# [2]
s = 1 / self.density
return np.random.choice([-np.sqrt(s / self.k), 0, np.sqrt(s / self.k)],
size=size,
p=[1 / (2 * s), 1 - 1 / s, 1 / (2 * s)]) | Create a random projection matrix
[1] D. Achlioptas. Database-friendly random projections: Johnson-Lindenstrauss with binary coins.
[2] P. Li, et al. Very sparse random projections.
http://scikit-learn.org/stable/modules/random_projection.html#sparse-random-projection | train | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/utils/projection.py#L72-L88 | null | class RandomProjection(BaseProjection):
def __init__(self, k, p, density=0.2):
self.k = k
self.density = density
self.R = sp.csr_matrix(self.__create_proj_mat((k, p)))
def insert_proj_col(self, offset):
col = self.__create_proj_mat((self.k, 1))
R = self.R.toarray()
self.R = sp.csr_matrix(np.concatenate((R[:, :offset], col, R[:, offset:]), axis=1))
def reduce(self, Y):
return safe_sparse_dot(self.R, Y)
|
takuti/flurs | flurs/datasets/movielens.py | load_movies | python | def load_movies(data_home, size):
all_genres = ['Action',
'Adventure',
'Animation',
"Children's",
'Comedy',
'Crime',
'Documentary',
'Drama',
'Fantasy',
'Film-Noir',
'Horror',
'Musical',
'Mystery',
'Romance',
'Sci-Fi',
'Thriller',
'War',
'Western']
n_genre = len(all_genres)
movies = {}
if size == '100k':
with open(os.path.join(data_home, 'u.item'), encoding='ISO-8859-1') as f:
lines = list(map(lambda l: l.rstrip().split('|'), f.readlines()))
for line in lines:
movie_vec = np.zeros(n_genre)
for i, flg_chr in enumerate(line[-n_genre:]):
if flg_chr == '1':
movie_vec[i] = 1.
movie_id = int(line[0])
movies[movie_id] = movie_vec
elif size == '1m':
with open(os.path.join(data_home, 'movies.dat'), encoding='ISO-8859-1') as f:
lines = list(map(lambda l: l.rstrip().split('::'), f.readlines()))
for item_id_str, title, genres in lines:
movie_vec = np.zeros(n_genre)
for genre in genres.split('|'):
i = all_genres.index(genre)
movie_vec[i] = 1.
item_id = int(item_id_str)
movies[item_id] = movie_vec
return movies | Load movie genres as a context.
Returns:
dict of movie vectors: item_id -> numpy array (n_genre,) | train | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/datasets/movielens.py#L12-L62 | null | from ..data.entity import User, Item, Event
import os
import time
import numpy as np
from calendar import monthrange
from datetime import datetime, timedelta
from sklearn.utils import Bunch
def load_users(data_home, size):
"""Load user demographics as contexts.User ID -> {sex (M/F), age (7 groupd), occupation(0-20; 21)}
Returns:
dict of user vectors: user_id -> numpy array (1+1+21,); (sex_flg + age_group + n_occupation, )
"""
ages = [1, 18, 25, 35, 45, 50, 56, 999]
users = {}
if size == '100k':
all_occupations = ['administrator',
'artist',
'doctor',
'educator',
'engineer',
'entertainment',
'executive',
'healthcare',
'homemaker',
'lawyer',
'librarian',
'marketing',
'none',
'other',
'programmer',
'retired',
'salesman',
'scientist',
'student',
'technician',
'writer']
with open(os.path.join(data_home, 'u.user'), encoding='ISO-8859-1') as f:
lines = list(map(lambda l: l.rstrip().split('|'), f.readlines()))
for user_id_str, age_str, sex_str, occupation_str, zip_code in lines:
user_vec = np.zeros(1 + 1 + 21) # 1 categorical, 1 value, 21 categorical
user_vec[0] = 0 if sex_str == 'M' else 1 # sex
# age (ML1M is "age group", but 100k has actual "age")
age = int(age_str)
for i in range(7):
if age >= ages[i] and age < ages[i + 1]:
user_vec[1] = i
break
user_vec[2 + all_occupations.index(occupation_str)] = 1 # occupation (1-of-21)
users[int(user_id_str)] = user_vec
elif size == '1m':
with open(os.path.join(data_home, 'users.dat'), encoding='ISO-8859-1') as f:
lines = list(map(lambda l: l.rstrip().split('::'), f.readlines()))
for user_id_str, sex_str, age_str, occupation_str, zip_code in lines:
user_vec = np.zeros(1 + 1 + 21) # 1 categorical, 1 value, 21 categorical
user_vec[0] = 0 if sex_str == 'M' else 1 # sex
user_vec[1] = ages.index(int(age_str)) # age group (1, 18, ...)
user_vec[2 + int(occupation_str)] = 1 # occupation (1-of-21)
users[int(user_id_str)] = user_vec
return users
def load_ratings(data_home, size):
"""Load all samples in the dataset.
"""
if size == '100k':
with open(os.path.join(data_home, 'u.data'), encoding='ISO-8859-1') as f:
lines = list(map(lambda l: list(map(int, l.rstrip().split('\t'))), f.readlines()))
elif size == '1m':
with open(os.path.join(data_home, 'ratings.dat'), encoding='ISO-8859-1') as f:
lines = list(map(lambda l: list(map(int, l.rstrip().split('::'))), f.readlines()))
ratings = []
for l in lines:
# Since we consider positive-only feedback setting, ratings < 5 will be excluded.
if l[2] == 5:
ratings.append(l)
ratings = np.asarray(ratings)
# sorted by timestamp
return ratings[np.argsort(ratings[:, 3])]
def delta(d1, d2, opt='d'):
"""Compute difference between given 2 dates in month/day.
"""
delta = 0
if opt == 'm':
while True:
mdays = monthrange(d1.year, d1.month)[1]
d1 += timedelta(days=mdays)
if d1 <= d2:
delta += 1
else:
break
else:
delta = (d2 - d1).days
return delta
def fetch_movielens(data_home=None, size='100k'):
assert data_home is not None
if size not in ('100k', '1m'):
raise ValueError("size can only be '100k' or '1m', got %s" % size)
ratings = load_ratings(data_home, size)
users = load_users(data_home, size)
movies = load_movies(data_home, size)
samples = []
user_ids = {}
item_ids = {}
head_date = datetime(*time.localtime(ratings[0, 3])[:6])
dts = []
last = {}
for user_id, item_id, rating, timestamp in ratings:
# give an unique user index
if user_id in user_ids:
u_index = user_ids[user_id]
else:
u_index = len(user_ids)
user_ids[user_id] = u_index
# give an unique item index
if item_id in item_ids:
i_index = item_ids[item_id]
else:
i_index = len(item_ids)
item_ids[item_id] = i_index
# delta days
date = datetime(*time.localtime(timestamp)[:6])
dt = delta(head_date, date)
dts.append(dt)
weekday_vec = np.zeros(7)
weekday_vec[date.weekday()] = 1
if user_id in last:
last_item_vec = last[user_id]['item']
last_weekday_vec = last[user_id]['weekday']
else:
last_item_vec = np.zeros(18)
last_weekday_vec = np.zeros(7)
others = np.concatenate((weekday_vec, last_item_vec, last_weekday_vec))
user = User(u_index, users[user_id])
item = Item(i_index, movies[item_id])
sample = Event(user, item, 1., others)
samples.append(sample)
# record users' last rated movie features
last[user_id] = {'item': movies[item_id], 'weekday': weekday_vec}
# contexts in this dataset
# 1 delta time, 18 genres, and 23 demographics (1 for M/F, 1 for age, 21 for occupation(0-20))
# 7 for day of week, 18 for the last rated item genres, 7 for the last day of week
return Bunch(samples=samples,
can_repeat=False,
contexts={'others': 7 + 18 + 7, 'item': 18, 'user': 23},
n_user=len(user_ids),
n_item=len(item_ids),
n_sample=len(samples))
|
takuti/flurs | flurs/datasets/movielens.py | load_users | python | def load_users(data_home, size):
ages = [1, 18, 25, 35, 45, 50, 56, 999]
users = {}
if size == '100k':
all_occupations = ['administrator',
'artist',
'doctor',
'educator',
'engineer',
'entertainment',
'executive',
'healthcare',
'homemaker',
'lawyer',
'librarian',
'marketing',
'none',
'other',
'programmer',
'retired',
'salesman',
'scientist',
'student',
'technician',
'writer']
with open(os.path.join(data_home, 'u.user'), encoding='ISO-8859-1') as f:
lines = list(map(lambda l: l.rstrip().split('|'), f.readlines()))
for user_id_str, age_str, sex_str, occupation_str, zip_code in lines:
user_vec = np.zeros(1 + 1 + 21) # 1 categorical, 1 value, 21 categorical
user_vec[0] = 0 if sex_str == 'M' else 1 # sex
# age (ML1M is "age group", but 100k has actual "age")
age = int(age_str)
for i in range(7):
if age >= ages[i] and age < ages[i + 1]:
user_vec[1] = i
break
user_vec[2 + all_occupations.index(occupation_str)] = 1 # occupation (1-of-21)
users[int(user_id_str)] = user_vec
elif size == '1m':
with open(os.path.join(data_home, 'users.dat'), encoding='ISO-8859-1') as f:
lines = list(map(lambda l: l.rstrip().split('::'), f.readlines()))
for user_id_str, sex_str, age_str, occupation_str, zip_code in lines:
user_vec = np.zeros(1 + 1 + 21) # 1 categorical, 1 value, 21 categorical
user_vec[0] = 0 if sex_str == 'M' else 1 # sex
user_vec[1] = ages.index(int(age_str)) # age group (1, 18, ...)
user_vec[2 + int(occupation_str)] = 1 # occupation (1-of-21)
users[int(user_id_str)] = user_vec
return users | Load user demographics as contexts.User ID -> {sex (M/F), age (7 groupd), occupation(0-20; 21)}
Returns:
dict of user vectors: user_id -> numpy array (1+1+21,); (sex_flg + age_group + n_occupation, ) | train | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/datasets/movielens.py#L65-L124 | null | from ..data.entity import User, Item, Event
import os
import time
import numpy as np
from calendar import monthrange
from datetime import datetime, timedelta
from sklearn.utils import Bunch
def load_movies(data_home, size):
"""Load movie genres as a context.
Returns:
dict of movie vectors: item_id -> numpy array (n_genre,)
"""
all_genres = ['Action',
'Adventure',
'Animation',
"Children's",
'Comedy',
'Crime',
'Documentary',
'Drama',
'Fantasy',
'Film-Noir',
'Horror',
'Musical',
'Mystery',
'Romance',
'Sci-Fi',
'Thriller',
'War',
'Western']
n_genre = len(all_genres)
movies = {}
if size == '100k':
with open(os.path.join(data_home, 'u.item'), encoding='ISO-8859-1') as f:
lines = list(map(lambda l: l.rstrip().split('|'), f.readlines()))
for line in lines:
movie_vec = np.zeros(n_genre)
for i, flg_chr in enumerate(line[-n_genre:]):
if flg_chr == '1':
movie_vec[i] = 1.
movie_id = int(line[0])
movies[movie_id] = movie_vec
elif size == '1m':
with open(os.path.join(data_home, 'movies.dat'), encoding='ISO-8859-1') as f:
lines = list(map(lambda l: l.rstrip().split('::'), f.readlines()))
for item_id_str, title, genres in lines:
movie_vec = np.zeros(n_genre)
for genre in genres.split('|'):
i = all_genres.index(genre)
movie_vec[i] = 1.
item_id = int(item_id_str)
movies[item_id] = movie_vec
return movies
def load_ratings(data_home, size):
"""Load all samples in the dataset.
"""
if size == '100k':
with open(os.path.join(data_home, 'u.data'), encoding='ISO-8859-1') as f:
lines = list(map(lambda l: list(map(int, l.rstrip().split('\t'))), f.readlines()))
elif size == '1m':
with open(os.path.join(data_home, 'ratings.dat'), encoding='ISO-8859-1') as f:
lines = list(map(lambda l: list(map(int, l.rstrip().split('::'))), f.readlines()))
ratings = []
for l in lines:
# Since we consider positive-only feedback setting, ratings < 5 will be excluded.
if l[2] == 5:
ratings.append(l)
ratings = np.asarray(ratings)
# sorted by timestamp
return ratings[np.argsort(ratings[:, 3])]
def delta(d1, d2, opt='d'):
"""Compute difference between given 2 dates in month/day.
"""
delta = 0
if opt == 'm':
while True:
mdays = monthrange(d1.year, d1.month)[1]
d1 += timedelta(days=mdays)
if d1 <= d2:
delta += 1
else:
break
else:
delta = (d2 - d1).days
return delta
def fetch_movielens(data_home=None, size='100k'):
assert data_home is not None
if size not in ('100k', '1m'):
raise ValueError("size can only be '100k' or '1m', got %s" % size)
ratings = load_ratings(data_home, size)
users = load_users(data_home, size)
movies = load_movies(data_home, size)
samples = []
user_ids = {}
item_ids = {}
head_date = datetime(*time.localtime(ratings[0, 3])[:6])
dts = []
last = {}
for user_id, item_id, rating, timestamp in ratings:
# give an unique user index
if user_id in user_ids:
u_index = user_ids[user_id]
else:
u_index = len(user_ids)
user_ids[user_id] = u_index
# give an unique item index
if item_id in item_ids:
i_index = item_ids[item_id]
else:
i_index = len(item_ids)
item_ids[item_id] = i_index
# delta days
date = datetime(*time.localtime(timestamp)[:6])
dt = delta(head_date, date)
dts.append(dt)
weekday_vec = np.zeros(7)
weekday_vec[date.weekday()] = 1
if user_id in last:
last_item_vec = last[user_id]['item']
last_weekday_vec = last[user_id]['weekday']
else:
last_item_vec = np.zeros(18)
last_weekday_vec = np.zeros(7)
others = np.concatenate((weekday_vec, last_item_vec, last_weekday_vec))
user = User(u_index, users[user_id])
item = Item(i_index, movies[item_id])
sample = Event(user, item, 1., others)
samples.append(sample)
# record users' last rated movie features
last[user_id] = {'item': movies[item_id], 'weekday': weekday_vec}
# contexts in this dataset
# 1 delta time, 18 genres, and 23 demographics (1 for M/F, 1 for age, 21 for occupation(0-20))
# 7 for day of week, 18 for the last rated item genres, 7 for the last day of week
return Bunch(samples=samples,
can_repeat=False,
contexts={'others': 7 + 18 + 7, 'item': 18, 'user': 23},
n_user=len(user_ids),
n_item=len(item_ids),
n_sample=len(samples))
|
takuti/flurs | flurs/datasets/movielens.py | load_ratings | python | def load_ratings(data_home, size):
if size == '100k':
with open(os.path.join(data_home, 'u.data'), encoding='ISO-8859-1') as f:
lines = list(map(lambda l: list(map(int, l.rstrip().split('\t'))), f.readlines()))
elif size == '1m':
with open(os.path.join(data_home, 'ratings.dat'), encoding='ISO-8859-1') as f:
lines = list(map(lambda l: list(map(int, l.rstrip().split('::'))), f.readlines()))
ratings = []
for l in lines:
# Since we consider positive-only feedback setting, ratings < 5 will be excluded.
if l[2] == 5:
ratings.append(l)
ratings = np.asarray(ratings)
# sorted by timestamp
return ratings[np.argsort(ratings[:, 3])] | Load all samples in the dataset. | train | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/datasets/movielens.py#L127-L148 | null | from ..data.entity import User, Item, Event
import os
import time
import numpy as np
from calendar import monthrange
from datetime import datetime, timedelta
from sklearn.utils import Bunch
def load_movies(data_home, size):
"""Load movie genres as a context.
Returns:
dict of movie vectors: item_id -> numpy array (n_genre,)
"""
all_genres = ['Action',
'Adventure',
'Animation',
"Children's",
'Comedy',
'Crime',
'Documentary',
'Drama',
'Fantasy',
'Film-Noir',
'Horror',
'Musical',
'Mystery',
'Romance',
'Sci-Fi',
'Thriller',
'War',
'Western']
n_genre = len(all_genres)
movies = {}
if size == '100k':
with open(os.path.join(data_home, 'u.item'), encoding='ISO-8859-1') as f:
lines = list(map(lambda l: l.rstrip().split('|'), f.readlines()))
for line in lines:
movie_vec = np.zeros(n_genre)
for i, flg_chr in enumerate(line[-n_genre:]):
if flg_chr == '1':
movie_vec[i] = 1.
movie_id = int(line[0])
movies[movie_id] = movie_vec
elif size == '1m':
with open(os.path.join(data_home, 'movies.dat'), encoding='ISO-8859-1') as f:
lines = list(map(lambda l: l.rstrip().split('::'), f.readlines()))
for item_id_str, title, genres in lines:
movie_vec = np.zeros(n_genre)
for genre in genres.split('|'):
i = all_genres.index(genre)
movie_vec[i] = 1.
item_id = int(item_id_str)
movies[item_id] = movie_vec
return movies
def load_users(data_home, size):
"""Load user demographics as contexts.User ID -> {sex (M/F), age (7 groupd), occupation(0-20; 21)}
Returns:
dict of user vectors: user_id -> numpy array (1+1+21,); (sex_flg + age_group + n_occupation, )
"""
ages = [1, 18, 25, 35, 45, 50, 56, 999]
users = {}
if size == '100k':
all_occupations = ['administrator',
'artist',
'doctor',
'educator',
'engineer',
'entertainment',
'executive',
'healthcare',
'homemaker',
'lawyer',
'librarian',
'marketing',
'none',
'other',
'programmer',
'retired',
'salesman',
'scientist',
'student',
'technician',
'writer']
with open(os.path.join(data_home, 'u.user'), encoding='ISO-8859-1') as f:
lines = list(map(lambda l: l.rstrip().split('|'), f.readlines()))
for user_id_str, age_str, sex_str, occupation_str, zip_code in lines:
user_vec = np.zeros(1 + 1 + 21) # 1 categorical, 1 value, 21 categorical
user_vec[0] = 0 if sex_str == 'M' else 1 # sex
# age (ML1M is "age group", but 100k has actual "age")
age = int(age_str)
for i in range(7):
if age >= ages[i] and age < ages[i + 1]:
user_vec[1] = i
break
user_vec[2 + all_occupations.index(occupation_str)] = 1 # occupation (1-of-21)
users[int(user_id_str)] = user_vec
elif size == '1m':
with open(os.path.join(data_home, 'users.dat'), encoding='ISO-8859-1') as f:
lines = list(map(lambda l: l.rstrip().split('::'), f.readlines()))
for user_id_str, sex_str, age_str, occupation_str, zip_code in lines:
user_vec = np.zeros(1 + 1 + 21) # 1 categorical, 1 value, 21 categorical
user_vec[0] = 0 if sex_str == 'M' else 1 # sex
user_vec[1] = ages.index(int(age_str)) # age group (1, 18, ...)
user_vec[2 + int(occupation_str)] = 1 # occupation (1-of-21)
users[int(user_id_str)] = user_vec
return users
def delta(d1, d2, opt='d'):
"""Compute difference between given 2 dates in month/day.
"""
delta = 0
if opt == 'm':
while True:
mdays = monthrange(d1.year, d1.month)[1]
d1 += timedelta(days=mdays)
if d1 <= d2:
delta += 1
else:
break
else:
delta = (d2 - d1).days
return delta
def fetch_movielens(data_home=None, size='100k'):
assert data_home is not None
if size not in ('100k', '1m'):
raise ValueError("size can only be '100k' or '1m', got %s" % size)
ratings = load_ratings(data_home, size)
users = load_users(data_home, size)
movies = load_movies(data_home, size)
samples = []
user_ids = {}
item_ids = {}
head_date = datetime(*time.localtime(ratings[0, 3])[:6])
dts = []
last = {}
for user_id, item_id, rating, timestamp in ratings:
# give an unique user index
if user_id in user_ids:
u_index = user_ids[user_id]
else:
u_index = len(user_ids)
user_ids[user_id] = u_index
# give an unique item index
if item_id in item_ids:
i_index = item_ids[item_id]
else:
i_index = len(item_ids)
item_ids[item_id] = i_index
# delta days
date = datetime(*time.localtime(timestamp)[:6])
dt = delta(head_date, date)
dts.append(dt)
weekday_vec = np.zeros(7)
weekday_vec[date.weekday()] = 1
if user_id in last:
last_item_vec = last[user_id]['item']
last_weekday_vec = last[user_id]['weekday']
else:
last_item_vec = np.zeros(18)
last_weekday_vec = np.zeros(7)
others = np.concatenate((weekday_vec, last_item_vec, last_weekday_vec))
user = User(u_index, users[user_id])
item = Item(i_index, movies[item_id])
sample = Event(user, item, 1., others)
samples.append(sample)
# record users' last rated movie features
last[user_id] = {'item': movies[item_id], 'weekday': weekday_vec}
# contexts in this dataset
# 1 delta time, 18 genres, and 23 demographics (1 for M/F, 1 for age, 21 for occupation(0-20))
# 7 for day of week, 18 for the last rated item genres, 7 for the last day of week
return Bunch(samples=samples,
can_repeat=False,
contexts={'others': 7 + 18 + 7, 'item': 18, 'user': 23},
n_user=len(user_ids),
n_item=len(item_ids),
n_sample=len(samples))
|
takuti/flurs | flurs/datasets/movielens.py | delta | python | def delta(d1, d2, opt='d'):
delta = 0
if opt == 'm':
while True:
mdays = monthrange(d1.year, d1.month)[1]
d1 += timedelta(days=mdays)
if d1 <= d2:
delta += 1
else:
break
else:
delta = (d2 - d1).days
return delta | Compute difference between given 2 dates in month/day. | train | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/datasets/movielens.py#L151-L167 | null | from ..data.entity import User, Item, Event
import os
import time
import numpy as np
from calendar import monthrange
from datetime import datetime, timedelta
from sklearn.utils import Bunch
def load_movies(data_home, size):
"""Load movie genres as a context.
Returns:
dict of movie vectors: item_id -> numpy array (n_genre,)
"""
all_genres = ['Action',
'Adventure',
'Animation',
"Children's",
'Comedy',
'Crime',
'Documentary',
'Drama',
'Fantasy',
'Film-Noir',
'Horror',
'Musical',
'Mystery',
'Romance',
'Sci-Fi',
'Thriller',
'War',
'Western']
n_genre = len(all_genres)
movies = {}
if size == '100k':
with open(os.path.join(data_home, 'u.item'), encoding='ISO-8859-1') as f:
lines = list(map(lambda l: l.rstrip().split('|'), f.readlines()))
for line in lines:
movie_vec = np.zeros(n_genre)
for i, flg_chr in enumerate(line[-n_genre:]):
if flg_chr == '1':
movie_vec[i] = 1.
movie_id = int(line[0])
movies[movie_id] = movie_vec
elif size == '1m':
with open(os.path.join(data_home, 'movies.dat'), encoding='ISO-8859-1') as f:
lines = list(map(lambda l: l.rstrip().split('::'), f.readlines()))
for item_id_str, title, genres in lines:
movie_vec = np.zeros(n_genre)
for genre in genres.split('|'):
i = all_genres.index(genre)
movie_vec[i] = 1.
item_id = int(item_id_str)
movies[item_id] = movie_vec
return movies
def load_users(data_home, size):
"""Load user demographics as contexts.User ID -> {sex (M/F), age (7 groupd), occupation(0-20; 21)}
Returns:
dict of user vectors: user_id -> numpy array (1+1+21,); (sex_flg + age_group + n_occupation, )
"""
ages = [1, 18, 25, 35, 45, 50, 56, 999]
users = {}
if size == '100k':
all_occupations = ['administrator',
'artist',
'doctor',
'educator',
'engineer',
'entertainment',
'executive',
'healthcare',
'homemaker',
'lawyer',
'librarian',
'marketing',
'none',
'other',
'programmer',
'retired',
'salesman',
'scientist',
'student',
'technician',
'writer']
with open(os.path.join(data_home, 'u.user'), encoding='ISO-8859-1') as f:
lines = list(map(lambda l: l.rstrip().split('|'), f.readlines()))
for user_id_str, age_str, sex_str, occupation_str, zip_code in lines:
user_vec = np.zeros(1 + 1 + 21) # 1 categorical, 1 value, 21 categorical
user_vec[0] = 0 if sex_str == 'M' else 1 # sex
# age (ML1M is "age group", but 100k has actual "age")
age = int(age_str)
for i in range(7):
if age >= ages[i] and age < ages[i + 1]:
user_vec[1] = i
break
user_vec[2 + all_occupations.index(occupation_str)] = 1 # occupation (1-of-21)
users[int(user_id_str)] = user_vec
elif size == '1m':
with open(os.path.join(data_home, 'users.dat'), encoding='ISO-8859-1') as f:
lines = list(map(lambda l: l.rstrip().split('::'), f.readlines()))
for user_id_str, sex_str, age_str, occupation_str, zip_code in lines:
user_vec = np.zeros(1 + 1 + 21) # 1 categorical, 1 value, 21 categorical
user_vec[0] = 0 if sex_str == 'M' else 1 # sex
user_vec[1] = ages.index(int(age_str)) # age group (1, 18, ...)
user_vec[2 + int(occupation_str)] = 1 # occupation (1-of-21)
users[int(user_id_str)] = user_vec
return users
def load_ratings(data_home, size):
"""Load all samples in the dataset.
"""
if size == '100k':
with open(os.path.join(data_home, 'u.data'), encoding='ISO-8859-1') as f:
lines = list(map(lambda l: list(map(int, l.rstrip().split('\t'))), f.readlines()))
elif size == '1m':
with open(os.path.join(data_home, 'ratings.dat'), encoding='ISO-8859-1') as f:
lines = list(map(lambda l: list(map(int, l.rstrip().split('::'))), f.readlines()))
ratings = []
for l in lines:
# Since we consider positive-only feedback setting, ratings < 5 will be excluded.
if l[2] == 5:
ratings.append(l)
ratings = np.asarray(ratings)
# sorted by timestamp
return ratings[np.argsort(ratings[:, 3])]
def fetch_movielens(data_home=None, size='100k'):
assert data_home is not None
if size not in ('100k', '1m'):
raise ValueError("size can only be '100k' or '1m', got %s" % size)
ratings = load_ratings(data_home, size)
users = load_users(data_home, size)
movies = load_movies(data_home, size)
samples = []
user_ids = {}
item_ids = {}
head_date = datetime(*time.localtime(ratings[0, 3])[:6])
dts = []
last = {}
for user_id, item_id, rating, timestamp in ratings:
# give an unique user index
if user_id in user_ids:
u_index = user_ids[user_id]
else:
u_index = len(user_ids)
user_ids[user_id] = u_index
# give an unique item index
if item_id in item_ids:
i_index = item_ids[item_id]
else:
i_index = len(item_ids)
item_ids[item_id] = i_index
# delta days
date = datetime(*time.localtime(timestamp)[:6])
dt = delta(head_date, date)
dts.append(dt)
weekday_vec = np.zeros(7)
weekday_vec[date.weekday()] = 1
if user_id in last:
last_item_vec = last[user_id]['item']
last_weekday_vec = last[user_id]['weekday']
else:
last_item_vec = np.zeros(18)
last_weekday_vec = np.zeros(7)
others = np.concatenate((weekday_vec, last_item_vec, last_weekday_vec))
user = User(u_index, users[user_id])
item = Item(i_index, movies[item_id])
sample = Event(user, item, 1., others)
samples.append(sample)
# record users' last rated movie features
last[user_id] = {'item': movies[item_id], 'weekday': weekday_vec}
# contexts in this dataset
# 1 delta time, 18 genres, and 23 demographics (1 for M/F, 1 for age, 21 for occupation(0-20))
# 7 for day of week, 18 for the last rated item genres, 7 for the last day of week
return Bunch(samples=samples,
can_repeat=False,
contexts={'others': 7 + 18 + 7, 'item': 18, 'user': 23},
n_user=len(user_ids),
n_item=len(item_ids),
n_sample=len(samples))
|
takuti/flurs | flurs/utils/feature_hash.py | n_feature_hash | python | def n_feature_hash(feature, dims, seeds):
vec = np.zeros(sum(dims))
offset = 0
for seed, dim in zip(seeds, dims):
vec[offset:(offset + dim)] = feature_hash(feature, dim, seed)
offset += dim
return vec | N-hot-encoded feature hashing.
Args:
feature (str): Target feature represented as string.
dims (list of int): Number of dimensions for each hash value.
seeds (list of float): Seed of each hash function (mmh3).
Returns:
numpy 1d array: n-hot-encoded feature vector for `s`. | train | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/utils/feature_hash.py#L5-L24 | [
"def feature_hash(feature, dim, seed=123):\n \"\"\"Feature hashing.\n\n Args:\n feature (str): Target feature represented as string.\n dim (int): Number of dimensions for a hash value.\n seed (float): Seed of a MurmurHash3 hash function.\n\n Returns:\n numpy 1d array: one-hot-encoded feature vector for `s`.\n\n \"\"\"\n vec = np.zeros(dim)\n i = mmh3.hash(feature, seed) % dim\n vec[i] = 1\n return vec\n"
] | import mmh3
import numpy as np
def feature_hash(feature, dim, seed=123):
"""Feature hashing.
Args:
feature (str): Target feature represented as string.
dim (int): Number of dimensions for a hash value.
seed (float): Seed of a MurmurHash3 hash function.
Returns:
numpy 1d array: one-hot-encoded feature vector for `s`.
"""
vec = np.zeros(dim)
i = mmh3.hash(feature, seed) % dim
vec[i] = 1
return vec
def multiple_feature_hash(feature, dim, seed=123):
"""Feature hashing using multiple hash function.
This technique is effective to prevent collisions.
Args:
feature (str): Target feature represented as string.
dim (int): Number of dimensions for a hash value.
seed (float): Seed of a MurmurHash3 hash function.
Returns:
numpy 1d array: one-hot-encoded feature vector for `s`.
"""
vec = np.zeros(dim)
i = mmh3.hash(feature, seed) % dim
vec[i] = 1 if mmh3.hash(feature) % 2 else -1
return vec
|
takuti/flurs | flurs/utils/feature_hash.py | feature_hash | python | def feature_hash(feature, dim, seed=123):
vec = np.zeros(dim)
i = mmh3.hash(feature, seed) % dim
vec[i] = 1
return vec | Feature hashing.
Args:
feature (str): Target feature represented as string.
dim (int): Number of dimensions for a hash value.
seed (float): Seed of a MurmurHash3 hash function.
Returns:
numpy 1d array: one-hot-encoded feature vector for `s`. | train | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/utils/feature_hash.py#L27-L42 | null | import mmh3
import numpy as np
def n_feature_hash(feature, dims, seeds):
"""N-hot-encoded feature hashing.
Args:
feature (str): Target feature represented as string.
dims (list of int): Number of dimensions for each hash value.
seeds (list of float): Seed of each hash function (mmh3).
Returns:
numpy 1d array: n-hot-encoded feature vector for `s`.
"""
vec = np.zeros(sum(dims))
offset = 0
for seed, dim in zip(seeds, dims):
vec[offset:(offset + dim)] = feature_hash(feature, dim, seed)
offset += dim
return vec
def multiple_feature_hash(feature, dim, seed=123):
"""Feature hashing using multiple hash function.
This technique is effective to prevent collisions.
Args:
feature (str): Target feature represented as string.
dim (int): Number of dimensions for a hash value.
seed (float): Seed of a MurmurHash3 hash function.
Returns:
numpy 1d array: one-hot-encoded feature vector for `s`.
"""
vec = np.zeros(dim)
i = mmh3.hash(feature, seed) % dim
vec[i] = 1 if mmh3.hash(feature) % 2 else -1
return vec
|
takuti/flurs | flurs/utils/metric.py | count_true_positive | python | def count_true_positive(truth, recommend):
tp = 0
for r in recommend:
if r in truth:
tp += 1
return tp | Count number of true positives from given sets of samples.
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
int: Number of true positives. | train | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/utils/metric.py#L4-L19 | null | import numpy as np
def recall(truth, recommend, k=None):
"""Recall@k.
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
k (int): Top-k items in `recommend` will be recommended.
Returns:
float: Recall@k.
"""
if len(truth) == 0:
if len(recommend) == 0:
return 1.
return 0.
if k is None:
k = len(recommend)
return count_true_positive(truth, recommend[:k]) / float(truth.size)
def precision(truth, recommend, k=None):
"""Precision@k.
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
k (int): Top-k items in `recommend` will be recommended.
Returns:
float: Precision@k.
"""
if len(recommend) == 0:
if len(truth) == 0:
return 1.
return 0.
if k is None:
k = len(recommend)
return count_true_positive(truth, recommend[:k]) / float(k)
def average_precision(truth, recommend):
"""Average Precision (AP).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: AP.
"""
if len(truth) == 0:
if len(recommend) == 0:
return 1.
return 0.
tp = accum = 0.
for n in range(recommend.size):
if recommend[n] in truth:
tp += 1.
accum += (tp / (n + 1.))
return accum / truth.size
def auc(truth, recommend):
"""Area under the ROC curve (AUC).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: AUC.
"""
tp = correct = 0.
for r in recommend:
if r in truth:
# keep track number of true positives placed before
tp += 1.
else:
correct += tp
# number of all possible tp-fp pairs
pairs = tp * (recommend.size - tp)
# if there is no TP (or no FP), it's meaningless for this metric (i.e., AUC=0.5)
if pairs == 0:
return 0.5
return correct / pairs
def reciprocal_rank(truth, recommend):
"""Reciprocal Rank (RR).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: RR.
"""
for n in range(recommend.size):
if recommend[n] in truth:
return 1. / (n + 1)
return 0.
def mpr(truth, recommend):
"""Mean Percentile Rank (MPR).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: MPR.
"""
if len(recommend) == 0 and len(truth) == 0:
return 0. # best
elif len(truth) == 0 or len(truth) == 0:
return 100. # worst
accum = 0.
n_recommend = recommend.size
for t in truth:
r = np.where(recommend == t)[0][0] / float(n_recommend)
accum += r
return accum * 100. / truth.size
def ndcg(truth, recommend, k=None):
"""Normalized Discounted Cumulative Grain (NDCG).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
k (int): Top-k items in `recommend` will be recommended.
Returns:
float: NDCG.
"""
if k is None:
k = len(recommend)
def idcg(n_possible_truth):
res = 0.
for n in range(n_possible_truth):
res += 1. / np.log2(n + 2)
return res
dcg = 0.
for n, r in enumerate(recommend[:k]):
if r not in truth:
continue
dcg += 1. / np.log2(n + 2)
res_idcg = idcg(np.min([truth.size, k]))
if res_idcg == 0.:
return 0.
return dcg / res_idcg
|
takuti/flurs | flurs/utils/metric.py | recall | python | def recall(truth, recommend, k=None):
if len(truth) == 0:
if len(recommend) == 0:
return 1.
return 0.
if k is None:
k = len(recommend)
return count_true_positive(truth, recommend[:k]) / float(truth.size) | Recall@k.
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
k (int): Top-k items in `recommend` will be recommended.
Returns:
float: Recall@k. | train | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/utils/metric.py#L22-L41 | [
"def count_true_positive(truth, recommend):\n \"\"\"Count number of true positives from given sets of samples.\n\n Args:\n truth (numpy 1d array): Set of truth samples.\n recommend (numpy 1d array): Ordered set of recommended samples.\n\n Returns:\n int: Number of true positives.\n\n \"\"\"\n tp = 0\n for r in recommend:\n if r in truth:\n tp += 1\n return tp\n"
] | import numpy as np
def count_true_positive(truth, recommend):
"""Count number of true positives from given sets of samples.
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
int: Number of true positives.
"""
tp = 0
for r in recommend:
if r in truth:
tp += 1
return tp
def precision(truth, recommend, k=None):
"""Precision@k.
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
k (int): Top-k items in `recommend` will be recommended.
Returns:
float: Precision@k.
"""
if len(recommend) == 0:
if len(truth) == 0:
return 1.
return 0.
if k is None:
k = len(recommend)
return count_true_positive(truth, recommend[:k]) / float(k)
def average_precision(truth, recommend):
"""Average Precision (AP).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: AP.
"""
if len(truth) == 0:
if len(recommend) == 0:
return 1.
return 0.
tp = accum = 0.
for n in range(recommend.size):
if recommend[n] in truth:
tp += 1.
accum += (tp / (n + 1.))
return accum / truth.size
def auc(truth, recommend):
"""Area under the ROC curve (AUC).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: AUC.
"""
tp = correct = 0.
for r in recommend:
if r in truth:
# keep track number of true positives placed before
tp += 1.
else:
correct += tp
# number of all possible tp-fp pairs
pairs = tp * (recommend.size - tp)
# if there is no TP (or no FP), it's meaningless for this metric (i.e., AUC=0.5)
if pairs == 0:
return 0.5
return correct / pairs
def reciprocal_rank(truth, recommend):
"""Reciprocal Rank (RR).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: RR.
"""
for n in range(recommend.size):
if recommend[n] in truth:
return 1. / (n + 1)
return 0.
def mpr(truth, recommend):
"""Mean Percentile Rank (MPR).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: MPR.
"""
if len(recommend) == 0 and len(truth) == 0:
return 0. # best
elif len(truth) == 0 or len(truth) == 0:
return 100. # worst
accum = 0.
n_recommend = recommend.size
for t in truth:
r = np.where(recommend == t)[0][0] / float(n_recommend)
accum += r
return accum * 100. / truth.size
def ndcg(truth, recommend, k=None):
"""Normalized Discounted Cumulative Grain (NDCG).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
k (int): Top-k items in `recommend` will be recommended.
Returns:
float: NDCG.
"""
if k is None:
k = len(recommend)
def idcg(n_possible_truth):
res = 0.
for n in range(n_possible_truth):
res += 1. / np.log2(n + 2)
return res
dcg = 0.
for n, r in enumerate(recommend[:k]):
if r not in truth:
continue
dcg += 1. / np.log2(n + 2)
res_idcg = idcg(np.min([truth.size, k]))
if res_idcg == 0.:
return 0.
return dcg / res_idcg
|
takuti/flurs | flurs/utils/metric.py | precision | python | def precision(truth, recommend, k=None):
if len(recommend) == 0:
if len(truth) == 0:
return 1.
return 0.
if k is None:
k = len(recommend)
return count_true_positive(truth, recommend[:k]) / float(k) | Precision@k.
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
k (int): Top-k items in `recommend` will be recommended.
Returns:
float: Precision@k. | train | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/utils/metric.py#L44-L63 | [
"def count_true_positive(truth, recommend):\n \"\"\"Count number of true positives from given sets of samples.\n\n Args:\n truth (numpy 1d array): Set of truth samples.\n recommend (numpy 1d array): Ordered set of recommended samples.\n\n Returns:\n int: Number of true positives.\n\n \"\"\"\n tp = 0\n for r in recommend:\n if r in truth:\n tp += 1\n return tp\n"
] | import numpy as np
def count_true_positive(truth, recommend):
"""Count number of true positives from given sets of samples.
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
int: Number of true positives.
"""
tp = 0
for r in recommend:
if r in truth:
tp += 1
return tp
def recall(truth, recommend, k=None):
"""Recall@k.
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
k (int): Top-k items in `recommend` will be recommended.
Returns:
float: Recall@k.
"""
if len(truth) == 0:
if len(recommend) == 0:
return 1.
return 0.
if k is None:
k = len(recommend)
return count_true_positive(truth, recommend[:k]) / float(truth.size)
def average_precision(truth, recommend):
"""Average Precision (AP).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: AP.
"""
if len(truth) == 0:
if len(recommend) == 0:
return 1.
return 0.
tp = accum = 0.
for n in range(recommend.size):
if recommend[n] in truth:
tp += 1.
accum += (tp / (n + 1.))
return accum / truth.size
def auc(truth, recommend):
"""Area under the ROC curve (AUC).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: AUC.
"""
tp = correct = 0.
for r in recommend:
if r in truth:
# keep track number of true positives placed before
tp += 1.
else:
correct += tp
# number of all possible tp-fp pairs
pairs = tp * (recommend.size - tp)
# if there is no TP (or no FP), it's meaningless for this metric (i.e., AUC=0.5)
if pairs == 0:
return 0.5
return correct / pairs
def reciprocal_rank(truth, recommend):
"""Reciprocal Rank (RR).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: RR.
"""
for n in range(recommend.size):
if recommend[n] in truth:
return 1. / (n + 1)
return 0.
def mpr(truth, recommend):
"""Mean Percentile Rank (MPR).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: MPR.
"""
if len(recommend) == 0 and len(truth) == 0:
return 0. # best
elif len(truth) == 0 or len(truth) == 0:
return 100. # worst
accum = 0.
n_recommend = recommend.size
for t in truth:
r = np.where(recommend == t)[0][0] / float(n_recommend)
accum += r
return accum * 100. / truth.size
def ndcg(truth, recommend, k=None):
"""Normalized Discounted Cumulative Grain (NDCG).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
k (int): Top-k items in `recommend` will be recommended.
Returns:
float: NDCG.
"""
if k is None:
k = len(recommend)
def idcg(n_possible_truth):
res = 0.
for n in range(n_possible_truth):
res += 1. / np.log2(n + 2)
return res
dcg = 0.
for n, r in enumerate(recommend[:k]):
if r not in truth:
continue
dcg += 1. / np.log2(n + 2)
res_idcg = idcg(np.min([truth.size, k]))
if res_idcg == 0.:
return 0.
return dcg / res_idcg
|
takuti/flurs | flurs/utils/metric.py | average_precision | python | def average_precision(truth, recommend):
if len(truth) == 0:
if len(recommend) == 0:
return 1.
return 0.
tp = accum = 0.
for n in range(recommend.size):
if recommend[n] in truth:
tp += 1.
accum += (tp / (n + 1.))
return accum / truth.size | Average Precision (AP).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: AP. | train | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/utils/metric.py#L66-L87 | null | import numpy as np
def count_true_positive(truth, recommend):
"""Count number of true positives from given sets of samples.
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
int: Number of true positives.
"""
tp = 0
for r in recommend:
if r in truth:
tp += 1
return tp
def recall(truth, recommend, k=None):
"""Recall@k.
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
k (int): Top-k items in `recommend` will be recommended.
Returns:
float: Recall@k.
"""
if len(truth) == 0:
if len(recommend) == 0:
return 1.
return 0.
if k is None:
k = len(recommend)
return count_true_positive(truth, recommend[:k]) / float(truth.size)
def precision(truth, recommend, k=None):
"""Precision@k.
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
k (int): Top-k items in `recommend` will be recommended.
Returns:
float: Precision@k.
"""
if len(recommend) == 0:
if len(truth) == 0:
return 1.
return 0.
if k is None:
k = len(recommend)
return count_true_positive(truth, recommend[:k]) / float(k)
def auc(truth, recommend):
"""Area under the ROC curve (AUC).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: AUC.
"""
tp = correct = 0.
for r in recommend:
if r in truth:
# keep track number of true positives placed before
tp += 1.
else:
correct += tp
# number of all possible tp-fp pairs
pairs = tp * (recommend.size - tp)
# if there is no TP (or no FP), it's meaningless for this metric (i.e., AUC=0.5)
if pairs == 0:
return 0.5
return correct / pairs
def reciprocal_rank(truth, recommend):
"""Reciprocal Rank (RR).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: RR.
"""
for n in range(recommend.size):
if recommend[n] in truth:
return 1. / (n + 1)
return 0.
def mpr(truth, recommend):
"""Mean Percentile Rank (MPR).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: MPR.
"""
if len(recommend) == 0 and len(truth) == 0:
return 0. # best
elif len(truth) == 0 or len(truth) == 0:
return 100. # worst
accum = 0.
n_recommend = recommend.size
for t in truth:
r = np.where(recommend == t)[0][0] / float(n_recommend)
accum += r
return accum * 100. / truth.size
def ndcg(truth, recommend, k=None):
"""Normalized Discounted Cumulative Grain (NDCG).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
k (int): Top-k items in `recommend` will be recommended.
Returns:
float: NDCG.
"""
if k is None:
k = len(recommend)
def idcg(n_possible_truth):
res = 0.
for n in range(n_possible_truth):
res += 1. / np.log2(n + 2)
return res
dcg = 0.
for n, r in enumerate(recommend[:k]):
if r not in truth:
continue
dcg += 1. / np.log2(n + 2)
res_idcg = idcg(np.min([truth.size, k]))
if res_idcg == 0.:
return 0.
return dcg / res_idcg
|
takuti/flurs | flurs/utils/metric.py | auc | python | def auc(truth, recommend):
tp = correct = 0.
for r in recommend:
if r in truth:
# keep track number of true positives placed before
tp += 1.
else:
correct += tp
# number of all possible tp-fp pairs
pairs = tp * (recommend.size - tp)
# if there is no TP (or no FP), it's meaningless for this metric (i.e., AUC=0.5)
if pairs == 0:
return 0.5
return correct / pairs | Area under the ROC curve (AUC).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: AUC. | train | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/utils/metric.py#L90-L115 | null | import numpy as np
def count_true_positive(truth, recommend):
"""Count number of true positives from given sets of samples.
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
int: Number of true positives.
"""
tp = 0
for r in recommend:
if r in truth:
tp += 1
return tp
def recall(truth, recommend, k=None):
"""Recall@k.
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
k (int): Top-k items in `recommend` will be recommended.
Returns:
float: Recall@k.
"""
if len(truth) == 0:
if len(recommend) == 0:
return 1.
return 0.
if k is None:
k = len(recommend)
return count_true_positive(truth, recommend[:k]) / float(truth.size)
def precision(truth, recommend, k=None):
"""Precision@k.
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
k (int): Top-k items in `recommend` will be recommended.
Returns:
float: Precision@k.
"""
if len(recommend) == 0:
if len(truth) == 0:
return 1.
return 0.
if k is None:
k = len(recommend)
return count_true_positive(truth, recommend[:k]) / float(k)
def average_precision(truth, recommend):
"""Average Precision (AP).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: AP.
"""
if len(truth) == 0:
if len(recommend) == 0:
return 1.
return 0.
tp = accum = 0.
for n in range(recommend.size):
if recommend[n] in truth:
tp += 1.
accum += (tp / (n + 1.))
return accum / truth.size
def reciprocal_rank(truth, recommend):
"""Reciprocal Rank (RR).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: RR.
"""
for n in range(recommend.size):
if recommend[n] in truth:
return 1. / (n + 1)
return 0.
def mpr(truth, recommend):
"""Mean Percentile Rank (MPR).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: MPR.
"""
if len(recommend) == 0 and len(truth) == 0:
return 0. # best
elif len(truth) == 0 or len(truth) == 0:
return 100. # worst
accum = 0.
n_recommend = recommend.size
for t in truth:
r = np.where(recommend == t)[0][0] / float(n_recommend)
accum += r
return accum * 100. / truth.size
def ndcg(truth, recommend, k=None):
"""Normalized Discounted Cumulative Grain (NDCG).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
k (int): Top-k items in `recommend` will be recommended.
Returns:
float: NDCG.
"""
if k is None:
k = len(recommend)
def idcg(n_possible_truth):
res = 0.
for n in range(n_possible_truth):
res += 1. / np.log2(n + 2)
return res
dcg = 0.
for n, r in enumerate(recommend[:k]):
if r not in truth:
continue
dcg += 1. / np.log2(n + 2)
res_idcg = idcg(np.min([truth.size, k]))
if res_idcg == 0.:
return 0.
return dcg / res_idcg
|
takuti/flurs | flurs/utils/metric.py | reciprocal_rank | python | def reciprocal_rank(truth, recommend):
for n in range(recommend.size):
if recommend[n] in truth:
return 1. / (n + 1)
return 0. | Reciprocal Rank (RR).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: RR. | train | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/utils/metric.py#L118-L132 | null | import numpy as np
def count_true_positive(truth, recommend):
"""Count number of true positives from given sets of samples.
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
int: Number of true positives.
"""
tp = 0
for r in recommend:
if r in truth:
tp += 1
return tp
def recall(truth, recommend, k=None):
"""Recall@k.
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
k (int): Top-k items in `recommend` will be recommended.
Returns:
float: Recall@k.
"""
if len(truth) == 0:
if len(recommend) == 0:
return 1.
return 0.
if k is None:
k = len(recommend)
return count_true_positive(truth, recommend[:k]) / float(truth.size)
def precision(truth, recommend, k=None):
"""Precision@k.
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
k (int): Top-k items in `recommend` will be recommended.
Returns:
float: Precision@k.
"""
if len(recommend) == 0:
if len(truth) == 0:
return 1.
return 0.
if k is None:
k = len(recommend)
return count_true_positive(truth, recommend[:k]) / float(k)
def average_precision(truth, recommend):
"""Average Precision (AP).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: AP.
"""
if len(truth) == 0:
if len(recommend) == 0:
return 1.
return 0.
tp = accum = 0.
for n in range(recommend.size):
if recommend[n] in truth:
tp += 1.
accum += (tp / (n + 1.))
return accum / truth.size
def auc(truth, recommend):
"""Area under the ROC curve (AUC).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: AUC.
"""
tp = correct = 0.
for r in recommend:
if r in truth:
# keep track number of true positives placed before
tp += 1.
else:
correct += tp
# number of all possible tp-fp pairs
pairs = tp * (recommend.size - tp)
# if there is no TP (or no FP), it's meaningless for this metric (i.e., AUC=0.5)
if pairs == 0:
return 0.5
return correct / pairs
def mpr(truth, recommend):
"""Mean Percentile Rank (MPR).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: MPR.
"""
if len(recommend) == 0 and len(truth) == 0:
return 0. # best
elif len(truth) == 0 or len(truth) == 0:
return 100. # worst
accum = 0.
n_recommend = recommend.size
for t in truth:
r = np.where(recommend == t)[0][0] / float(n_recommend)
accum += r
return accum * 100. / truth.size
def ndcg(truth, recommend, k=None):
"""Normalized Discounted Cumulative Grain (NDCG).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
k (int): Top-k items in `recommend` will be recommended.
Returns:
float: NDCG.
"""
if k is None:
k = len(recommend)
def idcg(n_possible_truth):
res = 0.
for n in range(n_possible_truth):
res += 1. / np.log2(n + 2)
return res
dcg = 0.
for n, r in enumerate(recommend[:k]):
if r not in truth:
continue
dcg += 1. / np.log2(n + 2)
res_idcg = idcg(np.min([truth.size, k]))
if res_idcg == 0.:
return 0.
return dcg / res_idcg
|
takuti/flurs | flurs/utils/metric.py | mpr | python | def mpr(truth, recommend):
if len(recommend) == 0 and len(truth) == 0:
return 0. # best
elif len(truth) == 0 or len(truth) == 0:
return 100. # worst
accum = 0.
n_recommend = recommend.size
for t in truth:
r = np.where(recommend == t)[0][0] / float(n_recommend)
accum += r
return accum * 100. / truth.size | Mean Percentile Rank (MPR).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: MPR. | train | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/utils/metric.py#L135-L156 | null | import numpy as np
def count_true_positive(truth, recommend):
"""Count number of true positives from given sets of samples.
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
int: Number of true positives.
"""
tp = 0
for r in recommend:
if r in truth:
tp += 1
return tp
def recall(truth, recommend, k=None):
"""Recall@k.
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
k (int): Top-k items in `recommend` will be recommended.
Returns:
float: Recall@k.
"""
if len(truth) == 0:
if len(recommend) == 0:
return 1.
return 0.
if k is None:
k = len(recommend)
return count_true_positive(truth, recommend[:k]) / float(truth.size)
def precision(truth, recommend, k=None):
"""Precision@k.
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
k (int): Top-k items in `recommend` will be recommended.
Returns:
float: Precision@k.
"""
if len(recommend) == 0:
if len(truth) == 0:
return 1.
return 0.
if k is None:
k = len(recommend)
return count_true_positive(truth, recommend[:k]) / float(k)
def average_precision(truth, recommend):
"""Average Precision (AP).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: AP.
"""
if len(truth) == 0:
if len(recommend) == 0:
return 1.
return 0.
tp = accum = 0.
for n in range(recommend.size):
if recommend[n] in truth:
tp += 1.
accum += (tp / (n + 1.))
return accum / truth.size
def auc(truth, recommend):
"""Area under the ROC curve (AUC).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: AUC.
"""
tp = correct = 0.
for r in recommend:
if r in truth:
# keep track number of true positives placed before
tp += 1.
else:
correct += tp
# number of all possible tp-fp pairs
pairs = tp * (recommend.size - tp)
# if there is no TP (or no FP), it's meaningless for this metric (i.e., AUC=0.5)
if pairs == 0:
return 0.5
return correct / pairs
def reciprocal_rank(truth, recommend):
"""Reciprocal Rank (RR).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: RR.
"""
for n in range(recommend.size):
if recommend[n] in truth:
return 1. / (n + 1)
return 0.
def ndcg(truth, recommend, k=None):
"""Normalized Discounted Cumulative Grain (NDCG).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
k (int): Top-k items in `recommend` will be recommended.
Returns:
float: NDCG.
"""
if k is None:
k = len(recommend)
def idcg(n_possible_truth):
res = 0.
for n in range(n_possible_truth):
res += 1. / np.log2(n + 2)
return res
dcg = 0.
for n, r in enumerate(recommend[:k]):
if r not in truth:
continue
dcg += 1. / np.log2(n + 2)
res_idcg = idcg(np.min([truth.size, k]))
if res_idcg == 0.:
return 0.
return dcg / res_idcg
|
takuti/flurs | flurs/utils/metric.py | ndcg | python | def ndcg(truth, recommend, k=None):
if k is None:
k = len(recommend)
def idcg(n_possible_truth):
res = 0.
for n in range(n_possible_truth):
res += 1. / np.log2(n + 2)
return res
dcg = 0.
for n, r in enumerate(recommend[:k]):
if r not in truth:
continue
dcg += 1. / np.log2(n + 2)
res_idcg = idcg(np.min([truth.size, k]))
if res_idcg == 0.:
return 0.
return dcg / res_idcg | Normalized Discounted Cumulative Grain (NDCG).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
k (int): Top-k items in `recommend` will be recommended.
Returns:
float: NDCG. | train | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/utils/metric.py#L159-L189 | [
"def idcg(n_possible_truth):\n res = 0.\n for n in range(n_possible_truth):\n res += 1. / np.log2(n + 2)\n return res\n"
] | import numpy as np
def count_true_positive(truth, recommend):
"""Count number of true positives from given sets of samples.
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
int: Number of true positives.
"""
tp = 0
for r in recommend:
if r in truth:
tp += 1
return tp
def recall(truth, recommend, k=None):
"""Recall@k.
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
k (int): Top-k items in `recommend` will be recommended.
Returns:
float: Recall@k.
"""
if len(truth) == 0:
if len(recommend) == 0:
return 1.
return 0.
if k is None:
k = len(recommend)
return count_true_positive(truth, recommend[:k]) / float(truth.size)
def precision(truth, recommend, k=None):
"""Precision@k.
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
k (int): Top-k items in `recommend` will be recommended.
Returns:
float: Precision@k.
"""
if len(recommend) == 0:
if len(truth) == 0:
return 1.
return 0.
if k is None:
k = len(recommend)
return count_true_positive(truth, recommend[:k]) / float(k)
def average_precision(truth, recommend):
"""Average Precision (AP).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: AP.
"""
if len(truth) == 0:
if len(recommend) == 0:
return 1.
return 0.
tp = accum = 0.
for n in range(recommend.size):
if recommend[n] in truth:
tp += 1.
accum += (tp / (n + 1.))
return accum / truth.size
def auc(truth, recommend):
"""Area under the ROC curve (AUC).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: AUC.
"""
tp = correct = 0.
for r in recommend:
if r in truth:
# keep track number of true positives placed before
tp += 1.
else:
correct += tp
# number of all possible tp-fp pairs
pairs = tp * (recommend.size - tp)
# if there is no TP (or no FP), it's meaningless for this metric (i.e., AUC=0.5)
if pairs == 0:
return 0.5
return correct / pairs
def reciprocal_rank(truth, recommend):
"""Reciprocal Rank (RR).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: RR.
"""
for n in range(recommend.size):
if recommend[n] in truth:
return 1. / (n + 1)
return 0.
def mpr(truth, recommend):
"""Mean Percentile Rank (MPR).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: MPR.
"""
if len(recommend) == 0 and len(truth) == 0:
return 0. # best
elif len(truth) == 0 or len(truth) == 0:
return 100. # worst
accum = 0.
n_recommend = recommend.size
for t in truth:
r = np.where(recommend == t)[0][0] / float(n_recommend)
accum += r
return accum * 100. / truth.size
|
takuti/flurs | flurs/base.py | RecommenderMixin.initialize | python | def initialize(self, *args):
# number of observed users
self.n_user = 0
# store user data
self.users = {}
# number of observed items
self.n_item = 0
# store item data
self.items = {} | Initialize a recommender by resetting stored users and items. | train | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/base.py#L11-L24 | null | class RecommenderMixin(object):
"""Mixin injected into a model to make it a recommender.
"""
def is_new_user(self, u):
"""Check if user is new.
Args:
u (int): User index.
Returns:
boolean: Whether the user is new.
"""
return u not in self.users
def register(self, entity):
t = type(entity)
if t == User:
self.register_user(entity)
elif t == Item:
self.register_item(entity)
def register_user(self, user):
"""For new users, append their information into the dictionaries.
Args:
user (User): User.
"""
self.users[user.index] = {'known_items': set()}
self.n_user += 1
def is_new_item(self, i):
"""Check if item is new.
Args:
i (int): Item index.
Returns:
boolean: Whether the item is new.
"""
return i not in self.items
def register_item(self, item):
"""For new items, append their information into the dictionaries.
Args:
item (Item): Item.
"""
self.items[item.index] = {}
self.n_item += 1
def update(self, e, batch_train):
"""Update model parameters based on d, a sample represented as a dictionary.
Args:
e (Event): Observed event.
"""
pass
def score(self, user, candidates):
"""Compute scores for the pairs of given user and item candidates.
Args:
user (User): Target user.
candidates (numpy array; (# candidates, )): Target item' indices.
Returns:
numpy float array; (# candidates, ): Predicted values for the given user-candidates pairs.
"""
return
def recommend(self, user, candidates):
"""Recommend items for a user represented as a dictionary d.
First, scores are computed.
Next, `self.__scores2recos()` is called to convert the scores into a recommendation list.
Args:
user (User): Target user.
candidates (numpy array; (# target items, )): Target items' indices. Only these items are considered as the recommendation candidates.
Returns:
(numpy array, numpy array) : (Sorted list of items, Sorted scores).
"""
return
def scores2recos(self, scores, candidates, rev=False):
"""Get recommendation list for a user u_index based on scores.
Args:
scores (numpy array; (n_target_items,)):
Scores for the target items. Smaller score indicates a promising item.
candidates (numpy array; (# target items, )): Target items' indices. Only these items are considered as the recommendation candidates.
rev (bool): If true, return items in an descending order. A ascending order (i.e., smaller scores are more promising) is default.
Returns:
(numpy array, numpy array) : (Sorted list of items, Sorted scores).
"""
sorted_indices = np.argsort(scores)
if rev:
sorted_indices = sorted_indices[::-1]
return candidates[sorted_indices], scores[sorted_indices]
|
takuti/flurs | flurs/base.py | RecommenderMixin.register_user | python | def register_user(self, user):
self.users[user.index] = {'known_items': set()}
self.n_user += 1 | For new users, append their information into the dictionaries.
Args:
user (User): User. | train | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/base.py#L45-L53 | null | class RecommenderMixin(object):
"""Mixin injected into a model to make it a recommender.
"""
def initialize(self, *args):
"""Initialize a recommender by resetting stored users and items.
"""
# number of observed users
self.n_user = 0
# store user data
self.users = {}
# number of observed items
self.n_item = 0
# store item data
self.items = {}
def is_new_user(self, u):
"""Check if user is new.
Args:
u (int): User index.
Returns:
boolean: Whether the user is new.
"""
return u not in self.users
def register(self, entity):
t = type(entity)
if t == User:
self.register_user(entity)
elif t == Item:
self.register_item(entity)
def is_new_item(self, i):
"""Check if item is new.
Args:
i (int): Item index.
Returns:
boolean: Whether the item is new.
"""
return i not in self.items
def register_item(self, item):
"""For new items, append their information into the dictionaries.
Args:
item (Item): Item.
"""
self.items[item.index] = {}
self.n_item += 1
def update(self, e, batch_train):
"""Update model parameters based on d, a sample represented as a dictionary.
Args:
e (Event): Observed event.
"""
pass
def score(self, user, candidates):
"""Compute scores for the pairs of given user and item candidates.
Args:
user (User): Target user.
candidates (numpy array; (# candidates, )): Target item' indices.
Returns:
numpy float array; (# candidates, ): Predicted values for the given user-candidates pairs.
"""
return
def recommend(self, user, candidates):
"""Recommend items for a user represented as a dictionary d.
First, scores are computed.
Next, `self.__scores2recos()` is called to convert the scores into a recommendation list.
Args:
user (User): Target user.
candidates (numpy array; (# target items, )): Target items' indices. Only these items are considered as the recommendation candidates.
Returns:
(numpy array, numpy array) : (Sorted list of items, Sorted scores).
"""
return
def scores2recos(self, scores, candidates, rev=False):
"""Get recommendation list for a user u_index based on scores.
Args:
scores (numpy array; (n_target_items,)):
Scores for the target items. Smaller score indicates a promising item.
candidates (numpy array; (# target items, )): Target items' indices. Only these items are considered as the recommendation candidates.
rev (bool): If true, return items in an descending order. A ascending order (i.e., smaller scores are more promising) is default.
Returns:
(numpy array, numpy array) : (Sorted list of items, Sorted scores).
"""
sorted_indices = np.argsort(scores)
if rev:
sorted_indices = sorted_indices[::-1]
return candidates[sorted_indices], scores[sorted_indices]
|
takuti/flurs | flurs/base.py | RecommenderMixin.scores2recos | python | def scores2recos(self, scores, candidates, rev=False):
sorted_indices = np.argsort(scores)
if rev:
sorted_indices = sorted_indices[::-1]
return candidates[sorted_indices], scores[sorted_indices] | Get recommendation list for a user u_index based on scores.
Args:
scores (numpy array; (n_target_items,)):
Scores for the target items. Smaller score indicates a promising item.
candidates (numpy array; (# target items, )): Target items' indices. Only these items are considered as the recommendation candidates.
rev (bool): If true, return items in an descending order. A ascending order (i.e., smaller scores are more promising) is default.
Returns:
(numpy array, numpy array) : (Sorted list of items, Sorted scores). | train | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/base.py#L115-L133 | null | class RecommenderMixin(object):
"""Mixin injected into a model to make it a recommender.
"""
def initialize(self, *args):
"""Initialize a recommender by resetting stored users and items.
"""
# number of observed users
self.n_user = 0
# store user data
self.users = {}
# number of observed items
self.n_item = 0
# store item data
self.items = {}
def is_new_user(self, u):
"""Check if user is new.
Args:
u (int): User index.
Returns:
boolean: Whether the user is new.
"""
return u not in self.users
def register(self, entity):
t = type(entity)
if t == User:
self.register_user(entity)
elif t == Item:
self.register_item(entity)
def register_user(self, user):
"""For new users, append their information into the dictionaries.
Args:
user (User): User.
"""
self.users[user.index] = {'known_items': set()}
self.n_user += 1
def is_new_item(self, i):
"""Check if item is new.
Args:
i (int): Item index.
Returns:
boolean: Whether the item is new.
"""
return i not in self.items
def register_item(self, item):
"""For new items, append their information into the dictionaries.
Args:
item (Item): Item.
"""
self.items[item.index] = {}
self.n_item += 1
def update(self, e, batch_train):
"""Update model parameters based on d, a sample represented as a dictionary.
Args:
e (Event): Observed event.
"""
pass
def score(self, user, candidates):
"""Compute scores for the pairs of given user and item candidates.
Args:
user (User): Target user.
candidates (numpy array; (# candidates, )): Target item' indices.
Returns:
numpy float array; (# candidates, ): Predicted values for the given user-candidates pairs.
"""
return
def recommend(self, user, candidates):
"""Recommend items for a user represented as a dictionary d.
First, scores are computed.
Next, `self.__scores2recos()` is called to convert the scores into a recommendation list.
Args:
user (User): Target user.
candidates (numpy array; (# target items, )): Target items' indices. Only these items are considered as the recommendation candidates.
Returns:
(numpy array, numpy array) : (Sorted list of items, Sorted scores).
"""
return
|
takuti/flurs | flurs/evaluator.py | Evaluator.fit | python | def fit(self, train_events, test_events, n_epoch=1):
# make initial status for batch training
for e in train_events:
self.__validate(e)
self.rec.users[e.user.index]['known_items'].add(e.item.index)
self.item_buffer.append(e.item.index)
# for batch evaluation, temporarily save new users info
for e in test_events:
self.__validate(e)
self.item_buffer.append(e.item.index)
self.__batch_update(train_events, test_events, n_epoch)
# batch test events are considered as a new observations;
# the model is incrementally updated based on them before the incremental evaluation step
for e in test_events:
self.rec.users[e.user.index]['known_items'].add(e.item.index)
self.rec.update(e) | Train a model using the first 30% positive events to avoid cold-start.
Evaluation of this batch training is done by using the next 20% positive events.
After the batch SGD training, the models are incrementally updated by using the 20% test events.
Args:
train_events (list of Event): Positive training events (0-30%).
test_events (list of Event): Test events (30-50%).
n_epoch (int): Number of epochs for the batch training. | train | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/evaluator.py#L35-L64 | [
"def __validate(self, e):\n self.__validate_user(e)\n self.__validate_item(e)\n",
"def __batch_update(self, train_events, test_events, n_epoch):\n \"\"\"Batch update called by the fitting method.\n\n Args:\n train_events (list of Event): Positive training events.\n test_events (list of Event): Test events.\n n_epoch (int): Number of epochs for the batch training.\n\n \"\"\"\n for epoch in range(n_epoch):\n # SGD requires us to shuffle events in each iteration\n # * if n_epoch == 1\n # => shuffle is not required because it is a deterministic training (i.e. matrix sketching)\n if n_epoch != 1:\n np.random.shuffle(train_events)\n\n # train\n for e in train_events:\n self.rec.update(e, batch_train=True)\n\n # test\n MPR = self.__batch_evaluate(test_events)\n if self.debug:\n logger.debug('epoch %2d: MPR = %f' % (epoch + 1, MPR))\n"
] | class Evaluator(object):
"""Base class for experimentation of the incremental models with positive-only feedback.
"""
def __init__(self, recommender, repeat=True, maxlen=None, debug=False):
"""Set/initialize parameters.
Args:
recommender (Recommender): Instance of a recommender which has been initialized.
repeat (boolean): Choose whether the same item can be repeatedly interacted by the same user.
maxlen (int): Size of an item buffer which stores most recently observed items.
"""
self.rec = recommender
self.feature_rec = issubclass(recommender.__class__, FeatureRecommenderMixin)
self.repeat = repeat
# create a ring buffer
# save items which are observed in most recent `maxlen` events
self.item_buffer = deque(maxlen=maxlen)
self.debug = debug
def evaluate(self, test_events):
"""Iterate recommend/update procedure and compute incremental recall.
Args:
test_events (list of Event): Positive test events.
Returns:
list of tuples: (rank, recommend time, update time)
"""
for i, e in enumerate(test_events):
self.__validate(e)
# target items (all or unobserved depending on a detaset)
unobserved = set(self.item_buffer)
if not self.repeat:
unobserved -= self.rec.users[e.user.index]['known_items']
# item i interacted by user u must be in the recommendation candidate
# even if it is a new item
unobserved.add(e.item.index)
candidates = np.asarray(list(unobserved))
# make top-{at} recommendation for the 1001 items
start = time.clock()
recos, scores = self.__recommend(e, candidates)
recommend_time = (time.clock() - start)
rank = np.where(recos == e.item.index)[0][0]
# Step 2: update the model with the observed event
self.rec.users[e.user.index]['known_items'].add(e.item.index)
start = time.clock()
self.rec.update(e)
update_time = (time.clock() - start)
self.item_buffer.append(e.item.index)
# (top-1 score, where the correct item is ranked, rec time, update time)
yield scores[0], rank, recommend_time, update_time
def __recommend(self, e, candidates):
if self.feature_rec:
return self.rec.recommend(e.user, candidates, e.context)
else:
return self.rec.recommend(e.user, candidates)
def __validate(self, e):
self.__validate_user(e)
self.__validate_item(e)
def __validate_user(self, e):
if self.rec.is_new_user(e.user.index):
self.rec.register_user(e.user)
def __validate_item(self, e):
if self.rec.is_new_item(e.item.index):
self.rec.register_item(e.item)
def __batch_update(self, train_events, test_events, n_epoch):
"""Batch update called by the fitting method.
Args:
train_events (list of Event): Positive training events.
test_events (list of Event): Test events.
n_epoch (int): Number of epochs for the batch training.
"""
for epoch in range(n_epoch):
# SGD requires us to shuffle events in each iteration
# * if n_epoch == 1
# => shuffle is not required because it is a deterministic training (i.e. matrix sketching)
if n_epoch != 1:
np.random.shuffle(train_events)
# train
for e in train_events:
self.rec.update(e, batch_train=True)
# test
MPR = self.__batch_evaluate(test_events)
if self.debug:
logger.debug('epoch %2d: MPR = %f' % (epoch + 1, MPR))
def __batch_evaluate(self, test_events):
"""Evaluate the current model by using the given test events.
Args:
test_events (list of Event): Current model is evaluated by these events.
Returns:
float: Mean Percentile Rank for the test set.
"""
percentiles = np.zeros(len(test_events))
all_items = set(self.item_buffer)
for i, e in enumerate(test_events):
# check if the data allows users to interact the same items repeatedly
unobserved = all_items
if not self.repeat:
# make recommendation for all unobserved items
unobserved -= self.rec.users[e.user.index]['known_items']
# true item itself must be in the recommendation candidates
unobserved.add(e.item.index)
candidates = np.asarray(list(unobserved))
recos, scores = self.__recommend(e, candidates)
pos = np.where(recos == e.item.index)[0][0]
percentiles[i] = pos / (len(recos) - 1) * 100
return np.mean(percentiles)
|
takuti/flurs | flurs/evaluator.py | Evaluator.evaluate | python | def evaluate(self, test_events):
for i, e in enumerate(test_events):
self.__validate(e)
# target items (all or unobserved depending on a detaset)
unobserved = set(self.item_buffer)
if not self.repeat:
unobserved -= self.rec.users[e.user.index]['known_items']
# item i interacted by user u must be in the recommendation candidate
# even if it is a new item
unobserved.add(e.item.index)
candidates = np.asarray(list(unobserved))
# make top-{at} recommendation for the 1001 items
start = time.clock()
recos, scores = self.__recommend(e, candidates)
recommend_time = (time.clock() - start)
rank = np.where(recos == e.item.index)[0][0]
# Step 2: update the model with the observed event
self.rec.users[e.user.index]['known_items'].add(e.item.index)
start = time.clock()
self.rec.update(e)
update_time = (time.clock() - start)
self.item_buffer.append(e.item.index)
# (top-1 score, where the correct item is ranked, rec time, update time)
yield scores[0], rank, recommend_time, update_time | Iterate recommend/update procedure and compute incremental recall.
Args:
test_events (list of Event): Positive test events.
Returns:
list of tuples: (rank, recommend time, update time) | train | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/evaluator.py#L66-L106 | [
"def __recommend(self, e, candidates):\n if self.feature_rec:\n return self.rec.recommend(e.user, candidates, e.context)\n else:\n return self.rec.recommend(e.user, candidates)\n",
"def __validate(self, e):\n self.__validate_user(e)\n self.__validate_item(e)\n"
] | class Evaluator(object):
"""Base class for experimentation of the incremental models with positive-only feedback.
"""
def __init__(self, recommender, repeat=True, maxlen=None, debug=False):
"""Set/initialize parameters.
Args:
recommender (Recommender): Instance of a recommender which has been initialized.
repeat (boolean): Choose whether the same item can be repeatedly interacted by the same user.
maxlen (int): Size of an item buffer which stores most recently observed items.
"""
self.rec = recommender
self.feature_rec = issubclass(recommender.__class__, FeatureRecommenderMixin)
self.repeat = repeat
# create a ring buffer
# save items which are observed in most recent `maxlen` events
self.item_buffer = deque(maxlen=maxlen)
self.debug = debug
def fit(self, train_events, test_events, n_epoch=1):
"""Train a model using the first 30% positive events to avoid cold-start.
Evaluation of this batch training is done by using the next 20% positive events.
After the batch SGD training, the models are incrementally updated by using the 20% test events.
Args:
train_events (list of Event): Positive training events (0-30%).
test_events (list of Event): Test events (30-50%).
n_epoch (int): Number of epochs for the batch training.
"""
# make initial status for batch training
for e in train_events:
self.__validate(e)
self.rec.users[e.user.index]['known_items'].add(e.item.index)
self.item_buffer.append(e.item.index)
# for batch evaluation, temporarily save new users info
for e in test_events:
self.__validate(e)
self.item_buffer.append(e.item.index)
self.__batch_update(train_events, test_events, n_epoch)
# batch test events are considered as a new observations;
# the model is incrementally updated based on them before the incremental evaluation step
for e in test_events:
self.rec.users[e.user.index]['known_items'].add(e.item.index)
self.rec.update(e)
def __recommend(self, e, candidates):
if self.feature_rec:
return self.rec.recommend(e.user, candidates, e.context)
else:
return self.rec.recommend(e.user, candidates)
def __validate(self, e):
self.__validate_user(e)
self.__validate_item(e)
def __validate_user(self, e):
if self.rec.is_new_user(e.user.index):
self.rec.register_user(e.user)
def __validate_item(self, e):
if self.rec.is_new_item(e.item.index):
self.rec.register_item(e.item)
def __batch_update(self, train_events, test_events, n_epoch):
"""Batch update called by the fitting method.
Args:
train_events (list of Event): Positive training events.
test_events (list of Event): Test events.
n_epoch (int): Number of epochs for the batch training.
"""
for epoch in range(n_epoch):
# SGD requires us to shuffle events in each iteration
# * if n_epoch == 1
# => shuffle is not required because it is a deterministic training (i.e. matrix sketching)
if n_epoch != 1:
np.random.shuffle(train_events)
# train
for e in train_events:
self.rec.update(e, batch_train=True)
# test
MPR = self.__batch_evaluate(test_events)
if self.debug:
logger.debug('epoch %2d: MPR = %f' % (epoch + 1, MPR))
def __batch_evaluate(self, test_events):
"""Evaluate the current model by using the given test events.
Args:
test_events (list of Event): Current model is evaluated by these events.
Returns:
float: Mean Percentile Rank for the test set.
"""
percentiles = np.zeros(len(test_events))
all_items = set(self.item_buffer)
for i, e in enumerate(test_events):
# check if the data allows users to interact the same items repeatedly
unobserved = all_items
if not self.repeat:
# make recommendation for all unobserved items
unobserved -= self.rec.users[e.user.index]['known_items']
# true item itself must be in the recommendation candidates
unobserved.add(e.item.index)
candidates = np.asarray(list(unobserved))
recos, scores = self.__recommend(e, candidates)
pos = np.where(recos == e.item.index)[0][0]
percentiles[i] = pos / (len(recos) - 1) * 100
return np.mean(percentiles)
|
takuti/flurs | flurs/evaluator.py | Evaluator.__batch_update | python | def __batch_update(self, train_events, test_events, n_epoch):
for epoch in range(n_epoch):
# SGD requires us to shuffle events in each iteration
# * if n_epoch == 1
# => shuffle is not required because it is a deterministic training (i.e. matrix sketching)
if n_epoch != 1:
np.random.shuffle(train_events)
# train
for e in train_events:
self.rec.update(e, batch_train=True)
# test
MPR = self.__batch_evaluate(test_events)
if self.debug:
logger.debug('epoch %2d: MPR = %f' % (epoch + 1, MPR)) | Batch update called by the fitting method.
Args:
train_events (list of Event): Positive training events.
test_events (list of Event): Test events.
n_epoch (int): Number of epochs for the batch training. | train | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/evaluator.py#L126-L149 | [
"def __batch_evaluate(self, test_events):\n \"\"\"Evaluate the current model by using the given test events.\n\n Args:\n test_events (list of Event): Current model is evaluated by these events.\n\n Returns:\n float: Mean Percentile Rank for the test set.\n\n \"\"\"\n percentiles = np.zeros(len(test_events))\n\n all_items = set(self.item_buffer)\n for i, e in enumerate(test_events):\n\n # check if the data allows users to interact the same items repeatedly\n unobserved = all_items\n if not self.repeat:\n # make recommendation for all unobserved items\n unobserved -= self.rec.users[e.user.index]['known_items']\n # true item itself must be in the recommendation candidates\n unobserved.add(e.item.index)\n\n candidates = np.asarray(list(unobserved))\n recos, scores = self.__recommend(e, candidates)\n\n pos = np.where(recos == e.item.index)[0][0]\n percentiles[i] = pos / (len(recos) - 1) * 100\n\n return np.mean(percentiles)\n"
] | class Evaluator(object):
"""Base class for experimentation of the incremental models with positive-only feedback.
"""
def __init__(self, recommender, repeat=True, maxlen=None, debug=False):
"""Set/initialize parameters.
Args:
recommender (Recommender): Instance of a recommender which has been initialized.
repeat (boolean): Choose whether the same item can be repeatedly interacted by the same user.
maxlen (int): Size of an item buffer which stores most recently observed items.
"""
self.rec = recommender
self.feature_rec = issubclass(recommender.__class__, FeatureRecommenderMixin)
self.repeat = repeat
# create a ring buffer
# save items which are observed in most recent `maxlen` events
self.item_buffer = deque(maxlen=maxlen)
self.debug = debug
def fit(self, train_events, test_events, n_epoch=1):
"""Train a model using the first 30% positive events to avoid cold-start.
Evaluation of this batch training is done by using the next 20% positive events.
After the batch SGD training, the models are incrementally updated by using the 20% test events.
Args:
train_events (list of Event): Positive training events (0-30%).
test_events (list of Event): Test events (30-50%).
n_epoch (int): Number of epochs for the batch training.
"""
# make initial status for batch training
for e in train_events:
self.__validate(e)
self.rec.users[e.user.index]['known_items'].add(e.item.index)
self.item_buffer.append(e.item.index)
# for batch evaluation, temporarily save new users info
for e in test_events:
self.__validate(e)
self.item_buffer.append(e.item.index)
self.__batch_update(train_events, test_events, n_epoch)
# batch test events are considered as a new observations;
# the model is incrementally updated based on them before the incremental evaluation step
for e in test_events:
self.rec.users[e.user.index]['known_items'].add(e.item.index)
self.rec.update(e)
def evaluate(self, test_events):
"""Iterate recommend/update procedure and compute incremental recall.
Args:
test_events (list of Event): Positive test events.
Returns:
list of tuples: (rank, recommend time, update time)
"""
for i, e in enumerate(test_events):
self.__validate(e)
# target items (all or unobserved depending on a detaset)
unobserved = set(self.item_buffer)
if not self.repeat:
unobserved -= self.rec.users[e.user.index]['known_items']
# item i interacted by user u must be in the recommendation candidate
# even if it is a new item
unobserved.add(e.item.index)
candidates = np.asarray(list(unobserved))
# make top-{at} recommendation for the 1001 items
start = time.clock()
recos, scores = self.__recommend(e, candidates)
recommend_time = (time.clock() - start)
rank = np.where(recos == e.item.index)[0][0]
# Step 2: update the model with the observed event
self.rec.users[e.user.index]['known_items'].add(e.item.index)
start = time.clock()
self.rec.update(e)
update_time = (time.clock() - start)
self.item_buffer.append(e.item.index)
# (top-1 score, where the correct item is ranked, rec time, update time)
yield scores[0], rank, recommend_time, update_time
def __recommend(self, e, candidates):
if self.feature_rec:
return self.rec.recommend(e.user, candidates, e.context)
else:
return self.rec.recommend(e.user, candidates)
def __validate(self, e):
self.__validate_user(e)
self.__validate_item(e)
def __validate_user(self, e):
if self.rec.is_new_user(e.user.index):
self.rec.register_user(e.user)
def __validate_item(self, e):
if self.rec.is_new_item(e.item.index):
self.rec.register_item(e.item)
def __batch_evaluate(self, test_events):
"""Evaluate the current model by using the given test events.
Args:
test_events (list of Event): Current model is evaluated by these events.
Returns:
float: Mean Percentile Rank for the test set.
"""
percentiles = np.zeros(len(test_events))
all_items = set(self.item_buffer)
for i, e in enumerate(test_events):
# check if the data allows users to interact the same items repeatedly
unobserved = all_items
if not self.repeat:
# make recommendation for all unobserved items
unobserved -= self.rec.users[e.user.index]['known_items']
# true item itself must be in the recommendation candidates
unobserved.add(e.item.index)
candidates = np.asarray(list(unobserved))
recos, scores = self.__recommend(e, candidates)
pos = np.where(recos == e.item.index)[0][0]
percentiles[i] = pos / (len(recos) - 1) * 100
return np.mean(percentiles)
|
takuti/flurs | flurs/evaluator.py | Evaluator.__batch_evaluate | python | def __batch_evaluate(self, test_events):
percentiles = np.zeros(len(test_events))
all_items = set(self.item_buffer)
for i, e in enumerate(test_events):
# check if the data allows users to interact the same items repeatedly
unobserved = all_items
if not self.repeat:
# make recommendation for all unobserved items
unobserved -= self.rec.users[e.user.index]['known_items']
# true item itself must be in the recommendation candidates
unobserved.add(e.item.index)
candidates = np.asarray(list(unobserved))
recos, scores = self.__recommend(e, candidates)
pos = np.where(recos == e.item.index)[0][0]
percentiles[i] = pos / (len(recos) - 1) * 100
return np.mean(percentiles) | Evaluate the current model by using the given test events.
Args:
test_events (list of Event): Current model is evaluated by these events.
Returns:
float: Mean Percentile Rank for the test set. | train | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/evaluator.py#L151-L180 | null | class Evaluator(object):
"""Base class for experimentation of the incremental models with positive-only feedback.
"""
def __init__(self, recommender, repeat=True, maxlen=None, debug=False):
"""Set/initialize parameters.
Args:
recommender (Recommender): Instance of a recommender which has been initialized.
repeat (boolean): Choose whether the same item can be repeatedly interacted by the same user.
maxlen (int): Size of an item buffer which stores most recently observed items.
"""
self.rec = recommender
self.feature_rec = issubclass(recommender.__class__, FeatureRecommenderMixin)
self.repeat = repeat
# create a ring buffer
# save items which are observed in most recent `maxlen` events
self.item_buffer = deque(maxlen=maxlen)
self.debug = debug
def fit(self, train_events, test_events, n_epoch=1):
"""Train a model using the first 30% positive events to avoid cold-start.
Evaluation of this batch training is done by using the next 20% positive events.
After the batch SGD training, the models are incrementally updated by using the 20% test events.
Args:
train_events (list of Event): Positive training events (0-30%).
test_events (list of Event): Test events (30-50%).
n_epoch (int): Number of epochs for the batch training.
"""
# make initial status for batch training
for e in train_events:
self.__validate(e)
self.rec.users[e.user.index]['known_items'].add(e.item.index)
self.item_buffer.append(e.item.index)
# for batch evaluation, temporarily save new users info
for e in test_events:
self.__validate(e)
self.item_buffer.append(e.item.index)
self.__batch_update(train_events, test_events, n_epoch)
# batch test events are considered as a new observations;
# the model is incrementally updated based on them before the incremental evaluation step
for e in test_events:
self.rec.users[e.user.index]['known_items'].add(e.item.index)
self.rec.update(e)
def evaluate(self, test_events):
"""Iterate recommend/update procedure and compute incremental recall.
Args:
test_events (list of Event): Positive test events.
Returns:
list of tuples: (rank, recommend time, update time)
"""
for i, e in enumerate(test_events):
self.__validate(e)
# target items (all or unobserved depending on a detaset)
unobserved = set(self.item_buffer)
if not self.repeat:
unobserved -= self.rec.users[e.user.index]['known_items']
# item i interacted by user u must be in the recommendation candidate
# even if it is a new item
unobserved.add(e.item.index)
candidates = np.asarray(list(unobserved))
# make top-{at} recommendation for the 1001 items
start = time.clock()
recos, scores = self.__recommend(e, candidates)
recommend_time = (time.clock() - start)
rank = np.where(recos == e.item.index)[0][0]
# Step 2: update the model with the observed event
self.rec.users[e.user.index]['known_items'].add(e.item.index)
start = time.clock()
self.rec.update(e)
update_time = (time.clock() - start)
self.item_buffer.append(e.item.index)
# (top-1 score, where the correct item is ranked, rec time, update time)
yield scores[0], rank, recommend_time, update_time
def __recommend(self, e, candidates):
if self.feature_rec:
return self.rec.recommend(e.user, candidates, e.context)
else:
return self.rec.recommend(e.user, candidates)
def __validate(self, e):
self.__validate_user(e)
self.__validate_item(e)
def __validate_user(self, e):
if self.rec.is_new_user(e.user.index):
self.rec.register_user(e.user)
def __validate_item(self, e):
if self.rec.is_new_item(e.item.index):
self.rec.register_item(e.item)
def __batch_update(self, train_events, test_events, n_epoch):
"""Batch update called by the fitting method.
Args:
train_events (list of Event): Positive training events.
test_events (list of Event): Test events.
n_epoch (int): Number of epochs for the batch training.
"""
for epoch in range(n_epoch):
# SGD requires us to shuffle events in each iteration
# * if n_epoch == 1
# => shuffle is not required because it is a deterministic training (i.e. matrix sketching)
if n_epoch != 1:
np.random.shuffle(train_events)
# train
for e in train_events:
self.rec.update(e, batch_train=True)
# test
MPR = self.__batch_evaluate(test_events)
if self.debug:
logger.debug('epoch %2d: MPR = %f' % (epoch + 1, MPR))
|
BYU-Hydroinformatics/HydroErr | HydroErr/HydroErr.py | me | python | def me(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
# Treating missing values
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero)
return np.mean(simulated_array - observed_array) | Compute the mean error of the simulated and observed data.
.. image:: /pictures/ME.png
**Range:** -inf < MAE < inf, data units, closer to zero is better, indicates bias.
**Notes:** The mean error (ME) measures the difference between the simulated data and the
observed data. For the mean error, a smaller number indicates a better fit to the original
data. Note that if the error is in the form of random noise, the mean error will be very small,
which can skew the accuracy of this metric. ME is cumulative and will be small even if there
are large positive and negative errors that balance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean error value.
Examples
--------
Note that in this example the random noise cancels, leaving a very small ME.
>>> import HydroErr as he
>>> import numpy as np
>>> # Seed for reproducibility
>>> np.random.seed(54839)
>>> x = np.arange(100) / 20
>>> sim = np.sin(x) + 2
>>> obs = sim * (((np.random.rand(100) - 0.5) / 10) + 1)
>>> he.me(sim, obs)
-0.006832220968967168
References
----------
- Fisher, R.A., 1920. A Mathematical Examination of the Methods of Determining the Accuracy of
an Observation by the Mean Error, and by the Mean Square Error. Monthly Notices of the Royal
Astronomical Society 80 758 - 770. | train | https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L39-L114 | [
"def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,\n remove_neg=False, remove_zero=False):\n \"\"\"Removes the nan, negative, and inf values in two numpy arrays\"\"\"\n sim_copy = np.copy(simulated_array)\n obs_copy = np.copy(observed_array)\n\n # Checking to see if the vectors are the same length\n assert sim_copy.ndim == 1, \"The simulated array is not one dimensional.\"\n assert obs_copy.ndim == 1, \"The observed array is not one dimensional.\"\n\n if sim_copy.size != obs_copy.size:\n raise RuntimeError(\"The two ndarrays are not the same size.\")\n\n # Treat missing data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain nan values\n all_treatment_array = np.ones(obs_copy.size, dtype=bool)\n\n if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_nan = np.isnan(sim_copy)\n obs_nan = np.isnan(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_nan] = replace_nan\n obs_copy[obs_nan] = replace_nan\n\n warnings.warn(\"Elements(s) {} contained NaN values in the simulated array and \"\n \"elements(s) {} contained NaN values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_nan)[0],\n np.where(obs_nan)[0]),\n UserWarning)\n else:\n # Getting the indices of the nan values, combining them, and informing user.\n nan_indices_fcst = ~np.isnan(sim_copy)\n nan_indices_obs = ~np.isnan(obs_copy)\n all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)\n\n warnings.warn(\"Row(s) {} contained NaN values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_nan_indices)[0]),\n UserWarning)\n\n if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_inf = np.isinf(sim_copy)\n obs_inf = np.isinf(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_inf] = replace_inf\n obs_copy[obs_inf] = replace_inf\n\n warnings.warn(\"Elements(s) {} contained Inf values in the simulated array and \"\n \"elements(s) {} contained Inf values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_inf)[0],\n np.where(obs_inf)[0]),\n UserWarning)\n else:\n inf_indices_fcst = ~(np.isinf(sim_copy))\n inf_indices_obs = ~np.isinf(obs_copy)\n all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)\n\n warnings.warn(\n \"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows \"\n \"are zero indexed).\".format(np.where(~all_inf_indices)[0]),\n UserWarning\n )\n\n # Treat zero data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain zero values\n if remove_zero:\n if (obs_copy == 0).any() or (sim_copy == 0).any():\n zero_indices_fcst = ~(sim_copy == 0)\n zero_indices_obs = ~(obs_copy == 0)\n all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)\n\n warnings.warn(\n \"Row(s) {} contained zero values and the row(s) have been removed (Rows are \"\n \"zero indexed).\".format(np.where(~all_zero_indices)[0]),\n UserWarning\n )\n\n # Treat negative data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain negative values\n\n # Ignore runtime warnings from comparing\n if remove_neg:\n with np.errstate(invalid='ignore'):\n obs_copy_bool = obs_copy < 0\n sim_copy_bool = sim_copy < 0\n\n if obs_copy_bool.any() or sim_copy_bool.any():\n neg_indices_fcst = ~sim_copy_bool\n neg_indices_obs = ~obs_copy_bool\n all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)\n\n warnings.warn(\"Row(s) {} contained negative values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_neg_indices)[0]),\n UserWarning)\n\n obs_copy = obs_copy[all_treatment_array]\n sim_copy = sim_copy[all_treatment_array]\n\n return sim_copy, obs_copy\n"
] | # -*- coding: utf-8 -*-
"""
HydroErr contains a library of goodness of fit metrics that measure hydrologic skill.
Each metric is contained in function, and every function has the parameters to treat missing values as
well as remove zero and negative values from the timeseries data.
Each function contains two properties, name and abbr. These can be used in the Hydrostats package when creating tables
and adding metrics to the plots. Link to the hydrostats package: https://github.com/BYU-Hydroinformatics/Hydrostats.
An example of this functionality is shown below.
>>> import HydroErr as he
>>>
>>> he.acc.name
'Anomaly Correlation Coefficient'
>>> he.acc.abbr
'ACC'
"""
from __future__ import division
import numpy as np
from scipy.stats import gmean, rankdata
import warnings
__all__ = ['me', 'mae', 'mse', 'mle', 'male', 'msle', 'mde', 'mdae', 'mdse', 'ed', 'ned', 'rmse',
'rmsle', 'nrmse_range', 'nrmse_mean', 'nrmse_iqr', 'irmse', 'mase', 'r_squared',
'pearson_r', 'spearman_r', 'acc', 'mape', 'mapd', 'maape', 'smape1', 'smape2', 'd', 'd1',
'dmod', 'drel', 'dr', 'watt_m', 'mb_r', 'nse', 'nse_mod', 'nse_rel', 'kge_2009',
'kge_2012', 'lm_index', 'd1_p', 've', 'sa', 'sc', 'sid', 'sga', 'h1_mhe', 'h1_mahe',
'h1_rmshe', 'h2_mhe', 'h2_mahe', 'h2_rmshe', 'h3_mhe', 'h3_mahe', 'h3_rmshe', 'h4_mhe',
'h4_mahe', 'h4_rmshe', 'h5_mhe', 'h5_mahe', 'h5_rmshe', 'h6_mhe', 'h6_mahe', 'h6_rmshe',
'h7_mhe', 'h7_mahe', 'h7_rmshe', 'h8_mhe', 'h8_mahe', 'h8_rmshe', 'h10_mhe', 'h10_mahe',
'h10_rmshe', 'g_mean_diff', 'mean_var']
####################################################################################################
# General and Hydrological Error Metrics #
####################################################################################################
def mae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute error of the simulated and observed data.
.. image:: /pictures/MAE.png
**Range:** 0 ≤ MAE < inf, data units, smaller is better.
**Notes:** The ME measures the absolute difference between the simulated data and the observed
data. For the mean abolute error, a smaller number indicates a better fit to the original data.
Also note that random errors do not cancel. Also referred to as an L1-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute error value.
References
----------
- Willmott, Cort J., and Kenji Matsuura. “Advantages of the Mean Absolute Error (MAE) over the
Root Mean Square Error (RMSE) in Assessing Average Model Performance.” Climate Research 30,
no. 1 (2005): 79–82.
- Willmott, Cort J., and Kenji Matsuura. “On the Use of Dimensioned Measures of Error to
Evaluate the Performance of Spatial Interpolators.” International Journal of Geographical
Information Science 20, no. 1 (2006): 89–102.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mae(sim, obs)
0.5666666666666665
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean(np.absolute(simulated_array - observed_array))
def mse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared error of the simulated and observed data.
.. image:: /pictures/MSE.png
**Range:** 0 ≤ MSE < inf, data units squared, smaller is better.
**Notes:** Random errors do not cancel, highlights larger errors, also referred to as a
squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mse(sim, obs)
0.4333333333333333
References
----------
- Wang, Zhou, and Alan C. Bovik. “Mean Squared Error: Love It or Leave It? A New Look at Signal
Fidelity Measures.” IEEE Signal Processing Magazine 26, no. 1 (2009): 98–117.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean((simulated_array - observed_array) ** 2)
def mle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean log error of the simulated and observed data.
.. image:: /pictures/MLE.png
**Range:** -inf < MLE < inf, data units, closer to zero is better.
**Notes** Same as the mean erro (ME) only use log ratios as the error term. Limits the impact of outliers, more
evenly weights high and low data values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mle(sim, obs)
0.002961767058151136
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(sim_log - obs_log)
def male(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean absolute log error of the simulated and observed data.
.. image:: /pictures/MALE.png
**Range:** 0 ≤ MALE < inf, data units squared, smaller is better.
**Notes** Same as MAE only use log ratios as the error term. Limits the impact of outliers,
more evenly weights high and low flows.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.male(sim, obs), 6)
0.090417
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(np.abs(sim_log - obs_log))
def msle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared log error of the simulated and observed data.
.. image:: /pictures/MSLE.png
**Range:** 0 ≤ MSLE < inf, data units squared, smaller is better.
**Notes** Same as the mean squared error (MSE) only use log ratios as the error term. Limits
the impact of outliers, more evenly weights high and low values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.msle(sim, obs), 6)
0.010426
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean((sim_log - obs_log) ** 2)
def mde(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median error (MdE) between the simulated and observed data.
.. image:: /pictures/MdE.png
**Range** -inf < MdE < inf, closer to zero is better.
**Notes** This metric indicates bias. It is similar to the mean error (ME), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mde(sim, obs)
-0.10000000000000009
Returns
-------
float
The median error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(simulated_array - observed_array)
def mdae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median absolute error (MdAE) between the simulated and observed data.
.. image:: /pictures/MdAE.png
**Range** 0 ≤ MdAE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean absolute error (MAE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdae(sim, obs)
0.75
Returns
-------
float
The median absolute error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(np.abs(simulated_array - observed_array))
def mdse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median squared error (MdSE) between the simulated and observed data.
.. image:: /pictures/MdSE.png
**Range** 0 ≤ MdSE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean squared error (MSE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdse(sim, obs)
0.625
Returns
-------
float
The median squared error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median((simulated_array - observed_array) ** 2)
def ed(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Euclidean distance between predicted and observed values in vector space.
.. image:: /pictures/ED.png
**Range** 0 ≤ ED < inf, smaller is better.
**Notes** Also sometimes referred to as the L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ed(sim, obs)
1.63707055437449
Returns
-------
float
The euclidean distance error value.
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.linalg.norm(observed_array - simulated_array)
def ned(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the normalized Euclidian distance between the simulated and observed data in vector
space.
.. image:: /pictures/NED.png
**Range** 0 ≤ NED < inf, smaller is better.
**Notes** Also sometimes referred to as the squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The normalized euclidean distance value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ned(sim, obs)
0.2872053604165771
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array / np.mean(observed_array)
b = simulated_array / np.mean(simulated_array)
return np.linalg.norm(a - b)
def rmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square error between the simulated and observed data.
.. image:: /pictures/RMSE.png
**Range** 0 ≤ RMSE < inf, smaller is better.
**Notes:** The standard deviation of the residuals. A lower spread indicates that the points
are better concentrated around the line of best fit (linear). Random errors do not cancel.
This metric will highlights larger errors.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.rmse(sim, obs)
0.668331255192114
References
----------
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.sqrt(np.mean((simulated_array - observed_array) ** 2))
def rmsle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square log error between the simulated and observed data.
.. image:: /pictures/RMSLE.png
**Range:** 0 ≤ RMSLE < inf. Smaller is better, and it does not indicate bias.
**Notes:** Random errors do not cancel while using this metric. This metric limits the
impact of outliers by more evenly weighting high and low values. To calculate the log values,
each value in the observed and simulated array is increased by one unit in order to avoid
run-time errors and nan values (function np.log1p).
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square log error value.
Examples
--------
Notice that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.rmsle(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
"""
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf, remove_neg=remove_neg,
remove_zero=remove_zero)
return np.sqrt(np.mean(np.power(np.log1p(simulated_array) - np.log1p(observed_array), 2)))
def nrmse_range(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the range normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Range.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the range of the observed time series (x).
Normalizing allows comparison between data sets with different scales. The NRMSErange is the
most sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The range normalized root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_range(sim, obs)
0.0891108340256152
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_max = np.max(observed_array)
obs_min = np.min(observed_array)
return rmse_value / (obs_max - obs_min)
def nrmse_mean(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Mean.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the mean of the observed time series (x).
Normalizing allows comparison between data sets with different scales.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_mean(sim, obs)
0.11725109740212526
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_mean = np.mean(observed_array)
return rmse_value / obs_mean
def nrmse_iqr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the IQR normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_IQR.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the interquartile range of the observed time
series (x). Normalizing allows comparison between data sets with different scales.
The NRMSEquartile is the least sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The IQR normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_iqr(sim, obs)
0.2595461185212093
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
q1 = np.percentile(observed_array, 25)
q3 = np.percentile(observed_array, 75)
iqr = q3 - q1
return rmse_value / iqr
def irmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the inertial root mean square error (IRMSE) between the simulated and observed data.
.. image:: /pictures/IRMSE.png
**Range:** 0 ≤ IRMSE < inf, lower is better.
**Notes:** This metric is the RMSE devided by by the standard deviation of the gradient of the
observed timeseries data. This metric is meant to be help understand the ability of the model
to predict changes in observation.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The inertial root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.irmse(sim, obs)
0.14572738134831856
References
----------
- Daga, M., Deo, M.C., 2009. Alternative data-driven methods to estimate wind from waves by
inverse modeling. Natural Hazards 49(2) 293-310.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Getting the gradient of the observed data
obs_len = observed_array.size
obs_grad = observed_array[1:obs_len] - observed_array[0:obs_len - 1]
# Standard deviation of the gradient
obs_grad_std = np.std(obs_grad, ddof=1)
# Divide RMSE by the standard deviation of the gradient of the observed data
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
return rmse_value / obs_grad_std
def mase(simulated_array, observed_array, m=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute scaled error between the simulated and observed data.
.. image:: /pictures/MASE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
m: int
If given, indicates the seasonal period m. If not given, the default is 1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute scaled error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mase(sim, obs)
0.17341040462427745
References
----------
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
start = m
end = simulated_array.size - m
a = np.mean(np.abs(simulated_array - observed_array))
b = np.abs(observed_array[start:observed_array.size] - observed_array[:end])
return a / (np.sum(b) / end)
def pearson_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the pearson correlation coefficient.
.. image:: /pictures/R_pearson.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The pearson r coefficient measures linear correlation. It is sensitive to outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Pearson correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.pearson_r(sim, obs)
0.9610793632835262
References
----------
- Pearson, K. (1895). Note on regression and inheritance in the case of two parents.
Proceedings of the Royal Society of London, 58, 240-242.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
top = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1 = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2 = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
return top / (bot1 * bot2)
def spearman_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the spearman rank correlation coefficient.
.. image:: /pictures/R_spearman.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The spearman r coefficient measures the monotonic relation between simulated and
observed data. Because it uses a nonparametric measure of rank correlation, it is less sensitive
to outliers compared to the Pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spearman rank correlation coefficient.
Examples
----------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.spearman_r(sim, obs)
0.942857142857143
References
----------
- Spearman C (1904). "The proof and measurement of association between two things". American
Journal of Psychology. 15: 72–101. doi:10.2307/1412159
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rank_sim = rankdata(simulated_array)
rank_obs = rankdata(observed_array)
mean_rank_sim = np.mean(rank_sim)
mean_rank_obs = np.mean(rank_obs)
top = np.mean((rank_obs - mean_rank_obs) * (rank_sim - mean_rank_sim))
bot = np.sqrt(
np.mean((rank_obs - mean_rank_obs) ** 2) * np.mean((rank_sim - mean_rank_sim) ** 2))
return top / bot
def r_squared(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Coefficient of Determination (r2).
.. image:: /pictures/r2.png
**Range:** 0 ≤ r2 ≤ 1. 1 indicates perfect correlation, 0 indicates complete randomness.
**Notes:** The Coefficient of Determination measures the linear relation between simulated and
observed data. Because it is the pearson correlation coefficient squared, it is more heavily
affected by outliers than the pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The coefficient of determination (R^2).
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.r_squared(sim, obs)
0.9236735425294681
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array - np.mean(observed_array)
b = simulated_array - np.mean(simulated_array)
return (np.sum(a * b)) ** 2 / (np.sum(a ** 2) * np.sum(b ** 2))
def acc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the anomaly correlation coefficient (ACC).
.. image:: /pictures/ACC.png
**Range:** -1 ≤ ACC ≤ 1. -1 indicates perfect negative correlation of the variation
pattern of the anomalies, 0 indicates complete randomness of the variation patterns of the
anomalies, 1 indicates perfect correlation of the variation pattern of the anomalies.
**Notes:** Common measure in the verification of spatial fields. Measures the correlation
between the variation pattern of the simulated data compared to the observed data.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The anomaly correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.acc(sim, obs)
0.8008994694029383
References
----------
- Langland, Rolf H., and Ryan N. Maue. “Recent Northern Hemisphere Mid-Latitude Medium-Range
Deterministic Forecast Skill.” Tellus A: Dynamic Meteorology and Oceanography 64,
no. 1 (2012): 17531.
- Miyakoda, K., G. D. Hembree, R. F. Strickler, and I. Shulman. “Cumulative Results of Extended
Forecast Experiments I. Model Performance for Winter Cases.” Monthly Weather Review 100, no.
12(1972): 836–55.
- Murphy, Allan H., and Edward S. Epstein. “Skill Scores and Correlation Coefficients in Model
Verification.” Monthly Weather Review 117, no. 3 (1989): 572–82.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - np.mean(simulated_array)
b = observed_array - np.mean(observed_array)
c = np.std(observed_array, ddof=1) * np.std(simulated_array, ddof=1) * simulated_array.size
return np.dot(a, b / c)
def mape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the mean absolute percentage error (MAPE).
.. image:: /pictures/MAPE.png
**Range:** 0% ≤ MAPE ≤ inf. 0% indicates perfect correlation, a larger error indicates a
larger percent error in the data.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
c = 100 / simulated_array.size
return c * np.sum(b)
def mapd(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the mean absolute percentage deviation (MAPD).
.. image:: /pictures/MAPD.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage deviation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mapd(sim, obs)
0.10526315789473682
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(np.abs(observed_array))
return a / b
def maape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the Mean Arctangent Absolute Percentage Error (MAAPE).
.. image:: /pictures/MAAPE.png
**Range:** 0 ≤ MAAPE < π/2, does not indicate bias, smaller is better.
**Notes:** Represents the mean absolute error as a percentage of the observed values. Handles
0s in the observed data. This metric is not as biased as MAPE by under-over predictions.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean arctangent absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
- Kim, S., Kim, H., 2016. A new metric of absolute percentage error for intermittent demand
forecasts. International Journal of Forecasting 32(3) 669-679.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
return np.mean(np.arctan(b))
def smape1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (1) (SMAPE1).
.. image:: /pictures/SMAPE1.png
**Range:** 0 ≤ SMAPE1 < 100%, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (1).
Examples
--------
Note that if we switch the simulated and observed arrays the result is the same
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape1(sim, obs)
5.871915694397428
>>> he.smape1(obs, sim)
5.871915694397428
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 100 / simulated_array.size
b = np.abs(simulated_array - observed_array)
c = np.abs(simulated_array) + np.abs(observed_array)
return a * np.sum(b / c)
def smape2(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (2) (SMAPE2).
.. image:: /pictures/SMAPE2.png
**Range:** 0 ≤ SMAPE1 < 200%, does not indicate bias, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE with only positive metric values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (2).
Examples
--------
Note that switching the simulated and observed arrays yields the same results
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape2(sim, obs)
11.743831388794856
>>> he.smape2(obs, sim)
11.743831388794856
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = (simulated_array + observed_array) / 2
c = 100 / simulated_array.size
return c * np.sum(np.abs(a / b))
def d(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d).
.. image:: /pictures/d.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d(sim, obs)
0.978477353035657
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (observed_array - simulated_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
return 1 - (np.sum(a) / np.sum((b + c) ** 2))
def d1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d1).
.. image:: /pictures/d1.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric. Compared
to the other index of agreement (d) it has a reduced impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (d1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1(sim, obs)
0.8434782608695652
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
obs_mean = np.mean(observed_array)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.abs(simulated_array - obs_mean)
c = np.abs(observed_array - obs_mean)
return 1 - np.sum(a) / np.sum(b + c)
def dr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the refined index of agreement (dr).
.. image:: /pictures/dr.png
**Range:** -1 ≤ dr < 1, does not indicate bias, larger is better.
**Notes:** Reformulation of Willmott’s index of agreement. This metric was created to address
issues in the index of agreement and the Nash-Sutcliffe efficiency metric. Meant to be a
flexible metric for use in climatology.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The refined index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dr(sim, obs)
0.847457627118644
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = 2 * np.sum(np.abs(observed_array - observed_array.mean()))
if a <= b:
return 1 - (a / b)
else:
return (b / a) - 1
def drel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the relative index of agreement (drel).
.. image:: /pictures/drel.png
**Range:** 0 ≤ drel < 1, does not indicate bias, larger is better.
**Notes:** Instead of absolute differences, this metric uses relative differences.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.drel(sim, obs)
0.9740868625579597
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = ((simulated_array - observed_array) / observed_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = ((b + c) / np.mean(observed_array)) ** 2
return 1 - (np.sum(a) / np.sum(e))
def dmod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the modified index of agreement (dmod).
.. image:: /pictures/dmod.png
**Range:** 0 ≤ dmod < 1, does not indicate bias, larger is better.
**Notes:** When j=1, this metric is the same as d1. As j becomes larger, outliers have a larger
impact on the value.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
Optional input indicating the j values desired. A higher j places more emphasis on
outliers. j is 1 by default.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified index of agreement.
Examples
--------
Note that using the default is the same as calculating the d1 metric. Changing the value of j
modification of the metric.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dmod(sim, obs) # Same as d1
0.8434782608695652
>>> he.dmod(sim, obs, j=1.5)
0.9413310986805733
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = (b + c) ** j
return 1 - (np.sum(a) / np.sum(e))
def watt_m(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute Watterson's M (M).
.. image:: /pictures/M.png
**Range:** -1 ≤ M < 1, does not indicate bias, larger is better.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
Watterson's M value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.watt_m(sim, obs)
0.8307913876595929
References
----------
- Watterson, I.G., 1996. Non‐dimensional measures of climate model performance. International
Journal of Climatology 16(4) 379-391.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 2 / np.pi
b = np.mean((simulated_array - observed_array) ** 2) # MSE
c = np.std(observed_array, ddof=1) ** 2 + np.std(simulated_array, ddof=1) ** 2
e = (np.mean(simulated_array) - np.mean(observed_array)) ** 2
f = c + e
return a * np.arcsin(1 - (b / f))
def mb_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute Mielke-Berry R value (MB R).
.. image:: /pictures/MB_R.png
**Range:** 0 ≤ MB R < 1, does not indicate bias, larger is better.
**Notes:** Compares prediction to probability it arose by chance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Mielke-Berry R value.
Notes
-----
If a more optimized version is desired, the `numba package <http://numba.pydata.org/doc.html>`_ can be implemented
for a much more optimized performance when computing this metric. An example is given below.
>>> from numba import njit, prange
>>> @njit(parallel=True, fastmath=True)
>>> def mb_par_fastmath(pred, obs): # uses LLVM compiler
>>> assert pred.size == obs.size
>>> n = pred.size
>>> tot = 0.0
>>> mae = 0.0
>>> for i in range(n):
>>> for j in prange(n):
>>> tot += abs(pred[i] - obs[j])
>>> mae += abs(pred[i] - obs[i])
>>> mae = mae / n
>>> mb = 1 - ((n ** 2) * mae / tot)
>>>
>>> return mb
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mb_r(sim, obs)
0.7726315789473684
References
----------
- Berry, K.J., Mielke, P.W., 1988. A Generalization of Cohen's Kappa Agreement Measure to
Interval Measurement and Multiple Raters. Educational and Psychological Measurement 48(4)
921-933.
- Mielke, P.W., Berry, K.J., 2007. Permutation methods: a distance function approach.
Springer Science & Business Media.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Calculate metric
n = simulated_array.size
tot = 0.0
for i in range(n):
tot = tot + np.sum(np.abs(simulated_array - observed_array[i]))
mae_val = np.sum(np.abs(simulated_array - observed_array)) / n
mb = 1 - ((n ** 2) * mae_val / tot)
return mb
def nse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Nash-Sutcliffe Efficiency.
.. image:: /pictures/NSE.png
**Range:** -inf < NSE < 1, does not indicate bias, larger is better.
**Notes:** The Nash-Sutcliffe efficiency metric compares prediction values to naive predictions
(i.e. average value). One major flaw of this metric is that it punishes a higher variance in
the observed values (denominator). This metric is analogous to the mean absolute error skill
score (MAESS) using the mean flow as a benchmark.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Nash-Sutcliffe Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse(sim, obs)
0.922093023255814
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
- McCuen, R.H., Knight, Z., Cutter, A.G., 2006. Evaluation of the Nash-Sutcliffe Efficiency
Index. Journal of Hydraulic Engineering.
- Nash, J.E., Sutcliffe, J.V., 1970. River flow forecasting through conceptual models part
I — A discussion of principles. Journal of Hydrology 282-290.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** 2
b = (np.abs(observed_array - np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def nse_mod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the modified Nash-Sutcliffe efficiency (NSE mod).
.. image:: /pictures/NSEmod.png
**Range:** -inf < NSE (mod) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
If given, sets the value of j to the input. j is 1 by default. A higher j gives more
emphasis to outliers
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_mod(sim, obs)
0.6949152542372882
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = (np.abs(observed_array - np.mean(observed_array))) ** j
return 1 - (np.sum(a) / np.sum(b))
def nse_rel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the relative Nash-Sutcliffe efficiency (NSE rel).
.. image:: /pictures/NSErel.png
**Range:** -inf < NSE (rel) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_rel(sim, obs)
0.9062004687708474
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs((simulated_array - observed_array) / observed_array)) ** 2
b = (np.abs((observed_array - np.mean(observed_array)) / np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def kge_2009(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""Compute the Kling-Gupta efficiency (2009).
.. image:: /pictures/KGE_2009.png
**Range:** -inf < KGE (2009) < 1, larger is better.
**Notes:** Gupta et al. (2009) created this metric to demonstrate the relative importance of
the three components of the NSE, which are correlation, bias and variability. This was done
with hydrologic modeling as the context. This metric is meant to address issues with the NSE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), Alpha, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, alpha, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2009) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2009(sim, obs)
0.912223072345668
>>> he.kge_2009(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.927910707932087, 1.0058823529411764, 0.9181073779138655)
References
----------
- Gupta, H. V., Kling, H., Yilmaz, K. K., & Martinez, G. F. (2009). Decomposition of the mean
squared error and NSE performance criteria: Implications for improving hydrological modelling.
Journal of Hydrology, 377(1-2), 80-91.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array, ddof=1)
obs_sigma = np.std(observed_array, ddof=1)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
if obs_mean != 0:
beta = sim_mean / obs_mean
else:
beta = np.nan
# Relative variability between simulated and observed values
if obs_sigma != 0:
alpha = sim_sigma / obs_sigma
else:
alpha = np.nan
if not np.isnan(beta) and not np.isnan(alpha):
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (alpha - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Alpha is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, alpha, beta, kge
else:
return kge
def kge_2012(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""
Compute the Kling-Gupta efficiency (2012).
.. image:: /pictures/KGE_2012.png
**Range:** -inf < KGE (2012) < 1, does not indicate bias, larger is better.
**Notes:** The modified version of the KGE (2009). Kling proposed this version to avoid
cross-correlation between bias and variability ratios.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), gamma, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, gamma, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2012) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2012(sim, obs)
0.9122230723456678
>>> he.kge_2012(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.9224843295231272, 1.0058823529411764, 0.9132923608280753)
References
----------
- Kling, H., Fuchs, M., & Paulin, M. (2012). Runoff conditions in the upper Danube basin under
an ensemble of climate change scenarios. Journal of Hydrology, 424, 264-277.
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array)
obs_sigma = np.std(observed_array)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
beta = sim_mean / obs_mean
# CV is the coefficient of variation (standard deviation / mean)
sim_cv = sim_sigma / sim_mean
obs_cv = obs_sigma / obs_mean
# Variability Ratio, or the ratio of simulated CV to observed CV
gam = sim_cv / obs_cv
if obs_mean != 0 and obs_sigma != 0 and sim_mean != 0:
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (gam - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
if sim_mean == 0:
warnings.warn(
'Warning: The simulated data mean is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, gam, beta, kge
else:
return kge
def lm_index(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""
Compute the Legate-McCabe Efficiency Index.
.. image:: /pictures/E1p.png
**Range:** 0 ≤ E1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.lm_index(sim, obs)
0.6949152542372882
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
mean_obs = np.mean(observed_array)
if obs_bar_p is not None:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def d1_p(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""Compute the Legate-McCabe Index of Agreement.
.. image:: /pictures/D1p.png
**Range:** 0 ≤ d1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1_p(sim, obs)
0.8434782608695652
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
if obs_bar_p is not None:
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - obs_bar_p) + np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
mean_obs = np.mean(observed_array)
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - mean_obs) + np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def ve(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Volumetric Efficiency (VE).
.. image:: /pictures/VE.png
**Range:** 0 ≤ VE < 1 smaller is better, does not indicate bias.
**Notes:** Represents the error as a percentage of flow.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Volumetric Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ve(sim, obs)
0.8947368421052632
References
----------
- Criss, R.E., Winston, W.E., 2008. Do Nash values have value? Discussion and alternate
proposals. Hydrological Processes 22(14) 2723.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(observed_array)
return 1 - (a / b)
def sa(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Angle (SA).
.. image:: /pictures/SA.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral angle metric measures the angle between the two vectors in hyperspace.
It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Angle value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sa(sim, obs)
0.10816831366492945
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(simulated_array, observed_array)
b = np.linalg.norm(simulated_array) * np.linalg.norm(observed_array)
return np.arccos(a / b)
def sc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Correlation (SC).
.. image:: /pictures/SC.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral correlation metric measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Correlation value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sc(sim, obs)
0.27991341383646606
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(observed_array - np.mean(observed_array), simulated_array - np.mean(simulated_array))
b = np.linalg.norm(observed_array - np.mean(observed_array))
c = np.linalg.norm(simulated_array - np.mean(simulated_array))
e = b * c
return np.arccos(a / e)
def sid(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Information Divergence (SID).
.. image:: /pictures/SID.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral information divergence measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral information divergence value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sid(sim, obs)
0.03517616895318012
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
first = (observed_array / np.mean(observed_array)) - (
simulated_array / np.mean(simulated_array))
second1 = np.log10(observed_array) - np.log10(np.mean(observed_array))
second2 = np.log10(simulated_array) - np.log10(np.mean(simulated_array))
return np.dot(first, second1 - second2)
def sga(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Gradient Angle (SGA).
.. image:: /pictures/SGA.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral gradient angle measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
SG is the gradient of the simulated or observed time series.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Gradient Angle.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sga(sim, obs)
0.26764286472739834
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sgx = observed_array[1:] - observed_array[:observed_array.size - 1]
sgy = simulated_array[1:] - simulated_array[:simulated_array.size - 1]
a = np.dot(sgx, sgy)
b = np.linalg.norm(sgx) * np.linalg.norm(sgy)
return np.arccos(a / b)
####################################################################################################
# H Metrics: Methods from Tornqvist L, Vartia P, and Vartia YO. (1985) #
####################################################################################################
def h1_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the H1 mean error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mhe(sim, obs)
0.002106551840594386
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(h)
def h1_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H1 absolute error.
.. image:: /pictures/H1.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The H1 absolute error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mahe(sim, obs)
0.11639226612630865
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(np.abs(h))
def h1_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H1 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean squared H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_rmshe(sim, obs)
0.12865571253672756
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.sqrt(np.mean(h ** 2))
def h2_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean error.
.. image:: /pictures/H2.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mhe(sim, obs)
-0.015319829424307036
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(h)
def h2_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean absolute error.
.. image:: /pictures/H2.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mahe(sim, obs)
0.11997591408039167
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(np.abs(h))
def h2_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_rmshe(sim, obs)
0.1373586680669673
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.sqrt(np.mean(h ** 2))
def h3_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 mean error.
.. image:: /pictures/H3.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mhe(sim, obs)
-0.006322019630356533
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(h)
def h3_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H3 mean absolute error.
.. image:: /pictures/H3.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mahe(sim, obs)
0.11743831388794855
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(np.abs(h))
def h3_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 root mean square error.
.. image:: /pictures/H3.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.sqrt(np.mean(h ** 2))
def h4_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mhe(sim, obs)
-0.0064637371129817
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(h)
def h4_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H4 mean absolute error.
.. image:: /pictures/H4.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mahe(sim, obs)
0.11781032209144082
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(np.abs(h))
def h4_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_rmshe(sim, obs)
0.13200901963465006
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.sqrt(np.mean(h ** 2))
def h5_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean error.
.. image:: /pictures/H5.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mhe(sim, obs)
-0.006606638791856322
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(h)
def h5_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean absolute error.
.. image:: /pictures/H5.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mahe(sim, obs)
0.11818409010335018
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(np.abs(h))
def h5_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 root mean square error.
.. image:: /pictures/H5.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_rmshe(sim, obs)
0.13254476469410933
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h6_mhe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H6 mean error.
.. image:: /pictures/H6.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mhe(sim, obs)
-0.006322019630356514
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(h)
def h6_mahe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""Compute the H6 mean absolute error.
.. image:: /pictures/H6.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mahe(sim, obs)
0.11743831388794852
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(np.abs(h))
def h6_rmshe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the H6 root mean square error.
.. image:: /pictures/H6.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h7_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean error.
.. image:: /pictures/H7.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mhe(sim, obs)
0.0026331898007430263
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(h)
def h7_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean absolute error.
.. image:: /pictures/H7.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mahe(sim, obs)
0.14549033265788583
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(np.abs(h))
def h7_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 root mean square error.
.. image:: /pictures/H7.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_rmshe(sim, obs)
0.16081964067090945
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
def h8_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H8 mean error.
.. image:: /pictures/H8.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mhe(sim, obs)
0.0018056158633666466
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(h)
def h8_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 mean absolute error.
.. image:: /pictures/H8.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mahe(sim, obs)
0.099764799536836
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(np.abs(h))
def h8_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 root mean square error.
.. image:: /pictures/H8.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_rmshe(sim, obs)
0.11027632503148076
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
# def h9(simulated_array, observed_array, h_type='mhe', k=1):
# h = (simulated_array / observed_array - 1) / \
# np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
# if h_type == 'mhe':
# return h.mean()
# elif h_type == 'ahe':
# return np.abs(h).mean()
# elif h_type == 'rmshe':
# return np.sqrt((h**2).mean())
# else:
# raise RuntimeError("The three types available are 'mhe', 'ahe', and 'rmshe'.")
def h10_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean error.
.. image:: /pictures/H10.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h10_mhe(sim, obs)
-0.0012578676058971154
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(h)
def h10_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean absolute error.
.. image:: /pictures/H10.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_mahe(sim, obs), 6)
0.094636
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(np.abs(h))
def h10_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 root mean square error.
.. image:: /pictures/H10.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_rmshe(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.sqrt(np.mean(h ** 2))
###################################################################################################
# Statistical Error Metrics for Distribution Testing #
###################################################################################################
def g_mean_diff(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the geometric mean difference.
.. image:: /pictures/GMD.png
**Range:**
**Notes:** For the difference of geometric means, the geometric mean is computed for each of
two samples then their difference is taken.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The geometric mean difference value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.g_mean_diff(sim, obs)
0.988855412098022
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.exp(gmean(sim_log) - gmean(obs_log))
def mean_var(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the mean variance.
.. image:: /pictures/MV.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean variance.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.mean_var(sim, obs), 6)
0.010641
References
----------
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.var(np.log1p(observed_array) - np.log1p(simulated_array))
####################################################################################################
# HELPER FUNCTIONS AND API INFORMATION #
####################################################################################################
metric_names = [
'Mean Error', 'Mean Absolute Error', 'Mean Squared Error', 'Mean Log Error',
'Mean Absolute Log Error', 'Mean Squared Log Error', 'Median Error', 'Median Absolute Error',
'Median Squared Error', 'Eclidean Distance', 'Normalized Eclidean Distance',
'Root Mean Square Error', 'Root Mean Squared Log Error',
'Normalized Root Mean Square Error - Range', 'Normalized Root Mean Square Error - Mean',
'Normalized Root Mean Square Error - IQR', 'Inertial Root Mean Square Error',
'Mean Absolute Scaled Error', 'Coefficient of Determination', 'Pearson Correlation Coefficient',
'Spearman Rank Correlation Coefficient', 'Anomaly Correlation Coefficient',
'Mean Absolute Percentage Error', 'Mean Absolute Percentage Deviation',
'Mean Arctangent Absolute Percentage Error', 'Symmetric Mean Absolute Percentage Error (1)',
'Symmetric Mean Absolute Percentage Error (2)', 'Index of Agreement (d)',
'Index of Agreement (d1)', 'Modified Index of Agreement', 'Relative Index of Agreement',
'Index of Agreement Refined (dr)', "Watterson's M", 'Mielke-Berry R',
'Nash-Sutcliffe Efficiency', 'Modified Nash-Sutcliffe Efficiency',
'Relative Nash-Sutcliffe Efficiency', 'Kling-Gupta Efficiency (2009)',
'Kling-Gupta Efficiency (2012)', 'Legate-McCabe Efficiency Index',
'Legate-McCabe Index of Agreement', 'Volumetric Efficiency', 'Spectral Angle',
'Spectral Correlation', 'Spectral Information Divergence', 'Spectral Gradient Angle',
'Mean H1 Error', 'Mean Absolute H1 Error', 'Root Mean Square H1 Error', 'Mean H2 Error',
'Mean Absolute H2 Error', 'Root Mean Square H2 Error', 'Mean H3 Error',
'Mean Absolute H3 Error', 'Root Mean Square H3 Error', 'Mean H4 Error',
'Mean Absolute H4 Error', 'Root Mean Square H4 Error', 'Mean H5 Error',
'Mean Absolute H5 Error', 'Root Mean Square H5 Error', 'Mean H6 Error',
'Mean Absolute H6 Error', 'Root Mean Square H6 Error', 'Mean H7 Error',
'Mean Absolute H7 Error', 'Root Mean Square H7 Error', 'Mean H8 Error',
'Mean Absolute H8 Error', 'Root Mean Square H8 Error', 'Mean H10 Error',
'Mean Absolute H10 Error', 'Root Mean Square H10 Error', 'Geometric Mean Difference',
'Mean Variance'
]
metric_abbr = [
'ME', 'MAE', 'MSE', 'MLE', 'MALE', 'MSLE', 'MdE', 'MdAE', 'MdSE', 'ED', 'NED', 'RMSE', 'RMSLE',
'NRMSE (Range)', 'NRMSE (Mean)', 'NRMSE (IQR)', 'IRMSE', 'MASE', 'r2', 'R (Pearson)',
'R (Spearman)', 'ACC', 'MAPE', 'MAPD', 'MAAPE', 'SMAPE1', 'SMAPE2', 'd', 'd1', 'd (Mod.)',
'd (Rel.)', 'dr', 'M', '(MB) R', 'NSE', 'NSE (Mod.)', 'NSE (Rel.)', 'KGE (2009)', 'KGE (2012)',
"E1'", "D1'", 'VE', 'SA', 'SC', 'SID', 'SGA', 'H1 (MHE)', 'H1 (MAHE)', 'H1 (RMSHE)', 'H2 (MHE)',
'H2 (MAHE)', 'H2 (RMSHE)', 'H3 (MHE)', 'H3 (MAHE)', 'H3 (RMSHE)', 'H4 (MHE)', 'H4 (MAHE)',
'H4 (RMSHE)', 'H5 (MHE)', 'H5 (MAHE)', 'H5 (RMSHE)', 'H6 (MHE)', 'H6 (MAHE)', 'H6 (RMSHE)',
'H7 (MHE)', 'H7 (MAHE)', 'H7 (RMSHE)', 'H8 (MHE)', 'H8 (MAHE)', 'H8 (RMSHE)', 'H10 (MHE)',
'H10 (MAHE)', 'H10 (RMSHE)', 'GMD', 'MV'
]
function_list = [
me, mae, mse, mle, male, msle, mde, mdae, mdse, ed, ned, rmse, rmsle, nrmse_range, nrmse_mean,
nrmse_iqr, irmse, mase, r_squared, pearson_r, spearman_r, acc, mape, mapd, maape, smape1,
smape2, d, d1, dmod, drel, dr, watt_m, mb_r, nse, nse_mod, nse_rel, kge_2009, kge_2012,
lm_index, d1_p, ve, sa, sc, sid, sga, h1_mhe, h1_mahe, h1_rmshe, h2_mhe, h2_mahe, h2_rmshe,
h3_mhe, h3_mahe, h3_rmshe, h4_mhe, h4_mahe, h4_rmshe, h5_mhe, h5_mahe, h5_rmshe, h6_mhe,
h6_mahe, h6_rmshe, h7_mhe, h7_mahe, h7_rmshe, h8_mhe, h8_mahe, h8_rmshe, h10_mhe, h10_mahe,
h10_rmshe, g_mean_diff, mean_var,
]
# Assign some properties to each function for ease of use for users
for i in range(len(function_list)):
function_list[i].name = metric_names[i]
function_list[i].abbr = metric_abbr[i]
def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Removes the nan, negative, and inf values in two numpy arrays"""
sim_copy = np.copy(simulated_array)
obs_copy = np.copy(observed_array)
# Checking to see if the vectors are the same length
assert sim_copy.ndim == 1, "The simulated array is not one dimensional."
assert obs_copy.ndim == 1, "The observed array is not one dimensional."
if sim_copy.size != obs_copy.size:
raise RuntimeError("The two ndarrays are not the same size.")
# Treat missing data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain nan values
all_treatment_array = np.ones(obs_copy.size, dtype=bool)
if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_nan = np.isnan(sim_copy)
obs_nan = np.isnan(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_nan] = replace_nan
obs_copy[obs_nan] = replace_nan
warnings.warn("Elements(s) {} contained NaN values in the simulated array and "
"elements(s) {} contained NaN values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_nan)[0],
np.where(obs_nan)[0]),
UserWarning)
else:
# Getting the indices of the nan values, combining them, and informing user.
nan_indices_fcst = ~np.isnan(sim_copy)
nan_indices_obs = ~np.isnan(obs_copy)
all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)
warnings.warn("Row(s) {} contained NaN values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_nan_indices)[0]),
UserWarning)
if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_inf = np.isinf(sim_copy)
obs_inf = np.isinf(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_inf] = replace_inf
obs_copy[obs_inf] = replace_inf
warnings.warn("Elements(s) {} contained Inf values in the simulated array and "
"elements(s) {} contained Inf values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_inf)[0],
np.where(obs_inf)[0]),
UserWarning)
else:
inf_indices_fcst = ~(np.isinf(sim_copy))
inf_indices_obs = ~np.isinf(obs_copy)
all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)
warnings.warn(
"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows "
"are zero indexed).".format(np.where(~all_inf_indices)[0]),
UserWarning
)
# Treat zero data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain zero values
if remove_zero:
if (obs_copy == 0).any() or (sim_copy == 0).any():
zero_indices_fcst = ~(sim_copy == 0)
zero_indices_obs = ~(obs_copy == 0)
all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)
warnings.warn(
"Row(s) {} contained zero values and the row(s) have been removed (Rows are "
"zero indexed).".format(np.where(~all_zero_indices)[0]),
UserWarning
)
# Treat negative data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain negative values
# Ignore runtime warnings from comparing
if remove_neg:
with np.errstate(invalid='ignore'):
obs_copy_bool = obs_copy < 0
sim_copy_bool = sim_copy < 0
if obs_copy_bool.any() or sim_copy_bool.any():
neg_indices_fcst = ~sim_copy_bool
neg_indices_obs = ~obs_copy_bool
all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)
warnings.warn("Row(s) {} contained negative values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_neg_indices)[0]),
UserWarning)
obs_copy = obs_copy[all_treatment_array]
sim_copy = sim_copy[all_treatment_array]
return sim_copy, obs_copy
if __name__ == "__main__":
pass
|
BYU-Hydroinformatics/HydroErr | HydroErr/HydroErr.py | mae | python | def mae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean(np.absolute(simulated_array - observed_array)) | Compute the mean absolute error of the simulated and observed data.
.. image:: /pictures/MAE.png
**Range:** 0 ≤ MAE < inf, data units, smaller is better.
**Notes:** The ME measures the absolute difference between the simulated data and the observed
data. For the mean abolute error, a smaller number indicates a better fit to the original data.
Also note that random errors do not cancel. Also referred to as an L1-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute error value.
References
----------
- Willmott, Cort J., and Kenji Matsuura. “Advantages of the Mean Absolute Error (MAE) over the
Root Mean Square Error (RMSE) in Assessing Average Model Performance.” Climate Research 30,
no. 1 (2005): 79–82.
- Willmott, Cort J., and Kenji Matsuura. “On the Use of Dimensioned Measures of Error to
Evaluate the Performance of Spatial Interpolators.” International Journal of Geographical
Information Science 20, no. 1 (2006): 89–102.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mae(sim, obs)
0.5666666666666665 | train | https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L117-L193 | [
"def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,\n remove_neg=False, remove_zero=False):\n \"\"\"Removes the nan, negative, and inf values in two numpy arrays\"\"\"\n sim_copy = np.copy(simulated_array)\n obs_copy = np.copy(observed_array)\n\n # Checking to see if the vectors are the same length\n assert sim_copy.ndim == 1, \"The simulated array is not one dimensional.\"\n assert obs_copy.ndim == 1, \"The observed array is not one dimensional.\"\n\n if sim_copy.size != obs_copy.size:\n raise RuntimeError(\"The two ndarrays are not the same size.\")\n\n # Treat missing data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain nan values\n all_treatment_array = np.ones(obs_copy.size, dtype=bool)\n\n if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_nan = np.isnan(sim_copy)\n obs_nan = np.isnan(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_nan] = replace_nan\n obs_copy[obs_nan] = replace_nan\n\n warnings.warn(\"Elements(s) {} contained NaN values in the simulated array and \"\n \"elements(s) {} contained NaN values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_nan)[0],\n np.where(obs_nan)[0]),\n UserWarning)\n else:\n # Getting the indices of the nan values, combining them, and informing user.\n nan_indices_fcst = ~np.isnan(sim_copy)\n nan_indices_obs = ~np.isnan(obs_copy)\n all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)\n\n warnings.warn(\"Row(s) {} contained NaN values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_nan_indices)[0]),\n UserWarning)\n\n if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_inf = np.isinf(sim_copy)\n obs_inf = np.isinf(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_inf] = replace_inf\n obs_copy[obs_inf] = replace_inf\n\n warnings.warn(\"Elements(s) {} contained Inf values in the simulated array and \"\n \"elements(s) {} contained Inf values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_inf)[0],\n np.where(obs_inf)[0]),\n UserWarning)\n else:\n inf_indices_fcst = ~(np.isinf(sim_copy))\n inf_indices_obs = ~np.isinf(obs_copy)\n all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)\n\n warnings.warn(\n \"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows \"\n \"are zero indexed).\".format(np.where(~all_inf_indices)[0]),\n UserWarning\n )\n\n # Treat zero data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain zero values\n if remove_zero:\n if (obs_copy == 0).any() or (sim_copy == 0).any():\n zero_indices_fcst = ~(sim_copy == 0)\n zero_indices_obs = ~(obs_copy == 0)\n all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)\n\n warnings.warn(\n \"Row(s) {} contained zero values and the row(s) have been removed (Rows are \"\n \"zero indexed).\".format(np.where(~all_zero_indices)[0]),\n UserWarning\n )\n\n # Treat negative data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain negative values\n\n # Ignore runtime warnings from comparing\n if remove_neg:\n with np.errstate(invalid='ignore'):\n obs_copy_bool = obs_copy < 0\n sim_copy_bool = sim_copy < 0\n\n if obs_copy_bool.any() or sim_copy_bool.any():\n neg_indices_fcst = ~sim_copy_bool\n neg_indices_obs = ~obs_copy_bool\n all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)\n\n warnings.warn(\"Row(s) {} contained negative values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_neg_indices)[0]),\n UserWarning)\n\n obs_copy = obs_copy[all_treatment_array]\n sim_copy = sim_copy[all_treatment_array]\n\n return sim_copy, obs_copy\n"
] | # -*- coding: utf-8 -*-
"""
HydroErr contains a library of goodness of fit metrics that measure hydrologic skill.
Each metric is contained in function, and every function has the parameters to treat missing values as
well as remove zero and negative values from the timeseries data.
Each function contains two properties, name and abbr. These can be used in the Hydrostats package when creating tables
and adding metrics to the plots. Link to the hydrostats package: https://github.com/BYU-Hydroinformatics/Hydrostats.
An example of this functionality is shown below.
>>> import HydroErr as he
>>>
>>> he.acc.name
'Anomaly Correlation Coefficient'
>>> he.acc.abbr
'ACC'
"""
from __future__ import division
import numpy as np
from scipy.stats import gmean, rankdata
import warnings
__all__ = ['me', 'mae', 'mse', 'mle', 'male', 'msle', 'mde', 'mdae', 'mdse', 'ed', 'ned', 'rmse',
'rmsle', 'nrmse_range', 'nrmse_mean', 'nrmse_iqr', 'irmse', 'mase', 'r_squared',
'pearson_r', 'spearman_r', 'acc', 'mape', 'mapd', 'maape', 'smape1', 'smape2', 'd', 'd1',
'dmod', 'drel', 'dr', 'watt_m', 'mb_r', 'nse', 'nse_mod', 'nse_rel', 'kge_2009',
'kge_2012', 'lm_index', 'd1_p', 've', 'sa', 'sc', 'sid', 'sga', 'h1_mhe', 'h1_mahe',
'h1_rmshe', 'h2_mhe', 'h2_mahe', 'h2_rmshe', 'h3_mhe', 'h3_mahe', 'h3_rmshe', 'h4_mhe',
'h4_mahe', 'h4_rmshe', 'h5_mhe', 'h5_mahe', 'h5_rmshe', 'h6_mhe', 'h6_mahe', 'h6_rmshe',
'h7_mhe', 'h7_mahe', 'h7_rmshe', 'h8_mhe', 'h8_mahe', 'h8_rmshe', 'h10_mhe', 'h10_mahe',
'h10_rmshe', 'g_mean_diff', 'mean_var']
####################################################################################################
# General and Hydrological Error Metrics #
####################################################################################################
def me(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean error of the simulated and observed data.
.. image:: /pictures/ME.png
**Range:** -inf < MAE < inf, data units, closer to zero is better, indicates bias.
**Notes:** The mean error (ME) measures the difference between the simulated data and the
observed data. For the mean error, a smaller number indicates a better fit to the original
data. Note that if the error is in the form of random noise, the mean error will be very small,
which can skew the accuracy of this metric. ME is cumulative and will be small even if there
are large positive and negative errors that balance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean error value.
Examples
--------
Note that in this example the random noise cancels, leaving a very small ME.
>>> import HydroErr as he
>>> import numpy as np
>>> # Seed for reproducibility
>>> np.random.seed(54839)
>>> x = np.arange(100) / 20
>>> sim = np.sin(x) + 2
>>> obs = sim * (((np.random.rand(100) - 0.5) / 10) + 1)
>>> he.me(sim, obs)
-0.006832220968967168
References
----------
- Fisher, R.A., 1920. A Mathematical Examination of the Methods of Determining the Accuracy of
an Observation by the Mean Error, and by the Mean Square Error. Monthly Notices of the Royal
Astronomical Society 80 758 - 770.
"""
# Treating missing values
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero)
return np.mean(simulated_array - observed_array)
def mse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared error of the simulated and observed data.
.. image:: /pictures/MSE.png
**Range:** 0 ≤ MSE < inf, data units squared, smaller is better.
**Notes:** Random errors do not cancel, highlights larger errors, also referred to as a
squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mse(sim, obs)
0.4333333333333333
References
----------
- Wang, Zhou, and Alan C. Bovik. “Mean Squared Error: Love It or Leave It? A New Look at Signal
Fidelity Measures.” IEEE Signal Processing Magazine 26, no. 1 (2009): 98–117.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean((simulated_array - observed_array) ** 2)
def mle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean log error of the simulated and observed data.
.. image:: /pictures/MLE.png
**Range:** -inf < MLE < inf, data units, closer to zero is better.
**Notes** Same as the mean erro (ME) only use log ratios as the error term. Limits the impact of outliers, more
evenly weights high and low data values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mle(sim, obs)
0.002961767058151136
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(sim_log - obs_log)
def male(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean absolute log error of the simulated and observed data.
.. image:: /pictures/MALE.png
**Range:** 0 ≤ MALE < inf, data units squared, smaller is better.
**Notes** Same as MAE only use log ratios as the error term. Limits the impact of outliers,
more evenly weights high and low flows.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.male(sim, obs), 6)
0.090417
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(np.abs(sim_log - obs_log))
def msle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared log error of the simulated and observed data.
.. image:: /pictures/MSLE.png
**Range:** 0 ≤ MSLE < inf, data units squared, smaller is better.
**Notes** Same as the mean squared error (MSE) only use log ratios as the error term. Limits
the impact of outliers, more evenly weights high and low values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.msle(sim, obs), 6)
0.010426
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean((sim_log - obs_log) ** 2)
def mde(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median error (MdE) between the simulated and observed data.
.. image:: /pictures/MdE.png
**Range** -inf < MdE < inf, closer to zero is better.
**Notes** This metric indicates bias. It is similar to the mean error (ME), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mde(sim, obs)
-0.10000000000000009
Returns
-------
float
The median error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(simulated_array - observed_array)
def mdae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median absolute error (MdAE) between the simulated and observed data.
.. image:: /pictures/MdAE.png
**Range** 0 ≤ MdAE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean absolute error (MAE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdae(sim, obs)
0.75
Returns
-------
float
The median absolute error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(np.abs(simulated_array - observed_array))
def mdse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median squared error (MdSE) between the simulated and observed data.
.. image:: /pictures/MdSE.png
**Range** 0 ≤ MdSE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean squared error (MSE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdse(sim, obs)
0.625
Returns
-------
float
The median squared error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median((simulated_array - observed_array) ** 2)
def ed(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Euclidean distance between predicted and observed values in vector space.
.. image:: /pictures/ED.png
**Range** 0 ≤ ED < inf, smaller is better.
**Notes** Also sometimes referred to as the L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ed(sim, obs)
1.63707055437449
Returns
-------
float
The euclidean distance error value.
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.linalg.norm(observed_array - simulated_array)
def ned(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the normalized Euclidian distance between the simulated and observed data in vector
space.
.. image:: /pictures/NED.png
**Range** 0 ≤ NED < inf, smaller is better.
**Notes** Also sometimes referred to as the squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The normalized euclidean distance value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ned(sim, obs)
0.2872053604165771
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array / np.mean(observed_array)
b = simulated_array / np.mean(simulated_array)
return np.linalg.norm(a - b)
def rmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square error between the simulated and observed data.
.. image:: /pictures/RMSE.png
**Range** 0 ≤ RMSE < inf, smaller is better.
**Notes:** The standard deviation of the residuals. A lower spread indicates that the points
are better concentrated around the line of best fit (linear). Random errors do not cancel.
This metric will highlights larger errors.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.rmse(sim, obs)
0.668331255192114
References
----------
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.sqrt(np.mean((simulated_array - observed_array) ** 2))
def rmsle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square log error between the simulated and observed data.
.. image:: /pictures/RMSLE.png
**Range:** 0 ≤ RMSLE < inf. Smaller is better, and it does not indicate bias.
**Notes:** Random errors do not cancel while using this metric. This metric limits the
impact of outliers by more evenly weighting high and low values. To calculate the log values,
each value in the observed and simulated array is increased by one unit in order to avoid
run-time errors and nan values (function np.log1p).
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square log error value.
Examples
--------
Notice that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.rmsle(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
"""
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf, remove_neg=remove_neg,
remove_zero=remove_zero)
return np.sqrt(np.mean(np.power(np.log1p(simulated_array) - np.log1p(observed_array), 2)))
def nrmse_range(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the range normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Range.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the range of the observed time series (x).
Normalizing allows comparison between data sets with different scales. The NRMSErange is the
most sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The range normalized root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_range(sim, obs)
0.0891108340256152
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_max = np.max(observed_array)
obs_min = np.min(observed_array)
return rmse_value / (obs_max - obs_min)
def nrmse_mean(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Mean.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the mean of the observed time series (x).
Normalizing allows comparison between data sets with different scales.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_mean(sim, obs)
0.11725109740212526
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_mean = np.mean(observed_array)
return rmse_value / obs_mean
def nrmse_iqr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the IQR normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_IQR.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the interquartile range of the observed time
series (x). Normalizing allows comparison between data sets with different scales.
The NRMSEquartile is the least sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The IQR normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_iqr(sim, obs)
0.2595461185212093
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
q1 = np.percentile(observed_array, 25)
q3 = np.percentile(observed_array, 75)
iqr = q3 - q1
return rmse_value / iqr
def irmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the inertial root mean square error (IRMSE) between the simulated and observed data.
.. image:: /pictures/IRMSE.png
**Range:** 0 ≤ IRMSE < inf, lower is better.
**Notes:** This metric is the RMSE devided by by the standard deviation of the gradient of the
observed timeseries data. This metric is meant to be help understand the ability of the model
to predict changes in observation.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The inertial root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.irmse(sim, obs)
0.14572738134831856
References
----------
- Daga, M., Deo, M.C., 2009. Alternative data-driven methods to estimate wind from waves by
inverse modeling. Natural Hazards 49(2) 293-310.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Getting the gradient of the observed data
obs_len = observed_array.size
obs_grad = observed_array[1:obs_len] - observed_array[0:obs_len - 1]
# Standard deviation of the gradient
obs_grad_std = np.std(obs_grad, ddof=1)
# Divide RMSE by the standard deviation of the gradient of the observed data
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
return rmse_value / obs_grad_std
def mase(simulated_array, observed_array, m=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute scaled error between the simulated and observed data.
.. image:: /pictures/MASE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
m: int
If given, indicates the seasonal period m. If not given, the default is 1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute scaled error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mase(sim, obs)
0.17341040462427745
References
----------
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
start = m
end = simulated_array.size - m
a = np.mean(np.abs(simulated_array - observed_array))
b = np.abs(observed_array[start:observed_array.size] - observed_array[:end])
return a / (np.sum(b) / end)
def pearson_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the pearson correlation coefficient.
.. image:: /pictures/R_pearson.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The pearson r coefficient measures linear correlation. It is sensitive to outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Pearson correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.pearson_r(sim, obs)
0.9610793632835262
References
----------
- Pearson, K. (1895). Note on regression and inheritance in the case of two parents.
Proceedings of the Royal Society of London, 58, 240-242.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
top = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1 = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2 = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
return top / (bot1 * bot2)
def spearman_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the spearman rank correlation coefficient.
.. image:: /pictures/R_spearman.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The spearman r coefficient measures the monotonic relation between simulated and
observed data. Because it uses a nonparametric measure of rank correlation, it is less sensitive
to outliers compared to the Pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spearman rank correlation coefficient.
Examples
----------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.spearman_r(sim, obs)
0.942857142857143
References
----------
- Spearman C (1904). "The proof and measurement of association between two things". American
Journal of Psychology. 15: 72–101. doi:10.2307/1412159
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rank_sim = rankdata(simulated_array)
rank_obs = rankdata(observed_array)
mean_rank_sim = np.mean(rank_sim)
mean_rank_obs = np.mean(rank_obs)
top = np.mean((rank_obs - mean_rank_obs) * (rank_sim - mean_rank_sim))
bot = np.sqrt(
np.mean((rank_obs - mean_rank_obs) ** 2) * np.mean((rank_sim - mean_rank_sim) ** 2))
return top / bot
def r_squared(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Coefficient of Determination (r2).
.. image:: /pictures/r2.png
**Range:** 0 ≤ r2 ≤ 1. 1 indicates perfect correlation, 0 indicates complete randomness.
**Notes:** The Coefficient of Determination measures the linear relation between simulated and
observed data. Because it is the pearson correlation coefficient squared, it is more heavily
affected by outliers than the pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The coefficient of determination (R^2).
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.r_squared(sim, obs)
0.9236735425294681
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array - np.mean(observed_array)
b = simulated_array - np.mean(simulated_array)
return (np.sum(a * b)) ** 2 / (np.sum(a ** 2) * np.sum(b ** 2))
def acc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the anomaly correlation coefficient (ACC).
.. image:: /pictures/ACC.png
**Range:** -1 ≤ ACC ≤ 1. -1 indicates perfect negative correlation of the variation
pattern of the anomalies, 0 indicates complete randomness of the variation patterns of the
anomalies, 1 indicates perfect correlation of the variation pattern of the anomalies.
**Notes:** Common measure in the verification of spatial fields. Measures the correlation
between the variation pattern of the simulated data compared to the observed data.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The anomaly correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.acc(sim, obs)
0.8008994694029383
References
----------
- Langland, Rolf H., and Ryan N. Maue. “Recent Northern Hemisphere Mid-Latitude Medium-Range
Deterministic Forecast Skill.” Tellus A: Dynamic Meteorology and Oceanography 64,
no. 1 (2012): 17531.
- Miyakoda, K., G. D. Hembree, R. F. Strickler, and I. Shulman. “Cumulative Results of Extended
Forecast Experiments I. Model Performance for Winter Cases.” Monthly Weather Review 100, no.
12(1972): 836–55.
- Murphy, Allan H., and Edward S. Epstein. “Skill Scores and Correlation Coefficients in Model
Verification.” Monthly Weather Review 117, no. 3 (1989): 572–82.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - np.mean(simulated_array)
b = observed_array - np.mean(observed_array)
c = np.std(observed_array, ddof=1) * np.std(simulated_array, ddof=1) * simulated_array.size
return np.dot(a, b / c)
def mape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the mean absolute percentage error (MAPE).
.. image:: /pictures/MAPE.png
**Range:** 0% ≤ MAPE ≤ inf. 0% indicates perfect correlation, a larger error indicates a
larger percent error in the data.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
c = 100 / simulated_array.size
return c * np.sum(b)
def mapd(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the mean absolute percentage deviation (MAPD).
.. image:: /pictures/MAPD.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage deviation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mapd(sim, obs)
0.10526315789473682
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(np.abs(observed_array))
return a / b
def maape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the Mean Arctangent Absolute Percentage Error (MAAPE).
.. image:: /pictures/MAAPE.png
**Range:** 0 ≤ MAAPE < π/2, does not indicate bias, smaller is better.
**Notes:** Represents the mean absolute error as a percentage of the observed values. Handles
0s in the observed data. This metric is not as biased as MAPE by under-over predictions.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean arctangent absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
- Kim, S., Kim, H., 2016. A new metric of absolute percentage error for intermittent demand
forecasts. International Journal of Forecasting 32(3) 669-679.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
return np.mean(np.arctan(b))
def smape1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (1) (SMAPE1).
.. image:: /pictures/SMAPE1.png
**Range:** 0 ≤ SMAPE1 < 100%, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (1).
Examples
--------
Note that if we switch the simulated and observed arrays the result is the same
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape1(sim, obs)
5.871915694397428
>>> he.smape1(obs, sim)
5.871915694397428
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 100 / simulated_array.size
b = np.abs(simulated_array - observed_array)
c = np.abs(simulated_array) + np.abs(observed_array)
return a * np.sum(b / c)
def smape2(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (2) (SMAPE2).
.. image:: /pictures/SMAPE2.png
**Range:** 0 ≤ SMAPE1 < 200%, does not indicate bias, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE with only positive metric values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (2).
Examples
--------
Note that switching the simulated and observed arrays yields the same results
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape2(sim, obs)
11.743831388794856
>>> he.smape2(obs, sim)
11.743831388794856
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = (simulated_array + observed_array) / 2
c = 100 / simulated_array.size
return c * np.sum(np.abs(a / b))
def d(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d).
.. image:: /pictures/d.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d(sim, obs)
0.978477353035657
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (observed_array - simulated_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
return 1 - (np.sum(a) / np.sum((b + c) ** 2))
def d1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d1).
.. image:: /pictures/d1.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric. Compared
to the other index of agreement (d) it has a reduced impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (d1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1(sim, obs)
0.8434782608695652
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
obs_mean = np.mean(observed_array)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.abs(simulated_array - obs_mean)
c = np.abs(observed_array - obs_mean)
return 1 - np.sum(a) / np.sum(b + c)
def dr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the refined index of agreement (dr).
.. image:: /pictures/dr.png
**Range:** -1 ≤ dr < 1, does not indicate bias, larger is better.
**Notes:** Reformulation of Willmott’s index of agreement. This metric was created to address
issues in the index of agreement and the Nash-Sutcliffe efficiency metric. Meant to be a
flexible metric for use in climatology.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The refined index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dr(sim, obs)
0.847457627118644
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = 2 * np.sum(np.abs(observed_array - observed_array.mean()))
if a <= b:
return 1 - (a / b)
else:
return (b / a) - 1
def drel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the relative index of agreement (drel).
.. image:: /pictures/drel.png
**Range:** 0 ≤ drel < 1, does not indicate bias, larger is better.
**Notes:** Instead of absolute differences, this metric uses relative differences.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.drel(sim, obs)
0.9740868625579597
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = ((simulated_array - observed_array) / observed_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = ((b + c) / np.mean(observed_array)) ** 2
return 1 - (np.sum(a) / np.sum(e))
def dmod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the modified index of agreement (dmod).
.. image:: /pictures/dmod.png
**Range:** 0 ≤ dmod < 1, does not indicate bias, larger is better.
**Notes:** When j=1, this metric is the same as d1. As j becomes larger, outliers have a larger
impact on the value.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
Optional input indicating the j values desired. A higher j places more emphasis on
outliers. j is 1 by default.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified index of agreement.
Examples
--------
Note that using the default is the same as calculating the d1 metric. Changing the value of j
modification of the metric.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dmod(sim, obs) # Same as d1
0.8434782608695652
>>> he.dmod(sim, obs, j=1.5)
0.9413310986805733
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = (b + c) ** j
return 1 - (np.sum(a) / np.sum(e))
def watt_m(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute Watterson's M (M).
.. image:: /pictures/M.png
**Range:** -1 ≤ M < 1, does not indicate bias, larger is better.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
Watterson's M value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.watt_m(sim, obs)
0.8307913876595929
References
----------
- Watterson, I.G., 1996. Non‐dimensional measures of climate model performance. International
Journal of Climatology 16(4) 379-391.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 2 / np.pi
b = np.mean((simulated_array - observed_array) ** 2) # MSE
c = np.std(observed_array, ddof=1) ** 2 + np.std(simulated_array, ddof=1) ** 2
e = (np.mean(simulated_array) - np.mean(observed_array)) ** 2
f = c + e
return a * np.arcsin(1 - (b / f))
def mb_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute Mielke-Berry R value (MB R).
.. image:: /pictures/MB_R.png
**Range:** 0 ≤ MB R < 1, does not indicate bias, larger is better.
**Notes:** Compares prediction to probability it arose by chance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Mielke-Berry R value.
Notes
-----
If a more optimized version is desired, the `numba package <http://numba.pydata.org/doc.html>`_ can be implemented
for a much more optimized performance when computing this metric. An example is given below.
>>> from numba import njit, prange
>>> @njit(parallel=True, fastmath=True)
>>> def mb_par_fastmath(pred, obs): # uses LLVM compiler
>>> assert pred.size == obs.size
>>> n = pred.size
>>> tot = 0.0
>>> mae = 0.0
>>> for i in range(n):
>>> for j in prange(n):
>>> tot += abs(pred[i] - obs[j])
>>> mae += abs(pred[i] - obs[i])
>>> mae = mae / n
>>> mb = 1 - ((n ** 2) * mae / tot)
>>>
>>> return mb
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mb_r(sim, obs)
0.7726315789473684
References
----------
- Berry, K.J., Mielke, P.W., 1988. A Generalization of Cohen's Kappa Agreement Measure to
Interval Measurement and Multiple Raters. Educational and Psychological Measurement 48(4)
921-933.
- Mielke, P.W., Berry, K.J., 2007. Permutation methods: a distance function approach.
Springer Science & Business Media.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Calculate metric
n = simulated_array.size
tot = 0.0
for i in range(n):
tot = tot + np.sum(np.abs(simulated_array - observed_array[i]))
mae_val = np.sum(np.abs(simulated_array - observed_array)) / n
mb = 1 - ((n ** 2) * mae_val / tot)
return mb
def nse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Nash-Sutcliffe Efficiency.
.. image:: /pictures/NSE.png
**Range:** -inf < NSE < 1, does not indicate bias, larger is better.
**Notes:** The Nash-Sutcliffe efficiency metric compares prediction values to naive predictions
(i.e. average value). One major flaw of this metric is that it punishes a higher variance in
the observed values (denominator). This metric is analogous to the mean absolute error skill
score (MAESS) using the mean flow as a benchmark.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Nash-Sutcliffe Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse(sim, obs)
0.922093023255814
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
- McCuen, R.H., Knight, Z., Cutter, A.G., 2006. Evaluation of the Nash-Sutcliffe Efficiency
Index. Journal of Hydraulic Engineering.
- Nash, J.E., Sutcliffe, J.V., 1970. River flow forecasting through conceptual models part
I — A discussion of principles. Journal of Hydrology 282-290.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** 2
b = (np.abs(observed_array - np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def nse_mod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the modified Nash-Sutcliffe efficiency (NSE mod).
.. image:: /pictures/NSEmod.png
**Range:** -inf < NSE (mod) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
If given, sets the value of j to the input. j is 1 by default. A higher j gives more
emphasis to outliers
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_mod(sim, obs)
0.6949152542372882
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = (np.abs(observed_array - np.mean(observed_array))) ** j
return 1 - (np.sum(a) / np.sum(b))
def nse_rel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the relative Nash-Sutcliffe efficiency (NSE rel).
.. image:: /pictures/NSErel.png
**Range:** -inf < NSE (rel) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_rel(sim, obs)
0.9062004687708474
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs((simulated_array - observed_array) / observed_array)) ** 2
b = (np.abs((observed_array - np.mean(observed_array)) / np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def kge_2009(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""Compute the Kling-Gupta efficiency (2009).
.. image:: /pictures/KGE_2009.png
**Range:** -inf < KGE (2009) < 1, larger is better.
**Notes:** Gupta et al. (2009) created this metric to demonstrate the relative importance of
the three components of the NSE, which are correlation, bias and variability. This was done
with hydrologic modeling as the context. This metric is meant to address issues with the NSE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), Alpha, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, alpha, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2009) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2009(sim, obs)
0.912223072345668
>>> he.kge_2009(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.927910707932087, 1.0058823529411764, 0.9181073779138655)
References
----------
- Gupta, H. V., Kling, H., Yilmaz, K. K., & Martinez, G. F. (2009). Decomposition of the mean
squared error and NSE performance criteria: Implications for improving hydrological modelling.
Journal of Hydrology, 377(1-2), 80-91.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array, ddof=1)
obs_sigma = np.std(observed_array, ddof=1)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
if obs_mean != 0:
beta = sim_mean / obs_mean
else:
beta = np.nan
# Relative variability between simulated and observed values
if obs_sigma != 0:
alpha = sim_sigma / obs_sigma
else:
alpha = np.nan
if not np.isnan(beta) and not np.isnan(alpha):
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (alpha - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Alpha is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, alpha, beta, kge
else:
return kge
def kge_2012(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""
Compute the Kling-Gupta efficiency (2012).
.. image:: /pictures/KGE_2012.png
**Range:** -inf < KGE (2012) < 1, does not indicate bias, larger is better.
**Notes:** The modified version of the KGE (2009). Kling proposed this version to avoid
cross-correlation between bias and variability ratios.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), gamma, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, gamma, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2012) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2012(sim, obs)
0.9122230723456678
>>> he.kge_2012(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.9224843295231272, 1.0058823529411764, 0.9132923608280753)
References
----------
- Kling, H., Fuchs, M., & Paulin, M. (2012). Runoff conditions in the upper Danube basin under
an ensemble of climate change scenarios. Journal of Hydrology, 424, 264-277.
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array)
obs_sigma = np.std(observed_array)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
beta = sim_mean / obs_mean
# CV is the coefficient of variation (standard deviation / mean)
sim_cv = sim_sigma / sim_mean
obs_cv = obs_sigma / obs_mean
# Variability Ratio, or the ratio of simulated CV to observed CV
gam = sim_cv / obs_cv
if obs_mean != 0 and obs_sigma != 0 and sim_mean != 0:
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (gam - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
if sim_mean == 0:
warnings.warn(
'Warning: The simulated data mean is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, gam, beta, kge
else:
return kge
def lm_index(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""
Compute the Legate-McCabe Efficiency Index.
.. image:: /pictures/E1p.png
**Range:** 0 ≤ E1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.lm_index(sim, obs)
0.6949152542372882
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
mean_obs = np.mean(observed_array)
if obs_bar_p is not None:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def d1_p(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""Compute the Legate-McCabe Index of Agreement.
.. image:: /pictures/D1p.png
**Range:** 0 ≤ d1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1_p(sim, obs)
0.8434782608695652
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
if obs_bar_p is not None:
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - obs_bar_p) + np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
mean_obs = np.mean(observed_array)
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - mean_obs) + np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def ve(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Volumetric Efficiency (VE).
.. image:: /pictures/VE.png
**Range:** 0 ≤ VE < 1 smaller is better, does not indicate bias.
**Notes:** Represents the error as a percentage of flow.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Volumetric Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ve(sim, obs)
0.8947368421052632
References
----------
- Criss, R.E., Winston, W.E., 2008. Do Nash values have value? Discussion and alternate
proposals. Hydrological Processes 22(14) 2723.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(observed_array)
return 1 - (a / b)
def sa(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Angle (SA).
.. image:: /pictures/SA.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral angle metric measures the angle between the two vectors in hyperspace.
It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Angle value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sa(sim, obs)
0.10816831366492945
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(simulated_array, observed_array)
b = np.linalg.norm(simulated_array) * np.linalg.norm(observed_array)
return np.arccos(a / b)
def sc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Correlation (SC).
.. image:: /pictures/SC.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral correlation metric measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Correlation value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sc(sim, obs)
0.27991341383646606
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(observed_array - np.mean(observed_array), simulated_array - np.mean(simulated_array))
b = np.linalg.norm(observed_array - np.mean(observed_array))
c = np.linalg.norm(simulated_array - np.mean(simulated_array))
e = b * c
return np.arccos(a / e)
def sid(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Information Divergence (SID).
.. image:: /pictures/SID.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral information divergence measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral information divergence value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sid(sim, obs)
0.03517616895318012
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
first = (observed_array / np.mean(observed_array)) - (
simulated_array / np.mean(simulated_array))
second1 = np.log10(observed_array) - np.log10(np.mean(observed_array))
second2 = np.log10(simulated_array) - np.log10(np.mean(simulated_array))
return np.dot(first, second1 - second2)
def sga(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Gradient Angle (SGA).
.. image:: /pictures/SGA.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral gradient angle measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
SG is the gradient of the simulated or observed time series.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Gradient Angle.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sga(sim, obs)
0.26764286472739834
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sgx = observed_array[1:] - observed_array[:observed_array.size - 1]
sgy = simulated_array[1:] - simulated_array[:simulated_array.size - 1]
a = np.dot(sgx, sgy)
b = np.linalg.norm(sgx) * np.linalg.norm(sgy)
return np.arccos(a / b)
####################################################################################################
# H Metrics: Methods from Tornqvist L, Vartia P, and Vartia YO. (1985) #
####################################################################################################
def h1_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the H1 mean error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mhe(sim, obs)
0.002106551840594386
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(h)
def h1_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H1 absolute error.
.. image:: /pictures/H1.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The H1 absolute error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mahe(sim, obs)
0.11639226612630865
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(np.abs(h))
def h1_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H1 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean squared H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_rmshe(sim, obs)
0.12865571253672756
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.sqrt(np.mean(h ** 2))
def h2_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean error.
.. image:: /pictures/H2.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mhe(sim, obs)
-0.015319829424307036
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(h)
def h2_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean absolute error.
.. image:: /pictures/H2.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mahe(sim, obs)
0.11997591408039167
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(np.abs(h))
def h2_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_rmshe(sim, obs)
0.1373586680669673
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.sqrt(np.mean(h ** 2))
def h3_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 mean error.
.. image:: /pictures/H3.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mhe(sim, obs)
-0.006322019630356533
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(h)
def h3_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H3 mean absolute error.
.. image:: /pictures/H3.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mahe(sim, obs)
0.11743831388794855
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(np.abs(h))
def h3_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 root mean square error.
.. image:: /pictures/H3.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.sqrt(np.mean(h ** 2))
def h4_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mhe(sim, obs)
-0.0064637371129817
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(h)
def h4_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H4 mean absolute error.
.. image:: /pictures/H4.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mahe(sim, obs)
0.11781032209144082
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(np.abs(h))
def h4_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_rmshe(sim, obs)
0.13200901963465006
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.sqrt(np.mean(h ** 2))
def h5_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean error.
.. image:: /pictures/H5.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mhe(sim, obs)
-0.006606638791856322
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(h)
def h5_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean absolute error.
.. image:: /pictures/H5.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mahe(sim, obs)
0.11818409010335018
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(np.abs(h))
def h5_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 root mean square error.
.. image:: /pictures/H5.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_rmshe(sim, obs)
0.13254476469410933
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h6_mhe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H6 mean error.
.. image:: /pictures/H6.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mhe(sim, obs)
-0.006322019630356514
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(h)
def h6_mahe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""Compute the H6 mean absolute error.
.. image:: /pictures/H6.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mahe(sim, obs)
0.11743831388794852
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(np.abs(h))
def h6_rmshe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the H6 root mean square error.
.. image:: /pictures/H6.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h7_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean error.
.. image:: /pictures/H7.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mhe(sim, obs)
0.0026331898007430263
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(h)
def h7_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean absolute error.
.. image:: /pictures/H7.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mahe(sim, obs)
0.14549033265788583
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(np.abs(h))
def h7_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 root mean square error.
.. image:: /pictures/H7.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_rmshe(sim, obs)
0.16081964067090945
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
def h8_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H8 mean error.
.. image:: /pictures/H8.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mhe(sim, obs)
0.0018056158633666466
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(h)
def h8_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 mean absolute error.
.. image:: /pictures/H8.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mahe(sim, obs)
0.099764799536836
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(np.abs(h))
def h8_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 root mean square error.
.. image:: /pictures/H8.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_rmshe(sim, obs)
0.11027632503148076
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
# def h9(simulated_array, observed_array, h_type='mhe', k=1):
# h = (simulated_array / observed_array - 1) / \
# np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
# if h_type == 'mhe':
# return h.mean()
# elif h_type == 'ahe':
# return np.abs(h).mean()
# elif h_type == 'rmshe':
# return np.sqrt((h**2).mean())
# else:
# raise RuntimeError("The three types available are 'mhe', 'ahe', and 'rmshe'.")
def h10_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean error.
.. image:: /pictures/H10.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h10_mhe(sim, obs)
-0.0012578676058971154
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(h)
def h10_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean absolute error.
.. image:: /pictures/H10.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_mahe(sim, obs), 6)
0.094636
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(np.abs(h))
def h10_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 root mean square error.
.. image:: /pictures/H10.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_rmshe(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.sqrt(np.mean(h ** 2))
###################################################################################################
# Statistical Error Metrics for Distribution Testing #
###################################################################################################
def g_mean_diff(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the geometric mean difference.
.. image:: /pictures/GMD.png
**Range:**
**Notes:** For the difference of geometric means, the geometric mean is computed for each of
two samples then their difference is taken.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The geometric mean difference value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.g_mean_diff(sim, obs)
0.988855412098022
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.exp(gmean(sim_log) - gmean(obs_log))
def mean_var(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the mean variance.
.. image:: /pictures/MV.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean variance.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.mean_var(sim, obs), 6)
0.010641
References
----------
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.var(np.log1p(observed_array) - np.log1p(simulated_array))
####################################################################################################
# HELPER FUNCTIONS AND API INFORMATION #
####################################################################################################
metric_names = [
'Mean Error', 'Mean Absolute Error', 'Mean Squared Error', 'Mean Log Error',
'Mean Absolute Log Error', 'Mean Squared Log Error', 'Median Error', 'Median Absolute Error',
'Median Squared Error', 'Eclidean Distance', 'Normalized Eclidean Distance',
'Root Mean Square Error', 'Root Mean Squared Log Error',
'Normalized Root Mean Square Error - Range', 'Normalized Root Mean Square Error - Mean',
'Normalized Root Mean Square Error - IQR', 'Inertial Root Mean Square Error',
'Mean Absolute Scaled Error', 'Coefficient of Determination', 'Pearson Correlation Coefficient',
'Spearman Rank Correlation Coefficient', 'Anomaly Correlation Coefficient',
'Mean Absolute Percentage Error', 'Mean Absolute Percentage Deviation',
'Mean Arctangent Absolute Percentage Error', 'Symmetric Mean Absolute Percentage Error (1)',
'Symmetric Mean Absolute Percentage Error (2)', 'Index of Agreement (d)',
'Index of Agreement (d1)', 'Modified Index of Agreement', 'Relative Index of Agreement',
'Index of Agreement Refined (dr)', "Watterson's M", 'Mielke-Berry R',
'Nash-Sutcliffe Efficiency', 'Modified Nash-Sutcliffe Efficiency',
'Relative Nash-Sutcliffe Efficiency', 'Kling-Gupta Efficiency (2009)',
'Kling-Gupta Efficiency (2012)', 'Legate-McCabe Efficiency Index',
'Legate-McCabe Index of Agreement', 'Volumetric Efficiency', 'Spectral Angle',
'Spectral Correlation', 'Spectral Information Divergence', 'Spectral Gradient Angle',
'Mean H1 Error', 'Mean Absolute H1 Error', 'Root Mean Square H1 Error', 'Mean H2 Error',
'Mean Absolute H2 Error', 'Root Mean Square H2 Error', 'Mean H3 Error',
'Mean Absolute H3 Error', 'Root Mean Square H3 Error', 'Mean H4 Error',
'Mean Absolute H4 Error', 'Root Mean Square H4 Error', 'Mean H5 Error',
'Mean Absolute H5 Error', 'Root Mean Square H5 Error', 'Mean H6 Error',
'Mean Absolute H6 Error', 'Root Mean Square H6 Error', 'Mean H7 Error',
'Mean Absolute H7 Error', 'Root Mean Square H7 Error', 'Mean H8 Error',
'Mean Absolute H8 Error', 'Root Mean Square H8 Error', 'Mean H10 Error',
'Mean Absolute H10 Error', 'Root Mean Square H10 Error', 'Geometric Mean Difference',
'Mean Variance'
]
metric_abbr = [
'ME', 'MAE', 'MSE', 'MLE', 'MALE', 'MSLE', 'MdE', 'MdAE', 'MdSE', 'ED', 'NED', 'RMSE', 'RMSLE',
'NRMSE (Range)', 'NRMSE (Mean)', 'NRMSE (IQR)', 'IRMSE', 'MASE', 'r2', 'R (Pearson)',
'R (Spearman)', 'ACC', 'MAPE', 'MAPD', 'MAAPE', 'SMAPE1', 'SMAPE2', 'd', 'd1', 'd (Mod.)',
'd (Rel.)', 'dr', 'M', '(MB) R', 'NSE', 'NSE (Mod.)', 'NSE (Rel.)', 'KGE (2009)', 'KGE (2012)',
"E1'", "D1'", 'VE', 'SA', 'SC', 'SID', 'SGA', 'H1 (MHE)', 'H1 (MAHE)', 'H1 (RMSHE)', 'H2 (MHE)',
'H2 (MAHE)', 'H2 (RMSHE)', 'H3 (MHE)', 'H3 (MAHE)', 'H3 (RMSHE)', 'H4 (MHE)', 'H4 (MAHE)',
'H4 (RMSHE)', 'H5 (MHE)', 'H5 (MAHE)', 'H5 (RMSHE)', 'H6 (MHE)', 'H6 (MAHE)', 'H6 (RMSHE)',
'H7 (MHE)', 'H7 (MAHE)', 'H7 (RMSHE)', 'H8 (MHE)', 'H8 (MAHE)', 'H8 (RMSHE)', 'H10 (MHE)',
'H10 (MAHE)', 'H10 (RMSHE)', 'GMD', 'MV'
]
function_list = [
me, mae, mse, mle, male, msle, mde, mdae, mdse, ed, ned, rmse, rmsle, nrmse_range, nrmse_mean,
nrmse_iqr, irmse, mase, r_squared, pearson_r, spearman_r, acc, mape, mapd, maape, smape1,
smape2, d, d1, dmod, drel, dr, watt_m, mb_r, nse, nse_mod, nse_rel, kge_2009, kge_2012,
lm_index, d1_p, ve, sa, sc, sid, sga, h1_mhe, h1_mahe, h1_rmshe, h2_mhe, h2_mahe, h2_rmshe,
h3_mhe, h3_mahe, h3_rmshe, h4_mhe, h4_mahe, h4_rmshe, h5_mhe, h5_mahe, h5_rmshe, h6_mhe,
h6_mahe, h6_rmshe, h7_mhe, h7_mahe, h7_rmshe, h8_mhe, h8_mahe, h8_rmshe, h10_mhe, h10_mahe,
h10_rmshe, g_mean_diff, mean_var,
]
# Assign some properties to each function for ease of use for users
for i in range(len(function_list)):
function_list[i].name = metric_names[i]
function_list[i].abbr = metric_abbr[i]
def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Removes the nan, negative, and inf values in two numpy arrays"""
sim_copy = np.copy(simulated_array)
obs_copy = np.copy(observed_array)
# Checking to see if the vectors are the same length
assert sim_copy.ndim == 1, "The simulated array is not one dimensional."
assert obs_copy.ndim == 1, "The observed array is not one dimensional."
if sim_copy.size != obs_copy.size:
raise RuntimeError("The two ndarrays are not the same size.")
# Treat missing data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain nan values
all_treatment_array = np.ones(obs_copy.size, dtype=bool)
if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_nan = np.isnan(sim_copy)
obs_nan = np.isnan(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_nan] = replace_nan
obs_copy[obs_nan] = replace_nan
warnings.warn("Elements(s) {} contained NaN values in the simulated array and "
"elements(s) {} contained NaN values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_nan)[0],
np.where(obs_nan)[0]),
UserWarning)
else:
# Getting the indices of the nan values, combining them, and informing user.
nan_indices_fcst = ~np.isnan(sim_copy)
nan_indices_obs = ~np.isnan(obs_copy)
all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)
warnings.warn("Row(s) {} contained NaN values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_nan_indices)[0]),
UserWarning)
if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_inf = np.isinf(sim_copy)
obs_inf = np.isinf(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_inf] = replace_inf
obs_copy[obs_inf] = replace_inf
warnings.warn("Elements(s) {} contained Inf values in the simulated array and "
"elements(s) {} contained Inf values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_inf)[0],
np.where(obs_inf)[0]),
UserWarning)
else:
inf_indices_fcst = ~(np.isinf(sim_copy))
inf_indices_obs = ~np.isinf(obs_copy)
all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)
warnings.warn(
"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows "
"are zero indexed).".format(np.where(~all_inf_indices)[0]),
UserWarning
)
# Treat zero data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain zero values
if remove_zero:
if (obs_copy == 0).any() or (sim_copy == 0).any():
zero_indices_fcst = ~(sim_copy == 0)
zero_indices_obs = ~(obs_copy == 0)
all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)
warnings.warn(
"Row(s) {} contained zero values and the row(s) have been removed (Rows are "
"zero indexed).".format(np.where(~all_zero_indices)[0]),
UserWarning
)
# Treat negative data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain negative values
# Ignore runtime warnings from comparing
if remove_neg:
with np.errstate(invalid='ignore'):
obs_copy_bool = obs_copy < 0
sim_copy_bool = sim_copy < 0
if obs_copy_bool.any() or sim_copy_bool.any():
neg_indices_fcst = ~sim_copy_bool
neg_indices_obs = ~obs_copy_bool
all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)
warnings.warn("Row(s) {} contained negative values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_neg_indices)[0]),
UserWarning)
obs_copy = obs_copy[all_treatment_array]
sim_copy = sim_copy[all_treatment_array]
return sim_copy, obs_copy
if __name__ == "__main__":
pass
|
BYU-Hydroinformatics/HydroErr | HydroErr/HydroErr.py | mle | python | def mle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(sim_log - obs_log) | Compute the mean log error of the simulated and observed data.
.. image:: /pictures/MLE.png
**Range:** -inf < MLE < inf, data units, closer to zero is better.
**Notes** Same as the mean erro (ME) only use log ratios as the error term. Limits the impact of outliers, more
evenly weights high and low data values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mle(sim, obs)
0.002961767058151136
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46. | train | https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L271-L348 | [
"def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,\n remove_neg=False, remove_zero=False):\n \"\"\"Removes the nan, negative, and inf values in two numpy arrays\"\"\"\n sim_copy = np.copy(simulated_array)\n obs_copy = np.copy(observed_array)\n\n # Checking to see if the vectors are the same length\n assert sim_copy.ndim == 1, \"The simulated array is not one dimensional.\"\n assert obs_copy.ndim == 1, \"The observed array is not one dimensional.\"\n\n if sim_copy.size != obs_copy.size:\n raise RuntimeError(\"The two ndarrays are not the same size.\")\n\n # Treat missing data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain nan values\n all_treatment_array = np.ones(obs_copy.size, dtype=bool)\n\n if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_nan = np.isnan(sim_copy)\n obs_nan = np.isnan(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_nan] = replace_nan\n obs_copy[obs_nan] = replace_nan\n\n warnings.warn(\"Elements(s) {} contained NaN values in the simulated array and \"\n \"elements(s) {} contained NaN values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_nan)[0],\n np.where(obs_nan)[0]),\n UserWarning)\n else:\n # Getting the indices of the nan values, combining them, and informing user.\n nan_indices_fcst = ~np.isnan(sim_copy)\n nan_indices_obs = ~np.isnan(obs_copy)\n all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)\n\n warnings.warn(\"Row(s) {} contained NaN values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_nan_indices)[0]),\n UserWarning)\n\n if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_inf = np.isinf(sim_copy)\n obs_inf = np.isinf(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_inf] = replace_inf\n obs_copy[obs_inf] = replace_inf\n\n warnings.warn(\"Elements(s) {} contained Inf values in the simulated array and \"\n \"elements(s) {} contained Inf values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_inf)[0],\n np.where(obs_inf)[0]),\n UserWarning)\n else:\n inf_indices_fcst = ~(np.isinf(sim_copy))\n inf_indices_obs = ~np.isinf(obs_copy)\n all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)\n\n warnings.warn(\n \"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows \"\n \"are zero indexed).\".format(np.where(~all_inf_indices)[0]),\n UserWarning\n )\n\n # Treat zero data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain zero values\n if remove_zero:\n if (obs_copy == 0).any() or (sim_copy == 0).any():\n zero_indices_fcst = ~(sim_copy == 0)\n zero_indices_obs = ~(obs_copy == 0)\n all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)\n\n warnings.warn(\n \"Row(s) {} contained zero values and the row(s) have been removed (Rows are \"\n \"zero indexed).\".format(np.where(~all_zero_indices)[0]),\n UserWarning\n )\n\n # Treat negative data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain negative values\n\n # Ignore runtime warnings from comparing\n if remove_neg:\n with np.errstate(invalid='ignore'):\n obs_copy_bool = obs_copy < 0\n sim_copy_bool = sim_copy < 0\n\n if obs_copy_bool.any() or sim_copy_bool.any():\n neg_indices_fcst = ~sim_copy_bool\n neg_indices_obs = ~obs_copy_bool\n all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)\n\n warnings.warn(\"Row(s) {} contained negative values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_neg_indices)[0]),\n UserWarning)\n\n obs_copy = obs_copy[all_treatment_array]\n sim_copy = sim_copy[all_treatment_array]\n\n return sim_copy, obs_copy\n"
] | # -*- coding: utf-8 -*-
"""
HydroErr contains a library of goodness of fit metrics that measure hydrologic skill.
Each metric is contained in function, and every function has the parameters to treat missing values as
well as remove zero and negative values from the timeseries data.
Each function contains two properties, name and abbr. These can be used in the Hydrostats package when creating tables
and adding metrics to the plots. Link to the hydrostats package: https://github.com/BYU-Hydroinformatics/Hydrostats.
An example of this functionality is shown below.
>>> import HydroErr as he
>>>
>>> he.acc.name
'Anomaly Correlation Coefficient'
>>> he.acc.abbr
'ACC'
"""
from __future__ import division
import numpy as np
from scipy.stats import gmean, rankdata
import warnings
__all__ = ['me', 'mae', 'mse', 'mle', 'male', 'msle', 'mde', 'mdae', 'mdse', 'ed', 'ned', 'rmse',
'rmsle', 'nrmse_range', 'nrmse_mean', 'nrmse_iqr', 'irmse', 'mase', 'r_squared',
'pearson_r', 'spearman_r', 'acc', 'mape', 'mapd', 'maape', 'smape1', 'smape2', 'd', 'd1',
'dmod', 'drel', 'dr', 'watt_m', 'mb_r', 'nse', 'nse_mod', 'nse_rel', 'kge_2009',
'kge_2012', 'lm_index', 'd1_p', 've', 'sa', 'sc', 'sid', 'sga', 'h1_mhe', 'h1_mahe',
'h1_rmshe', 'h2_mhe', 'h2_mahe', 'h2_rmshe', 'h3_mhe', 'h3_mahe', 'h3_rmshe', 'h4_mhe',
'h4_mahe', 'h4_rmshe', 'h5_mhe', 'h5_mahe', 'h5_rmshe', 'h6_mhe', 'h6_mahe', 'h6_rmshe',
'h7_mhe', 'h7_mahe', 'h7_rmshe', 'h8_mhe', 'h8_mahe', 'h8_rmshe', 'h10_mhe', 'h10_mahe',
'h10_rmshe', 'g_mean_diff', 'mean_var']
####################################################################################################
# General and Hydrological Error Metrics #
####################################################################################################
def me(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean error of the simulated and observed data.
.. image:: /pictures/ME.png
**Range:** -inf < MAE < inf, data units, closer to zero is better, indicates bias.
**Notes:** The mean error (ME) measures the difference between the simulated data and the
observed data. For the mean error, a smaller number indicates a better fit to the original
data. Note that if the error is in the form of random noise, the mean error will be very small,
which can skew the accuracy of this metric. ME is cumulative and will be small even if there
are large positive and negative errors that balance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean error value.
Examples
--------
Note that in this example the random noise cancels, leaving a very small ME.
>>> import HydroErr as he
>>> import numpy as np
>>> # Seed for reproducibility
>>> np.random.seed(54839)
>>> x = np.arange(100) / 20
>>> sim = np.sin(x) + 2
>>> obs = sim * (((np.random.rand(100) - 0.5) / 10) + 1)
>>> he.me(sim, obs)
-0.006832220968967168
References
----------
- Fisher, R.A., 1920. A Mathematical Examination of the Methods of Determining the Accuracy of
an Observation by the Mean Error, and by the Mean Square Error. Monthly Notices of the Royal
Astronomical Society 80 758 - 770.
"""
# Treating missing values
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero)
return np.mean(simulated_array - observed_array)
def mae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute error of the simulated and observed data.
.. image:: /pictures/MAE.png
**Range:** 0 ≤ MAE < inf, data units, smaller is better.
**Notes:** The ME measures the absolute difference between the simulated data and the observed
data. For the mean abolute error, a smaller number indicates a better fit to the original data.
Also note that random errors do not cancel. Also referred to as an L1-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute error value.
References
----------
- Willmott, Cort J., and Kenji Matsuura. “Advantages of the Mean Absolute Error (MAE) over the
Root Mean Square Error (RMSE) in Assessing Average Model Performance.” Climate Research 30,
no. 1 (2005): 79–82.
- Willmott, Cort J., and Kenji Matsuura. “On the Use of Dimensioned Measures of Error to
Evaluate the Performance of Spatial Interpolators.” International Journal of Geographical
Information Science 20, no. 1 (2006): 89–102.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mae(sim, obs)
0.5666666666666665
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean(np.absolute(simulated_array - observed_array))
def mse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared error of the simulated and observed data.
.. image:: /pictures/MSE.png
**Range:** 0 ≤ MSE < inf, data units squared, smaller is better.
**Notes:** Random errors do not cancel, highlights larger errors, also referred to as a
squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mse(sim, obs)
0.4333333333333333
References
----------
- Wang, Zhou, and Alan C. Bovik. “Mean Squared Error: Love It or Leave It? A New Look at Signal
Fidelity Measures.” IEEE Signal Processing Magazine 26, no. 1 (2009): 98–117.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean((simulated_array - observed_array) ** 2)
def mle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean log error of the simulated and observed data.
.. image:: /pictures/MLE.png
**Range:** -inf < MLE < inf, data units, closer to zero is better.
**Notes** Same as the mean erro (ME) only use log ratios as the error term. Limits the impact of outliers, more
evenly weights high and low data values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mle(sim, obs)
0.002961767058151136
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(sim_log - obs_log)
def male(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean absolute log error of the simulated and observed data.
.. image:: /pictures/MALE.png
**Range:** 0 ≤ MALE < inf, data units squared, smaller is better.
**Notes** Same as MAE only use log ratios as the error term. Limits the impact of outliers,
more evenly weights high and low flows.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.male(sim, obs), 6)
0.090417
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(np.abs(sim_log - obs_log))
def msle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared log error of the simulated and observed data.
.. image:: /pictures/MSLE.png
**Range:** 0 ≤ MSLE < inf, data units squared, smaller is better.
**Notes** Same as the mean squared error (MSE) only use log ratios as the error term. Limits
the impact of outliers, more evenly weights high and low values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.msle(sim, obs), 6)
0.010426
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean((sim_log - obs_log) ** 2)
def mde(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median error (MdE) between the simulated and observed data.
.. image:: /pictures/MdE.png
**Range** -inf < MdE < inf, closer to zero is better.
**Notes** This metric indicates bias. It is similar to the mean error (ME), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mde(sim, obs)
-0.10000000000000009
Returns
-------
float
The median error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(simulated_array - observed_array)
def mdae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median absolute error (MdAE) between the simulated and observed data.
.. image:: /pictures/MdAE.png
**Range** 0 ≤ MdAE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean absolute error (MAE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdae(sim, obs)
0.75
Returns
-------
float
The median absolute error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(np.abs(simulated_array - observed_array))
def mdse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median squared error (MdSE) between the simulated and observed data.
.. image:: /pictures/MdSE.png
**Range** 0 ≤ MdSE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean squared error (MSE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdse(sim, obs)
0.625
Returns
-------
float
The median squared error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median((simulated_array - observed_array) ** 2)
def ed(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Euclidean distance between predicted and observed values in vector space.
.. image:: /pictures/ED.png
**Range** 0 ≤ ED < inf, smaller is better.
**Notes** Also sometimes referred to as the L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ed(sim, obs)
1.63707055437449
Returns
-------
float
The euclidean distance error value.
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.linalg.norm(observed_array - simulated_array)
def ned(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the normalized Euclidian distance between the simulated and observed data in vector
space.
.. image:: /pictures/NED.png
**Range** 0 ≤ NED < inf, smaller is better.
**Notes** Also sometimes referred to as the squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The normalized euclidean distance value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ned(sim, obs)
0.2872053604165771
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array / np.mean(observed_array)
b = simulated_array / np.mean(simulated_array)
return np.linalg.norm(a - b)
def rmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square error between the simulated and observed data.
.. image:: /pictures/RMSE.png
**Range** 0 ≤ RMSE < inf, smaller is better.
**Notes:** The standard deviation of the residuals. A lower spread indicates that the points
are better concentrated around the line of best fit (linear). Random errors do not cancel.
This metric will highlights larger errors.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.rmse(sim, obs)
0.668331255192114
References
----------
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.sqrt(np.mean((simulated_array - observed_array) ** 2))
def rmsle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square log error between the simulated and observed data.
.. image:: /pictures/RMSLE.png
**Range:** 0 ≤ RMSLE < inf. Smaller is better, and it does not indicate bias.
**Notes:** Random errors do not cancel while using this metric. This metric limits the
impact of outliers by more evenly weighting high and low values. To calculate the log values,
each value in the observed and simulated array is increased by one unit in order to avoid
run-time errors and nan values (function np.log1p).
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square log error value.
Examples
--------
Notice that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.rmsle(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
"""
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf, remove_neg=remove_neg,
remove_zero=remove_zero)
return np.sqrt(np.mean(np.power(np.log1p(simulated_array) - np.log1p(observed_array), 2)))
def nrmse_range(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the range normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Range.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the range of the observed time series (x).
Normalizing allows comparison between data sets with different scales. The NRMSErange is the
most sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The range normalized root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_range(sim, obs)
0.0891108340256152
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_max = np.max(observed_array)
obs_min = np.min(observed_array)
return rmse_value / (obs_max - obs_min)
def nrmse_mean(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Mean.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the mean of the observed time series (x).
Normalizing allows comparison between data sets with different scales.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_mean(sim, obs)
0.11725109740212526
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_mean = np.mean(observed_array)
return rmse_value / obs_mean
def nrmse_iqr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the IQR normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_IQR.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the interquartile range of the observed time
series (x). Normalizing allows comparison between data sets with different scales.
The NRMSEquartile is the least sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The IQR normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_iqr(sim, obs)
0.2595461185212093
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
q1 = np.percentile(observed_array, 25)
q3 = np.percentile(observed_array, 75)
iqr = q3 - q1
return rmse_value / iqr
def irmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the inertial root mean square error (IRMSE) between the simulated and observed data.
.. image:: /pictures/IRMSE.png
**Range:** 0 ≤ IRMSE < inf, lower is better.
**Notes:** This metric is the RMSE devided by by the standard deviation of the gradient of the
observed timeseries data. This metric is meant to be help understand the ability of the model
to predict changes in observation.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The inertial root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.irmse(sim, obs)
0.14572738134831856
References
----------
- Daga, M., Deo, M.C., 2009. Alternative data-driven methods to estimate wind from waves by
inverse modeling. Natural Hazards 49(2) 293-310.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Getting the gradient of the observed data
obs_len = observed_array.size
obs_grad = observed_array[1:obs_len] - observed_array[0:obs_len - 1]
# Standard deviation of the gradient
obs_grad_std = np.std(obs_grad, ddof=1)
# Divide RMSE by the standard deviation of the gradient of the observed data
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
return rmse_value / obs_grad_std
def mase(simulated_array, observed_array, m=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute scaled error between the simulated and observed data.
.. image:: /pictures/MASE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
m: int
If given, indicates the seasonal period m. If not given, the default is 1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute scaled error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mase(sim, obs)
0.17341040462427745
References
----------
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
start = m
end = simulated_array.size - m
a = np.mean(np.abs(simulated_array - observed_array))
b = np.abs(observed_array[start:observed_array.size] - observed_array[:end])
return a / (np.sum(b) / end)
def pearson_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the pearson correlation coefficient.
.. image:: /pictures/R_pearson.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The pearson r coefficient measures linear correlation. It is sensitive to outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Pearson correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.pearson_r(sim, obs)
0.9610793632835262
References
----------
- Pearson, K. (1895). Note on regression and inheritance in the case of two parents.
Proceedings of the Royal Society of London, 58, 240-242.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
top = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1 = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2 = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
return top / (bot1 * bot2)
def spearman_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the spearman rank correlation coefficient.
.. image:: /pictures/R_spearman.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The spearman r coefficient measures the monotonic relation between simulated and
observed data. Because it uses a nonparametric measure of rank correlation, it is less sensitive
to outliers compared to the Pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spearman rank correlation coefficient.
Examples
----------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.spearman_r(sim, obs)
0.942857142857143
References
----------
- Spearman C (1904). "The proof and measurement of association between two things". American
Journal of Psychology. 15: 72–101. doi:10.2307/1412159
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rank_sim = rankdata(simulated_array)
rank_obs = rankdata(observed_array)
mean_rank_sim = np.mean(rank_sim)
mean_rank_obs = np.mean(rank_obs)
top = np.mean((rank_obs - mean_rank_obs) * (rank_sim - mean_rank_sim))
bot = np.sqrt(
np.mean((rank_obs - mean_rank_obs) ** 2) * np.mean((rank_sim - mean_rank_sim) ** 2))
return top / bot
def r_squared(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Coefficient of Determination (r2).
.. image:: /pictures/r2.png
**Range:** 0 ≤ r2 ≤ 1. 1 indicates perfect correlation, 0 indicates complete randomness.
**Notes:** The Coefficient of Determination measures the linear relation between simulated and
observed data. Because it is the pearson correlation coefficient squared, it is more heavily
affected by outliers than the pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The coefficient of determination (R^2).
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.r_squared(sim, obs)
0.9236735425294681
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array - np.mean(observed_array)
b = simulated_array - np.mean(simulated_array)
return (np.sum(a * b)) ** 2 / (np.sum(a ** 2) * np.sum(b ** 2))
def acc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the anomaly correlation coefficient (ACC).
.. image:: /pictures/ACC.png
**Range:** -1 ≤ ACC ≤ 1. -1 indicates perfect negative correlation of the variation
pattern of the anomalies, 0 indicates complete randomness of the variation patterns of the
anomalies, 1 indicates perfect correlation of the variation pattern of the anomalies.
**Notes:** Common measure in the verification of spatial fields. Measures the correlation
between the variation pattern of the simulated data compared to the observed data.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The anomaly correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.acc(sim, obs)
0.8008994694029383
References
----------
- Langland, Rolf H., and Ryan N. Maue. “Recent Northern Hemisphere Mid-Latitude Medium-Range
Deterministic Forecast Skill.” Tellus A: Dynamic Meteorology and Oceanography 64,
no. 1 (2012): 17531.
- Miyakoda, K., G. D. Hembree, R. F. Strickler, and I. Shulman. “Cumulative Results of Extended
Forecast Experiments I. Model Performance for Winter Cases.” Monthly Weather Review 100, no.
12(1972): 836–55.
- Murphy, Allan H., and Edward S. Epstein. “Skill Scores and Correlation Coefficients in Model
Verification.” Monthly Weather Review 117, no. 3 (1989): 572–82.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - np.mean(simulated_array)
b = observed_array - np.mean(observed_array)
c = np.std(observed_array, ddof=1) * np.std(simulated_array, ddof=1) * simulated_array.size
return np.dot(a, b / c)
def mape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the mean absolute percentage error (MAPE).
.. image:: /pictures/MAPE.png
**Range:** 0% ≤ MAPE ≤ inf. 0% indicates perfect correlation, a larger error indicates a
larger percent error in the data.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
c = 100 / simulated_array.size
return c * np.sum(b)
def mapd(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the mean absolute percentage deviation (MAPD).
.. image:: /pictures/MAPD.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage deviation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mapd(sim, obs)
0.10526315789473682
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(np.abs(observed_array))
return a / b
def maape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the Mean Arctangent Absolute Percentage Error (MAAPE).
.. image:: /pictures/MAAPE.png
**Range:** 0 ≤ MAAPE < π/2, does not indicate bias, smaller is better.
**Notes:** Represents the mean absolute error as a percentage of the observed values. Handles
0s in the observed data. This metric is not as biased as MAPE by under-over predictions.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean arctangent absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
- Kim, S., Kim, H., 2016. A new metric of absolute percentage error for intermittent demand
forecasts. International Journal of Forecasting 32(3) 669-679.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
return np.mean(np.arctan(b))
def smape1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (1) (SMAPE1).
.. image:: /pictures/SMAPE1.png
**Range:** 0 ≤ SMAPE1 < 100%, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (1).
Examples
--------
Note that if we switch the simulated and observed arrays the result is the same
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape1(sim, obs)
5.871915694397428
>>> he.smape1(obs, sim)
5.871915694397428
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 100 / simulated_array.size
b = np.abs(simulated_array - observed_array)
c = np.abs(simulated_array) + np.abs(observed_array)
return a * np.sum(b / c)
def smape2(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (2) (SMAPE2).
.. image:: /pictures/SMAPE2.png
**Range:** 0 ≤ SMAPE1 < 200%, does not indicate bias, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE with only positive metric values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (2).
Examples
--------
Note that switching the simulated and observed arrays yields the same results
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape2(sim, obs)
11.743831388794856
>>> he.smape2(obs, sim)
11.743831388794856
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = (simulated_array + observed_array) / 2
c = 100 / simulated_array.size
return c * np.sum(np.abs(a / b))
def d(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d).
.. image:: /pictures/d.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d(sim, obs)
0.978477353035657
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (observed_array - simulated_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
return 1 - (np.sum(a) / np.sum((b + c) ** 2))
def d1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d1).
.. image:: /pictures/d1.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric. Compared
to the other index of agreement (d) it has a reduced impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (d1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1(sim, obs)
0.8434782608695652
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
obs_mean = np.mean(observed_array)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.abs(simulated_array - obs_mean)
c = np.abs(observed_array - obs_mean)
return 1 - np.sum(a) / np.sum(b + c)
def dr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the refined index of agreement (dr).
.. image:: /pictures/dr.png
**Range:** -1 ≤ dr < 1, does not indicate bias, larger is better.
**Notes:** Reformulation of Willmott’s index of agreement. This metric was created to address
issues in the index of agreement and the Nash-Sutcliffe efficiency metric. Meant to be a
flexible metric for use in climatology.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The refined index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dr(sim, obs)
0.847457627118644
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = 2 * np.sum(np.abs(observed_array - observed_array.mean()))
if a <= b:
return 1 - (a / b)
else:
return (b / a) - 1
def drel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the relative index of agreement (drel).
.. image:: /pictures/drel.png
**Range:** 0 ≤ drel < 1, does not indicate bias, larger is better.
**Notes:** Instead of absolute differences, this metric uses relative differences.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.drel(sim, obs)
0.9740868625579597
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = ((simulated_array - observed_array) / observed_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = ((b + c) / np.mean(observed_array)) ** 2
return 1 - (np.sum(a) / np.sum(e))
def dmod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the modified index of agreement (dmod).
.. image:: /pictures/dmod.png
**Range:** 0 ≤ dmod < 1, does not indicate bias, larger is better.
**Notes:** When j=1, this metric is the same as d1. As j becomes larger, outliers have a larger
impact on the value.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
Optional input indicating the j values desired. A higher j places more emphasis on
outliers. j is 1 by default.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified index of agreement.
Examples
--------
Note that using the default is the same as calculating the d1 metric. Changing the value of j
modification of the metric.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dmod(sim, obs) # Same as d1
0.8434782608695652
>>> he.dmod(sim, obs, j=1.5)
0.9413310986805733
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = (b + c) ** j
return 1 - (np.sum(a) / np.sum(e))
def watt_m(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute Watterson's M (M).
.. image:: /pictures/M.png
**Range:** -1 ≤ M < 1, does not indicate bias, larger is better.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
Watterson's M value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.watt_m(sim, obs)
0.8307913876595929
References
----------
- Watterson, I.G., 1996. Non‐dimensional measures of climate model performance. International
Journal of Climatology 16(4) 379-391.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 2 / np.pi
b = np.mean((simulated_array - observed_array) ** 2) # MSE
c = np.std(observed_array, ddof=1) ** 2 + np.std(simulated_array, ddof=1) ** 2
e = (np.mean(simulated_array) - np.mean(observed_array)) ** 2
f = c + e
return a * np.arcsin(1 - (b / f))
def mb_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute Mielke-Berry R value (MB R).
.. image:: /pictures/MB_R.png
**Range:** 0 ≤ MB R < 1, does not indicate bias, larger is better.
**Notes:** Compares prediction to probability it arose by chance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Mielke-Berry R value.
Notes
-----
If a more optimized version is desired, the `numba package <http://numba.pydata.org/doc.html>`_ can be implemented
for a much more optimized performance when computing this metric. An example is given below.
>>> from numba import njit, prange
>>> @njit(parallel=True, fastmath=True)
>>> def mb_par_fastmath(pred, obs): # uses LLVM compiler
>>> assert pred.size == obs.size
>>> n = pred.size
>>> tot = 0.0
>>> mae = 0.0
>>> for i in range(n):
>>> for j in prange(n):
>>> tot += abs(pred[i] - obs[j])
>>> mae += abs(pred[i] - obs[i])
>>> mae = mae / n
>>> mb = 1 - ((n ** 2) * mae / tot)
>>>
>>> return mb
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mb_r(sim, obs)
0.7726315789473684
References
----------
- Berry, K.J., Mielke, P.W., 1988. A Generalization of Cohen's Kappa Agreement Measure to
Interval Measurement and Multiple Raters. Educational and Psychological Measurement 48(4)
921-933.
- Mielke, P.W., Berry, K.J., 2007. Permutation methods: a distance function approach.
Springer Science & Business Media.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Calculate metric
n = simulated_array.size
tot = 0.0
for i in range(n):
tot = tot + np.sum(np.abs(simulated_array - observed_array[i]))
mae_val = np.sum(np.abs(simulated_array - observed_array)) / n
mb = 1 - ((n ** 2) * mae_val / tot)
return mb
def nse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Nash-Sutcliffe Efficiency.
.. image:: /pictures/NSE.png
**Range:** -inf < NSE < 1, does not indicate bias, larger is better.
**Notes:** The Nash-Sutcliffe efficiency metric compares prediction values to naive predictions
(i.e. average value). One major flaw of this metric is that it punishes a higher variance in
the observed values (denominator). This metric is analogous to the mean absolute error skill
score (MAESS) using the mean flow as a benchmark.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Nash-Sutcliffe Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse(sim, obs)
0.922093023255814
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
- McCuen, R.H., Knight, Z., Cutter, A.G., 2006. Evaluation of the Nash-Sutcliffe Efficiency
Index. Journal of Hydraulic Engineering.
- Nash, J.E., Sutcliffe, J.V., 1970. River flow forecasting through conceptual models part
I — A discussion of principles. Journal of Hydrology 282-290.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** 2
b = (np.abs(observed_array - np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def nse_mod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the modified Nash-Sutcliffe efficiency (NSE mod).
.. image:: /pictures/NSEmod.png
**Range:** -inf < NSE (mod) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
If given, sets the value of j to the input. j is 1 by default. A higher j gives more
emphasis to outliers
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_mod(sim, obs)
0.6949152542372882
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = (np.abs(observed_array - np.mean(observed_array))) ** j
return 1 - (np.sum(a) / np.sum(b))
def nse_rel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the relative Nash-Sutcliffe efficiency (NSE rel).
.. image:: /pictures/NSErel.png
**Range:** -inf < NSE (rel) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_rel(sim, obs)
0.9062004687708474
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs((simulated_array - observed_array) / observed_array)) ** 2
b = (np.abs((observed_array - np.mean(observed_array)) / np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def kge_2009(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""Compute the Kling-Gupta efficiency (2009).
.. image:: /pictures/KGE_2009.png
**Range:** -inf < KGE (2009) < 1, larger is better.
**Notes:** Gupta et al. (2009) created this metric to demonstrate the relative importance of
the three components of the NSE, which are correlation, bias and variability. This was done
with hydrologic modeling as the context. This metric is meant to address issues with the NSE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), Alpha, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, alpha, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2009) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2009(sim, obs)
0.912223072345668
>>> he.kge_2009(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.927910707932087, 1.0058823529411764, 0.9181073779138655)
References
----------
- Gupta, H. V., Kling, H., Yilmaz, K. K., & Martinez, G. F. (2009). Decomposition of the mean
squared error and NSE performance criteria: Implications for improving hydrological modelling.
Journal of Hydrology, 377(1-2), 80-91.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array, ddof=1)
obs_sigma = np.std(observed_array, ddof=1)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
if obs_mean != 0:
beta = sim_mean / obs_mean
else:
beta = np.nan
# Relative variability between simulated and observed values
if obs_sigma != 0:
alpha = sim_sigma / obs_sigma
else:
alpha = np.nan
if not np.isnan(beta) and not np.isnan(alpha):
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (alpha - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Alpha is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, alpha, beta, kge
else:
return kge
def kge_2012(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""
Compute the Kling-Gupta efficiency (2012).
.. image:: /pictures/KGE_2012.png
**Range:** -inf < KGE (2012) < 1, does not indicate bias, larger is better.
**Notes:** The modified version of the KGE (2009). Kling proposed this version to avoid
cross-correlation between bias and variability ratios.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), gamma, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, gamma, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2012) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2012(sim, obs)
0.9122230723456678
>>> he.kge_2012(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.9224843295231272, 1.0058823529411764, 0.9132923608280753)
References
----------
- Kling, H., Fuchs, M., & Paulin, M. (2012). Runoff conditions in the upper Danube basin under
an ensemble of climate change scenarios. Journal of Hydrology, 424, 264-277.
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array)
obs_sigma = np.std(observed_array)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
beta = sim_mean / obs_mean
# CV is the coefficient of variation (standard deviation / mean)
sim_cv = sim_sigma / sim_mean
obs_cv = obs_sigma / obs_mean
# Variability Ratio, or the ratio of simulated CV to observed CV
gam = sim_cv / obs_cv
if obs_mean != 0 and obs_sigma != 0 and sim_mean != 0:
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (gam - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
if sim_mean == 0:
warnings.warn(
'Warning: The simulated data mean is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, gam, beta, kge
else:
return kge
def lm_index(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""
Compute the Legate-McCabe Efficiency Index.
.. image:: /pictures/E1p.png
**Range:** 0 ≤ E1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.lm_index(sim, obs)
0.6949152542372882
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
mean_obs = np.mean(observed_array)
if obs_bar_p is not None:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def d1_p(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""Compute the Legate-McCabe Index of Agreement.
.. image:: /pictures/D1p.png
**Range:** 0 ≤ d1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1_p(sim, obs)
0.8434782608695652
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
if obs_bar_p is not None:
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - obs_bar_p) + np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
mean_obs = np.mean(observed_array)
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - mean_obs) + np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def ve(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Volumetric Efficiency (VE).
.. image:: /pictures/VE.png
**Range:** 0 ≤ VE < 1 smaller is better, does not indicate bias.
**Notes:** Represents the error as a percentage of flow.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Volumetric Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ve(sim, obs)
0.8947368421052632
References
----------
- Criss, R.E., Winston, W.E., 2008. Do Nash values have value? Discussion and alternate
proposals. Hydrological Processes 22(14) 2723.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(observed_array)
return 1 - (a / b)
def sa(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Angle (SA).
.. image:: /pictures/SA.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral angle metric measures the angle between the two vectors in hyperspace.
It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Angle value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sa(sim, obs)
0.10816831366492945
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(simulated_array, observed_array)
b = np.linalg.norm(simulated_array) * np.linalg.norm(observed_array)
return np.arccos(a / b)
def sc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Correlation (SC).
.. image:: /pictures/SC.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral correlation metric measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Correlation value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sc(sim, obs)
0.27991341383646606
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(observed_array - np.mean(observed_array), simulated_array - np.mean(simulated_array))
b = np.linalg.norm(observed_array - np.mean(observed_array))
c = np.linalg.norm(simulated_array - np.mean(simulated_array))
e = b * c
return np.arccos(a / e)
def sid(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Information Divergence (SID).
.. image:: /pictures/SID.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral information divergence measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral information divergence value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sid(sim, obs)
0.03517616895318012
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
first = (observed_array / np.mean(observed_array)) - (
simulated_array / np.mean(simulated_array))
second1 = np.log10(observed_array) - np.log10(np.mean(observed_array))
second2 = np.log10(simulated_array) - np.log10(np.mean(simulated_array))
return np.dot(first, second1 - second2)
def sga(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Gradient Angle (SGA).
.. image:: /pictures/SGA.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral gradient angle measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
SG is the gradient of the simulated or observed time series.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Gradient Angle.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sga(sim, obs)
0.26764286472739834
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sgx = observed_array[1:] - observed_array[:observed_array.size - 1]
sgy = simulated_array[1:] - simulated_array[:simulated_array.size - 1]
a = np.dot(sgx, sgy)
b = np.linalg.norm(sgx) * np.linalg.norm(sgy)
return np.arccos(a / b)
####################################################################################################
# H Metrics: Methods from Tornqvist L, Vartia P, and Vartia YO. (1985) #
####################################################################################################
def h1_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the H1 mean error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mhe(sim, obs)
0.002106551840594386
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(h)
def h1_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H1 absolute error.
.. image:: /pictures/H1.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The H1 absolute error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mahe(sim, obs)
0.11639226612630865
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(np.abs(h))
def h1_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H1 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean squared H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_rmshe(sim, obs)
0.12865571253672756
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.sqrt(np.mean(h ** 2))
def h2_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean error.
.. image:: /pictures/H2.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mhe(sim, obs)
-0.015319829424307036
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(h)
def h2_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean absolute error.
.. image:: /pictures/H2.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mahe(sim, obs)
0.11997591408039167
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(np.abs(h))
def h2_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_rmshe(sim, obs)
0.1373586680669673
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.sqrt(np.mean(h ** 2))
def h3_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 mean error.
.. image:: /pictures/H3.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mhe(sim, obs)
-0.006322019630356533
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(h)
def h3_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H3 mean absolute error.
.. image:: /pictures/H3.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mahe(sim, obs)
0.11743831388794855
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(np.abs(h))
def h3_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 root mean square error.
.. image:: /pictures/H3.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.sqrt(np.mean(h ** 2))
def h4_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mhe(sim, obs)
-0.0064637371129817
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(h)
def h4_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H4 mean absolute error.
.. image:: /pictures/H4.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mahe(sim, obs)
0.11781032209144082
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(np.abs(h))
def h4_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_rmshe(sim, obs)
0.13200901963465006
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.sqrt(np.mean(h ** 2))
def h5_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean error.
.. image:: /pictures/H5.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mhe(sim, obs)
-0.006606638791856322
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(h)
def h5_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean absolute error.
.. image:: /pictures/H5.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mahe(sim, obs)
0.11818409010335018
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(np.abs(h))
def h5_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 root mean square error.
.. image:: /pictures/H5.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_rmshe(sim, obs)
0.13254476469410933
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h6_mhe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H6 mean error.
.. image:: /pictures/H6.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mhe(sim, obs)
-0.006322019630356514
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(h)
def h6_mahe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""Compute the H6 mean absolute error.
.. image:: /pictures/H6.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mahe(sim, obs)
0.11743831388794852
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(np.abs(h))
def h6_rmshe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the H6 root mean square error.
.. image:: /pictures/H6.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h7_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean error.
.. image:: /pictures/H7.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mhe(sim, obs)
0.0026331898007430263
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(h)
def h7_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean absolute error.
.. image:: /pictures/H7.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mahe(sim, obs)
0.14549033265788583
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(np.abs(h))
def h7_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 root mean square error.
.. image:: /pictures/H7.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_rmshe(sim, obs)
0.16081964067090945
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
def h8_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H8 mean error.
.. image:: /pictures/H8.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mhe(sim, obs)
0.0018056158633666466
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(h)
def h8_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 mean absolute error.
.. image:: /pictures/H8.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mahe(sim, obs)
0.099764799536836
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(np.abs(h))
def h8_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 root mean square error.
.. image:: /pictures/H8.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_rmshe(sim, obs)
0.11027632503148076
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
# def h9(simulated_array, observed_array, h_type='mhe', k=1):
# h = (simulated_array / observed_array - 1) / \
# np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
# if h_type == 'mhe':
# return h.mean()
# elif h_type == 'ahe':
# return np.abs(h).mean()
# elif h_type == 'rmshe':
# return np.sqrt((h**2).mean())
# else:
# raise RuntimeError("The three types available are 'mhe', 'ahe', and 'rmshe'.")
def h10_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean error.
.. image:: /pictures/H10.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h10_mhe(sim, obs)
-0.0012578676058971154
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(h)
def h10_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean absolute error.
.. image:: /pictures/H10.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_mahe(sim, obs), 6)
0.094636
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(np.abs(h))
def h10_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 root mean square error.
.. image:: /pictures/H10.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_rmshe(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.sqrt(np.mean(h ** 2))
###################################################################################################
# Statistical Error Metrics for Distribution Testing #
###################################################################################################
def g_mean_diff(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the geometric mean difference.
.. image:: /pictures/GMD.png
**Range:**
**Notes:** For the difference of geometric means, the geometric mean is computed for each of
two samples then their difference is taken.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The geometric mean difference value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.g_mean_diff(sim, obs)
0.988855412098022
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.exp(gmean(sim_log) - gmean(obs_log))
def mean_var(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the mean variance.
.. image:: /pictures/MV.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean variance.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.mean_var(sim, obs), 6)
0.010641
References
----------
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.var(np.log1p(observed_array) - np.log1p(simulated_array))
####################################################################################################
# HELPER FUNCTIONS AND API INFORMATION #
####################################################################################################
metric_names = [
'Mean Error', 'Mean Absolute Error', 'Mean Squared Error', 'Mean Log Error',
'Mean Absolute Log Error', 'Mean Squared Log Error', 'Median Error', 'Median Absolute Error',
'Median Squared Error', 'Eclidean Distance', 'Normalized Eclidean Distance',
'Root Mean Square Error', 'Root Mean Squared Log Error',
'Normalized Root Mean Square Error - Range', 'Normalized Root Mean Square Error - Mean',
'Normalized Root Mean Square Error - IQR', 'Inertial Root Mean Square Error',
'Mean Absolute Scaled Error', 'Coefficient of Determination', 'Pearson Correlation Coefficient',
'Spearman Rank Correlation Coefficient', 'Anomaly Correlation Coefficient',
'Mean Absolute Percentage Error', 'Mean Absolute Percentage Deviation',
'Mean Arctangent Absolute Percentage Error', 'Symmetric Mean Absolute Percentage Error (1)',
'Symmetric Mean Absolute Percentage Error (2)', 'Index of Agreement (d)',
'Index of Agreement (d1)', 'Modified Index of Agreement', 'Relative Index of Agreement',
'Index of Agreement Refined (dr)', "Watterson's M", 'Mielke-Berry R',
'Nash-Sutcliffe Efficiency', 'Modified Nash-Sutcliffe Efficiency',
'Relative Nash-Sutcliffe Efficiency', 'Kling-Gupta Efficiency (2009)',
'Kling-Gupta Efficiency (2012)', 'Legate-McCabe Efficiency Index',
'Legate-McCabe Index of Agreement', 'Volumetric Efficiency', 'Spectral Angle',
'Spectral Correlation', 'Spectral Information Divergence', 'Spectral Gradient Angle',
'Mean H1 Error', 'Mean Absolute H1 Error', 'Root Mean Square H1 Error', 'Mean H2 Error',
'Mean Absolute H2 Error', 'Root Mean Square H2 Error', 'Mean H3 Error',
'Mean Absolute H3 Error', 'Root Mean Square H3 Error', 'Mean H4 Error',
'Mean Absolute H4 Error', 'Root Mean Square H4 Error', 'Mean H5 Error',
'Mean Absolute H5 Error', 'Root Mean Square H5 Error', 'Mean H6 Error',
'Mean Absolute H6 Error', 'Root Mean Square H6 Error', 'Mean H7 Error',
'Mean Absolute H7 Error', 'Root Mean Square H7 Error', 'Mean H8 Error',
'Mean Absolute H8 Error', 'Root Mean Square H8 Error', 'Mean H10 Error',
'Mean Absolute H10 Error', 'Root Mean Square H10 Error', 'Geometric Mean Difference',
'Mean Variance'
]
metric_abbr = [
'ME', 'MAE', 'MSE', 'MLE', 'MALE', 'MSLE', 'MdE', 'MdAE', 'MdSE', 'ED', 'NED', 'RMSE', 'RMSLE',
'NRMSE (Range)', 'NRMSE (Mean)', 'NRMSE (IQR)', 'IRMSE', 'MASE', 'r2', 'R (Pearson)',
'R (Spearman)', 'ACC', 'MAPE', 'MAPD', 'MAAPE', 'SMAPE1', 'SMAPE2', 'd', 'd1', 'd (Mod.)',
'd (Rel.)', 'dr', 'M', '(MB) R', 'NSE', 'NSE (Mod.)', 'NSE (Rel.)', 'KGE (2009)', 'KGE (2012)',
"E1'", "D1'", 'VE', 'SA', 'SC', 'SID', 'SGA', 'H1 (MHE)', 'H1 (MAHE)', 'H1 (RMSHE)', 'H2 (MHE)',
'H2 (MAHE)', 'H2 (RMSHE)', 'H3 (MHE)', 'H3 (MAHE)', 'H3 (RMSHE)', 'H4 (MHE)', 'H4 (MAHE)',
'H4 (RMSHE)', 'H5 (MHE)', 'H5 (MAHE)', 'H5 (RMSHE)', 'H6 (MHE)', 'H6 (MAHE)', 'H6 (RMSHE)',
'H7 (MHE)', 'H7 (MAHE)', 'H7 (RMSHE)', 'H8 (MHE)', 'H8 (MAHE)', 'H8 (RMSHE)', 'H10 (MHE)',
'H10 (MAHE)', 'H10 (RMSHE)', 'GMD', 'MV'
]
function_list = [
me, mae, mse, mle, male, msle, mde, mdae, mdse, ed, ned, rmse, rmsle, nrmse_range, nrmse_mean,
nrmse_iqr, irmse, mase, r_squared, pearson_r, spearman_r, acc, mape, mapd, maape, smape1,
smape2, d, d1, dmod, drel, dr, watt_m, mb_r, nse, nse_mod, nse_rel, kge_2009, kge_2012,
lm_index, d1_p, ve, sa, sc, sid, sga, h1_mhe, h1_mahe, h1_rmshe, h2_mhe, h2_mahe, h2_rmshe,
h3_mhe, h3_mahe, h3_rmshe, h4_mhe, h4_mahe, h4_rmshe, h5_mhe, h5_mahe, h5_rmshe, h6_mhe,
h6_mahe, h6_rmshe, h7_mhe, h7_mahe, h7_rmshe, h8_mhe, h8_mahe, h8_rmshe, h10_mhe, h10_mahe,
h10_rmshe, g_mean_diff, mean_var,
]
# Assign some properties to each function for ease of use for users
for i in range(len(function_list)):
function_list[i].name = metric_names[i]
function_list[i].abbr = metric_abbr[i]
def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Removes the nan, negative, and inf values in two numpy arrays"""
sim_copy = np.copy(simulated_array)
obs_copy = np.copy(observed_array)
# Checking to see if the vectors are the same length
assert sim_copy.ndim == 1, "The simulated array is not one dimensional."
assert obs_copy.ndim == 1, "The observed array is not one dimensional."
if sim_copy.size != obs_copy.size:
raise RuntimeError("The two ndarrays are not the same size.")
# Treat missing data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain nan values
all_treatment_array = np.ones(obs_copy.size, dtype=bool)
if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_nan = np.isnan(sim_copy)
obs_nan = np.isnan(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_nan] = replace_nan
obs_copy[obs_nan] = replace_nan
warnings.warn("Elements(s) {} contained NaN values in the simulated array and "
"elements(s) {} contained NaN values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_nan)[0],
np.where(obs_nan)[0]),
UserWarning)
else:
# Getting the indices of the nan values, combining them, and informing user.
nan_indices_fcst = ~np.isnan(sim_copy)
nan_indices_obs = ~np.isnan(obs_copy)
all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)
warnings.warn("Row(s) {} contained NaN values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_nan_indices)[0]),
UserWarning)
if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_inf = np.isinf(sim_copy)
obs_inf = np.isinf(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_inf] = replace_inf
obs_copy[obs_inf] = replace_inf
warnings.warn("Elements(s) {} contained Inf values in the simulated array and "
"elements(s) {} contained Inf values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_inf)[0],
np.where(obs_inf)[0]),
UserWarning)
else:
inf_indices_fcst = ~(np.isinf(sim_copy))
inf_indices_obs = ~np.isinf(obs_copy)
all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)
warnings.warn(
"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows "
"are zero indexed).".format(np.where(~all_inf_indices)[0]),
UserWarning
)
# Treat zero data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain zero values
if remove_zero:
if (obs_copy == 0).any() or (sim_copy == 0).any():
zero_indices_fcst = ~(sim_copy == 0)
zero_indices_obs = ~(obs_copy == 0)
all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)
warnings.warn(
"Row(s) {} contained zero values and the row(s) have been removed (Rows are "
"zero indexed).".format(np.where(~all_zero_indices)[0]),
UserWarning
)
# Treat negative data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain negative values
# Ignore runtime warnings from comparing
if remove_neg:
with np.errstate(invalid='ignore'):
obs_copy_bool = obs_copy < 0
sim_copy_bool = sim_copy < 0
if obs_copy_bool.any() or sim_copy_bool.any():
neg_indices_fcst = ~sim_copy_bool
neg_indices_obs = ~obs_copy_bool
all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)
warnings.warn("Row(s) {} contained negative values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_neg_indices)[0]),
UserWarning)
obs_copy = obs_copy[all_treatment_array]
sim_copy = sim_copy[all_treatment_array]
return sim_copy, obs_copy
if __name__ == "__main__":
pass
|
BYU-Hydroinformatics/HydroErr | HydroErr/HydroErr.py | mde | python | def mde(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(simulated_array - observed_array) | Compute the median error (MdE) between the simulated and observed data.
.. image:: /pictures/MdE.png
**Range** -inf < MdE < inf, closer to zero is better.
**Notes** This metric indicates bias. It is similar to the mean error (ME), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mde(sim, obs)
-0.10000000000000009
Returns
-------
float
The median error value. | train | https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L511-L582 | [
"def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,\n remove_neg=False, remove_zero=False):\n \"\"\"Removes the nan, negative, and inf values in two numpy arrays\"\"\"\n sim_copy = np.copy(simulated_array)\n obs_copy = np.copy(observed_array)\n\n # Checking to see if the vectors are the same length\n assert sim_copy.ndim == 1, \"The simulated array is not one dimensional.\"\n assert obs_copy.ndim == 1, \"The observed array is not one dimensional.\"\n\n if sim_copy.size != obs_copy.size:\n raise RuntimeError(\"The two ndarrays are not the same size.\")\n\n # Treat missing data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain nan values\n all_treatment_array = np.ones(obs_copy.size, dtype=bool)\n\n if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_nan = np.isnan(sim_copy)\n obs_nan = np.isnan(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_nan] = replace_nan\n obs_copy[obs_nan] = replace_nan\n\n warnings.warn(\"Elements(s) {} contained NaN values in the simulated array and \"\n \"elements(s) {} contained NaN values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_nan)[0],\n np.where(obs_nan)[0]),\n UserWarning)\n else:\n # Getting the indices of the nan values, combining them, and informing user.\n nan_indices_fcst = ~np.isnan(sim_copy)\n nan_indices_obs = ~np.isnan(obs_copy)\n all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)\n\n warnings.warn(\"Row(s) {} contained NaN values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_nan_indices)[0]),\n UserWarning)\n\n if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_inf = np.isinf(sim_copy)\n obs_inf = np.isinf(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_inf] = replace_inf\n obs_copy[obs_inf] = replace_inf\n\n warnings.warn(\"Elements(s) {} contained Inf values in the simulated array and \"\n \"elements(s) {} contained Inf values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_inf)[0],\n np.where(obs_inf)[0]),\n UserWarning)\n else:\n inf_indices_fcst = ~(np.isinf(sim_copy))\n inf_indices_obs = ~np.isinf(obs_copy)\n all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)\n\n warnings.warn(\n \"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows \"\n \"are zero indexed).\".format(np.where(~all_inf_indices)[0]),\n UserWarning\n )\n\n # Treat zero data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain zero values\n if remove_zero:\n if (obs_copy == 0).any() or (sim_copy == 0).any():\n zero_indices_fcst = ~(sim_copy == 0)\n zero_indices_obs = ~(obs_copy == 0)\n all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)\n\n warnings.warn(\n \"Row(s) {} contained zero values and the row(s) have been removed (Rows are \"\n \"zero indexed).\".format(np.where(~all_zero_indices)[0]),\n UserWarning\n )\n\n # Treat negative data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain negative values\n\n # Ignore runtime warnings from comparing\n if remove_neg:\n with np.errstate(invalid='ignore'):\n obs_copy_bool = obs_copy < 0\n sim_copy_bool = sim_copy < 0\n\n if obs_copy_bool.any() or sim_copy_bool.any():\n neg_indices_fcst = ~sim_copy_bool\n neg_indices_obs = ~obs_copy_bool\n all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)\n\n warnings.warn(\"Row(s) {} contained negative values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_neg_indices)[0]),\n UserWarning)\n\n obs_copy = obs_copy[all_treatment_array]\n sim_copy = sim_copy[all_treatment_array]\n\n return sim_copy, obs_copy\n"
] | # -*- coding: utf-8 -*-
"""
HydroErr contains a library of goodness of fit metrics that measure hydrologic skill.
Each metric is contained in function, and every function has the parameters to treat missing values as
well as remove zero and negative values from the timeseries data.
Each function contains two properties, name and abbr. These can be used in the Hydrostats package when creating tables
and adding metrics to the plots. Link to the hydrostats package: https://github.com/BYU-Hydroinformatics/Hydrostats.
An example of this functionality is shown below.
>>> import HydroErr as he
>>>
>>> he.acc.name
'Anomaly Correlation Coefficient'
>>> he.acc.abbr
'ACC'
"""
from __future__ import division
import numpy as np
from scipy.stats import gmean, rankdata
import warnings
__all__ = ['me', 'mae', 'mse', 'mle', 'male', 'msle', 'mde', 'mdae', 'mdse', 'ed', 'ned', 'rmse',
'rmsle', 'nrmse_range', 'nrmse_mean', 'nrmse_iqr', 'irmse', 'mase', 'r_squared',
'pearson_r', 'spearman_r', 'acc', 'mape', 'mapd', 'maape', 'smape1', 'smape2', 'd', 'd1',
'dmod', 'drel', 'dr', 'watt_m', 'mb_r', 'nse', 'nse_mod', 'nse_rel', 'kge_2009',
'kge_2012', 'lm_index', 'd1_p', 've', 'sa', 'sc', 'sid', 'sga', 'h1_mhe', 'h1_mahe',
'h1_rmshe', 'h2_mhe', 'h2_mahe', 'h2_rmshe', 'h3_mhe', 'h3_mahe', 'h3_rmshe', 'h4_mhe',
'h4_mahe', 'h4_rmshe', 'h5_mhe', 'h5_mahe', 'h5_rmshe', 'h6_mhe', 'h6_mahe', 'h6_rmshe',
'h7_mhe', 'h7_mahe', 'h7_rmshe', 'h8_mhe', 'h8_mahe', 'h8_rmshe', 'h10_mhe', 'h10_mahe',
'h10_rmshe', 'g_mean_diff', 'mean_var']
####################################################################################################
# General and Hydrological Error Metrics #
####################################################################################################
def me(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean error of the simulated and observed data.
.. image:: /pictures/ME.png
**Range:** -inf < MAE < inf, data units, closer to zero is better, indicates bias.
**Notes:** The mean error (ME) measures the difference between the simulated data and the
observed data. For the mean error, a smaller number indicates a better fit to the original
data. Note that if the error is in the form of random noise, the mean error will be very small,
which can skew the accuracy of this metric. ME is cumulative and will be small even if there
are large positive and negative errors that balance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean error value.
Examples
--------
Note that in this example the random noise cancels, leaving a very small ME.
>>> import HydroErr as he
>>> import numpy as np
>>> # Seed for reproducibility
>>> np.random.seed(54839)
>>> x = np.arange(100) / 20
>>> sim = np.sin(x) + 2
>>> obs = sim * (((np.random.rand(100) - 0.5) / 10) + 1)
>>> he.me(sim, obs)
-0.006832220968967168
References
----------
- Fisher, R.A., 1920. A Mathematical Examination of the Methods of Determining the Accuracy of
an Observation by the Mean Error, and by the Mean Square Error. Monthly Notices of the Royal
Astronomical Society 80 758 - 770.
"""
# Treating missing values
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero)
return np.mean(simulated_array - observed_array)
def mae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute error of the simulated and observed data.
.. image:: /pictures/MAE.png
**Range:** 0 ≤ MAE < inf, data units, smaller is better.
**Notes:** The ME measures the absolute difference between the simulated data and the observed
data. For the mean abolute error, a smaller number indicates a better fit to the original data.
Also note that random errors do not cancel. Also referred to as an L1-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute error value.
References
----------
- Willmott, Cort J., and Kenji Matsuura. “Advantages of the Mean Absolute Error (MAE) over the
Root Mean Square Error (RMSE) in Assessing Average Model Performance.” Climate Research 30,
no. 1 (2005): 79–82.
- Willmott, Cort J., and Kenji Matsuura. “On the Use of Dimensioned Measures of Error to
Evaluate the Performance of Spatial Interpolators.” International Journal of Geographical
Information Science 20, no. 1 (2006): 89–102.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mae(sim, obs)
0.5666666666666665
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean(np.absolute(simulated_array - observed_array))
def mse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared error of the simulated and observed data.
.. image:: /pictures/MSE.png
**Range:** 0 ≤ MSE < inf, data units squared, smaller is better.
**Notes:** Random errors do not cancel, highlights larger errors, also referred to as a
squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mse(sim, obs)
0.4333333333333333
References
----------
- Wang, Zhou, and Alan C. Bovik. “Mean Squared Error: Love It or Leave It? A New Look at Signal
Fidelity Measures.” IEEE Signal Processing Magazine 26, no. 1 (2009): 98–117.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean((simulated_array - observed_array) ** 2)
def mle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean log error of the simulated and observed data.
.. image:: /pictures/MLE.png
**Range:** -inf < MLE < inf, data units, closer to zero is better.
**Notes** Same as the mean erro (ME) only use log ratios as the error term. Limits the impact of outliers, more
evenly weights high and low data values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mle(sim, obs)
0.002961767058151136
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(sim_log - obs_log)
def male(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean absolute log error of the simulated and observed data.
.. image:: /pictures/MALE.png
**Range:** 0 ≤ MALE < inf, data units squared, smaller is better.
**Notes** Same as MAE only use log ratios as the error term. Limits the impact of outliers,
more evenly weights high and low flows.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.male(sim, obs), 6)
0.090417
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(np.abs(sim_log - obs_log))
def msle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared log error of the simulated and observed data.
.. image:: /pictures/MSLE.png
**Range:** 0 ≤ MSLE < inf, data units squared, smaller is better.
**Notes** Same as the mean squared error (MSE) only use log ratios as the error term. Limits
the impact of outliers, more evenly weights high and low values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.msle(sim, obs), 6)
0.010426
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean((sim_log - obs_log) ** 2)
def mde(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median error (MdE) between the simulated and observed data.
.. image:: /pictures/MdE.png
**Range** -inf < MdE < inf, closer to zero is better.
**Notes** This metric indicates bias. It is similar to the mean error (ME), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mde(sim, obs)
-0.10000000000000009
Returns
-------
float
The median error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(simulated_array - observed_array)
def mdae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median absolute error (MdAE) between the simulated and observed data.
.. image:: /pictures/MdAE.png
**Range** 0 ≤ MdAE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean absolute error (MAE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdae(sim, obs)
0.75
Returns
-------
float
The median absolute error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(np.abs(simulated_array - observed_array))
def mdse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median squared error (MdSE) between the simulated and observed data.
.. image:: /pictures/MdSE.png
**Range** 0 ≤ MdSE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean squared error (MSE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdse(sim, obs)
0.625
Returns
-------
float
The median squared error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median((simulated_array - observed_array) ** 2)
def ed(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Euclidean distance between predicted and observed values in vector space.
.. image:: /pictures/ED.png
**Range** 0 ≤ ED < inf, smaller is better.
**Notes** Also sometimes referred to as the L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ed(sim, obs)
1.63707055437449
Returns
-------
float
The euclidean distance error value.
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.linalg.norm(observed_array - simulated_array)
def ned(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the normalized Euclidian distance between the simulated and observed data in vector
space.
.. image:: /pictures/NED.png
**Range** 0 ≤ NED < inf, smaller is better.
**Notes** Also sometimes referred to as the squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The normalized euclidean distance value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ned(sim, obs)
0.2872053604165771
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array / np.mean(observed_array)
b = simulated_array / np.mean(simulated_array)
return np.linalg.norm(a - b)
def rmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square error between the simulated and observed data.
.. image:: /pictures/RMSE.png
**Range** 0 ≤ RMSE < inf, smaller is better.
**Notes:** The standard deviation of the residuals. A lower spread indicates that the points
are better concentrated around the line of best fit (linear). Random errors do not cancel.
This metric will highlights larger errors.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.rmse(sim, obs)
0.668331255192114
References
----------
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.sqrt(np.mean((simulated_array - observed_array) ** 2))
def rmsle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square log error between the simulated and observed data.
.. image:: /pictures/RMSLE.png
**Range:** 0 ≤ RMSLE < inf. Smaller is better, and it does not indicate bias.
**Notes:** Random errors do not cancel while using this metric. This metric limits the
impact of outliers by more evenly weighting high and low values. To calculate the log values,
each value in the observed and simulated array is increased by one unit in order to avoid
run-time errors and nan values (function np.log1p).
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square log error value.
Examples
--------
Notice that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.rmsle(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
"""
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf, remove_neg=remove_neg,
remove_zero=remove_zero)
return np.sqrt(np.mean(np.power(np.log1p(simulated_array) - np.log1p(observed_array), 2)))
def nrmse_range(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the range normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Range.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the range of the observed time series (x).
Normalizing allows comparison between data sets with different scales. The NRMSErange is the
most sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The range normalized root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_range(sim, obs)
0.0891108340256152
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_max = np.max(observed_array)
obs_min = np.min(observed_array)
return rmse_value / (obs_max - obs_min)
def nrmse_mean(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Mean.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the mean of the observed time series (x).
Normalizing allows comparison between data sets with different scales.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_mean(sim, obs)
0.11725109740212526
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_mean = np.mean(observed_array)
return rmse_value / obs_mean
def nrmse_iqr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the IQR normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_IQR.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the interquartile range of the observed time
series (x). Normalizing allows comparison between data sets with different scales.
The NRMSEquartile is the least sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The IQR normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_iqr(sim, obs)
0.2595461185212093
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
q1 = np.percentile(observed_array, 25)
q3 = np.percentile(observed_array, 75)
iqr = q3 - q1
return rmse_value / iqr
def irmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the inertial root mean square error (IRMSE) between the simulated and observed data.
.. image:: /pictures/IRMSE.png
**Range:** 0 ≤ IRMSE < inf, lower is better.
**Notes:** This metric is the RMSE devided by by the standard deviation of the gradient of the
observed timeseries data. This metric is meant to be help understand the ability of the model
to predict changes in observation.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The inertial root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.irmse(sim, obs)
0.14572738134831856
References
----------
- Daga, M., Deo, M.C., 2009. Alternative data-driven methods to estimate wind from waves by
inverse modeling. Natural Hazards 49(2) 293-310.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Getting the gradient of the observed data
obs_len = observed_array.size
obs_grad = observed_array[1:obs_len] - observed_array[0:obs_len - 1]
# Standard deviation of the gradient
obs_grad_std = np.std(obs_grad, ddof=1)
# Divide RMSE by the standard deviation of the gradient of the observed data
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
return rmse_value / obs_grad_std
def mase(simulated_array, observed_array, m=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute scaled error between the simulated and observed data.
.. image:: /pictures/MASE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
m: int
If given, indicates the seasonal period m. If not given, the default is 1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute scaled error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mase(sim, obs)
0.17341040462427745
References
----------
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
start = m
end = simulated_array.size - m
a = np.mean(np.abs(simulated_array - observed_array))
b = np.abs(observed_array[start:observed_array.size] - observed_array[:end])
return a / (np.sum(b) / end)
def pearson_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the pearson correlation coefficient.
.. image:: /pictures/R_pearson.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The pearson r coefficient measures linear correlation. It is sensitive to outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Pearson correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.pearson_r(sim, obs)
0.9610793632835262
References
----------
- Pearson, K. (1895). Note on regression and inheritance in the case of two parents.
Proceedings of the Royal Society of London, 58, 240-242.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
top = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1 = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2 = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
return top / (bot1 * bot2)
def spearman_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the spearman rank correlation coefficient.
.. image:: /pictures/R_spearman.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The spearman r coefficient measures the monotonic relation between simulated and
observed data. Because it uses a nonparametric measure of rank correlation, it is less sensitive
to outliers compared to the Pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spearman rank correlation coefficient.
Examples
----------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.spearman_r(sim, obs)
0.942857142857143
References
----------
- Spearman C (1904). "The proof and measurement of association between two things". American
Journal of Psychology. 15: 72–101. doi:10.2307/1412159
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rank_sim = rankdata(simulated_array)
rank_obs = rankdata(observed_array)
mean_rank_sim = np.mean(rank_sim)
mean_rank_obs = np.mean(rank_obs)
top = np.mean((rank_obs - mean_rank_obs) * (rank_sim - mean_rank_sim))
bot = np.sqrt(
np.mean((rank_obs - mean_rank_obs) ** 2) * np.mean((rank_sim - mean_rank_sim) ** 2))
return top / bot
def r_squared(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Coefficient of Determination (r2).
.. image:: /pictures/r2.png
**Range:** 0 ≤ r2 ≤ 1. 1 indicates perfect correlation, 0 indicates complete randomness.
**Notes:** The Coefficient of Determination measures the linear relation between simulated and
observed data. Because it is the pearson correlation coefficient squared, it is more heavily
affected by outliers than the pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The coefficient of determination (R^2).
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.r_squared(sim, obs)
0.9236735425294681
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array - np.mean(observed_array)
b = simulated_array - np.mean(simulated_array)
return (np.sum(a * b)) ** 2 / (np.sum(a ** 2) * np.sum(b ** 2))
def acc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the anomaly correlation coefficient (ACC).
.. image:: /pictures/ACC.png
**Range:** -1 ≤ ACC ≤ 1. -1 indicates perfect negative correlation of the variation
pattern of the anomalies, 0 indicates complete randomness of the variation patterns of the
anomalies, 1 indicates perfect correlation of the variation pattern of the anomalies.
**Notes:** Common measure in the verification of spatial fields. Measures the correlation
between the variation pattern of the simulated data compared to the observed data.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The anomaly correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.acc(sim, obs)
0.8008994694029383
References
----------
- Langland, Rolf H., and Ryan N. Maue. “Recent Northern Hemisphere Mid-Latitude Medium-Range
Deterministic Forecast Skill.” Tellus A: Dynamic Meteorology and Oceanography 64,
no. 1 (2012): 17531.
- Miyakoda, K., G. D. Hembree, R. F. Strickler, and I. Shulman. “Cumulative Results of Extended
Forecast Experiments I. Model Performance for Winter Cases.” Monthly Weather Review 100, no.
12(1972): 836–55.
- Murphy, Allan H., and Edward S. Epstein. “Skill Scores and Correlation Coefficients in Model
Verification.” Monthly Weather Review 117, no. 3 (1989): 572–82.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - np.mean(simulated_array)
b = observed_array - np.mean(observed_array)
c = np.std(observed_array, ddof=1) * np.std(simulated_array, ddof=1) * simulated_array.size
return np.dot(a, b / c)
def mape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the mean absolute percentage error (MAPE).
.. image:: /pictures/MAPE.png
**Range:** 0% ≤ MAPE ≤ inf. 0% indicates perfect correlation, a larger error indicates a
larger percent error in the data.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
c = 100 / simulated_array.size
return c * np.sum(b)
def mapd(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the mean absolute percentage deviation (MAPD).
.. image:: /pictures/MAPD.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage deviation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mapd(sim, obs)
0.10526315789473682
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(np.abs(observed_array))
return a / b
def maape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the Mean Arctangent Absolute Percentage Error (MAAPE).
.. image:: /pictures/MAAPE.png
**Range:** 0 ≤ MAAPE < π/2, does not indicate bias, smaller is better.
**Notes:** Represents the mean absolute error as a percentage of the observed values. Handles
0s in the observed data. This metric is not as biased as MAPE by under-over predictions.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean arctangent absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
- Kim, S., Kim, H., 2016. A new metric of absolute percentage error for intermittent demand
forecasts. International Journal of Forecasting 32(3) 669-679.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
return np.mean(np.arctan(b))
def smape1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (1) (SMAPE1).
.. image:: /pictures/SMAPE1.png
**Range:** 0 ≤ SMAPE1 < 100%, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (1).
Examples
--------
Note that if we switch the simulated and observed arrays the result is the same
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape1(sim, obs)
5.871915694397428
>>> he.smape1(obs, sim)
5.871915694397428
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 100 / simulated_array.size
b = np.abs(simulated_array - observed_array)
c = np.abs(simulated_array) + np.abs(observed_array)
return a * np.sum(b / c)
def smape2(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (2) (SMAPE2).
.. image:: /pictures/SMAPE2.png
**Range:** 0 ≤ SMAPE1 < 200%, does not indicate bias, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE with only positive metric values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (2).
Examples
--------
Note that switching the simulated and observed arrays yields the same results
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape2(sim, obs)
11.743831388794856
>>> he.smape2(obs, sim)
11.743831388794856
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = (simulated_array + observed_array) / 2
c = 100 / simulated_array.size
return c * np.sum(np.abs(a / b))
def d(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d).
.. image:: /pictures/d.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d(sim, obs)
0.978477353035657
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (observed_array - simulated_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
return 1 - (np.sum(a) / np.sum((b + c) ** 2))
def d1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d1).
.. image:: /pictures/d1.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric. Compared
to the other index of agreement (d) it has a reduced impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (d1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1(sim, obs)
0.8434782608695652
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
obs_mean = np.mean(observed_array)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.abs(simulated_array - obs_mean)
c = np.abs(observed_array - obs_mean)
return 1 - np.sum(a) / np.sum(b + c)
def dr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the refined index of agreement (dr).
.. image:: /pictures/dr.png
**Range:** -1 ≤ dr < 1, does not indicate bias, larger is better.
**Notes:** Reformulation of Willmott’s index of agreement. This metric was created to address
issues in the index of agreement and the Nash-Sutcliffe efficiency metric. Meant to be a
flexible metric for use in climatology.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The refined index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dr(sim, obs)
0.847457627118644
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = 2 * np.sum(np.abs(observed_array - observed_array.mean()))
if a <= b:
return 1 - (a / b)
else:
return (b / a) - 1
def drel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the relative index of agreement (drel).
.. image:: /pictures/drel.png
**Range:** 0 ≤ drel < 1, does not indicate bias, larger is better.
**Notes:** Instead of absolute differences, this metric uses relative differences.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.drel(sim, obs)
0.9740868625579597
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = ((simulated_array - observed_array) / observed_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = ((b + c) / np.mean(observed_array)) ** 2
return 1 - (np.sum(a) / np.sum(e))
def dmod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the modified index of agreement (dmod).
.. image:: /pictures/dmod.png
**Range:** 0 ≤ dmod < 1, does not indicate bias, larger is better.
**Notes:** When j=1, this metric is the same as d1. As j becomes larger, outliers have a larger
impact on the value.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
Optional input indicating the j values desired. A higher j places more emphasis on
outliers. j is 1 by default.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified index of agreement.
Examples
--------
Note that using the default is the same as calculating the d1 metric. Changing the value of j
modification of the metric.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dmod(sim, obs) # Same as d1
0.8434782608695652
>>> he.dmod(sim, obs, j=1.5)
0.9413310986805733
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = (b + c) ** j
return 1 - (np.sum(a) / np.sum(e))
def watt_m(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute Watterson's M (M).
.. image:: /pictures/M.png
**Range:** -1 ≤ M < 1, does not indicate bias, larger is better.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
Watterson's M value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.watt_m(sim, obs)
0.8307913876595929
References
----------
- Watterson, I.G., 1996. Non‐dimensional measures of climate model performance. International
Journal of Climatology 16(4) 379-391.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 2 / np.pi
b = np.mean((simulated_array - observed_array) ** 2) # MSE
c = np.std(observed_array, ddof=1) ** 2 + np.std(simulated_array, ddof=1) ** 2
e = (np.mean(simulated_array) - np.mean(observed_array)) ** 2
f = c + e
return a * np.arcsin(1 - (b / f))
def mb_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute Mielke-Berry R value (MB R).
.. image:: /pictures/MB_R.png
**Range:** 0 ≤ MB R < 1, does not indicate bias, larger is better.
**Notes:** Compares prediction to probability it arose by chance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Mielke-Berry R value.
Notes
-----
If a more optimized version is desired, the `numba package <http://numba.pydata.org/doc.html>`_ can be implemented
for a much more optimized performance when computing this metric. An example is given below.
>>> from numba import njit, prange
>>> @njit(parallel=True, fastmath=True)
>>> def mb_par_fastmath(pred, obs): # uses LLVM compiler
>>> assert pred.size == obs.size
>>> n = pred.size
>>> tot = 0.0
>>> mae = 0.0
>>> for i in range(n):
>>> for j in prange(n):
>>> tot += abs(pred[i] - obs[j])
>>> mae += abs(pred[i] - obs[i])
>>> mae = mae / n
>>> mb = 1 - ((n ** 2) * mae / tot)
>>>
>>> return mb
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mb_r(sim, obs)
0.7726315789473684
References
----------
- Berry, K.J., Mielke, P.W., 1988. A Generalization of Cohen's Kappa Agreement Measure to
Interval Measurement and Multiple Raters. Educational and Psychological Measurement 48(4)
921-933.
- Mielke, P.W., Berry, K.J., 2007. Permutation methods: a distance function approach.
Springer Science & Business Media.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Calculate metric
n = simulated_array.size
tot = 0.0
for i in range(n):
tot = tot + np.sum(np.abs(simulated_array - observed_array[i]))
mae_val = np.sum(np.abs(simulated_array - observed_array)) / n
mb = 1 - ((n ** 2) * mae_val / tot)
return mb
def nse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Nash-Sutcliffe Efficiency.
.. image:: /pictures/NSE.png
**Range:** -inf < NSE < 1, does not indicate bias, larger is better.
**Notes:** The Nash-Sutcliffe efficiency metric compares prediction values to naive predictions
(i.e. average value). One major flaw of this metric is that it punishes a higher variance in
the observed values (denominator). This metric is analogous to the mean absolute error skill
score (MAESS) using the mean flow as a benchmark.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Nash-Sutcliffe Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse(sim, obs)
0.922093023255814
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
- McCuen, R.H., Knight, Z., Cutter, A.G., 2006. Evaluation of the Nash-Sutcliffe Efficiency
Index. Journal of Hydraulic Engineering.
- Nash, J.E., Sutcliffe, J.V., 1970. River flow forecasting through conceptual models part
I — A discussion of principles. Journal of Hydrology 282-290.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** 2
b = (np.abs(observed_array - np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def nse_mod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the modified Nash-Sutcliffe efficiency (NSE mod).
.. image:: /pictures/NSEmod.png
**Range:** -inf < NSE (mod) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
If given, sets the value of j to the input. j is 1 by default. A higher j gives more
emphasis to outliers
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_mod(sim, obs)
0.6949152542372882
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = (np.abs(observed_array - np.mean(observed_array))) ** j
return 1 - (np.sum(a) / np.sum(b))
def nse_rel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the relative Nash-Sutcliffe efficiency (NSE rel).
.. image:: /pictures/NSErel.png
**Range:** -inf < NSE (rel) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_rel(sim, obs)
0.9062004687708474
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs((simulated_array - observed_array) / observed_array)) ** 2
b = (np.abs((observed_array - np.mean(observed_array)) / np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def kge_2009(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""Compute the Kling-Gupta efficiency (2009).
.. image:: /pictures/KGE_2009.png
**Range:** -inf < KGE (2009) < 1, larger is better.
**Notes:** Gupta et al. (2009) created this metric to demonstrate the relative importance of
the three components of the NSE, which are correlation, bias and variability. This was done
with hydrologic modeling as the context. This metric is meant to address issues with the NSE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), Alpha, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, alpha, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2009) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2009(sim, obs)
0.912223072345668
>>> he.kge_2009(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.927910707932087, 1.0058823529411764, 0.9181073779138655)
References
----------
- Gupta, H. V., Kling, H., Yilmaz, K. K., & Martinez, G. F. (2009). Decomposition of the mean
squared error and NSE performance criteria: Implications for improving hydrological modelling.
Journal of Hydrology, 377(1-2), 80-91.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array, ddof=1)
obs_sigma = np.std(observed_array, ddof=1)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
if obs_mean != 0:
beta = sim_mean / obs_mean
else:
beta = np.nan
# Relative variability between simulated and observed values
if obs_sigma != 0:
alpha = sim_sigma / obs_sigma
else:
alpha = np.nan
if not np.isnan(beta) and not np.isnan(alpha):
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (alpha - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Alpha is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, alpha, beta, kge
else:
return kge
def kge_2012(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""
Compute the Kling-Gupta efficiency (2012).
.. image:: /pictures/KGE_2012.png
**Range:** -inf < KGE (2012) < 1, does not indicate bias, larger is better.
**Notes:** The modified version of the KGE (2009). Kling proposed this version to avoid
cross-correlation between bias and variability ratios.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), gamma, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, gamma, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2012) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2012(sim, obs)
0.9122230723456678
>>> he.kge_2012(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.9224843295231272, 1.0058823529411764, 0.9132923608280753)
References
----------
- Kling, H., Fuchs, M., & Paulin, M. (2012). Runoff conditions in the upper Danube basin under
an ensemble of climate change scenarios. Journal of Hydrology, 424, 264-277.
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array)
obs_sigma = np.std(observed_array)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
beta = sim_mean / obs_mean
# CV is the coefficient of variation (standard deviation / mean)
sim_cv = sim_sigma / sim_mean
obs_cv = obs_sigma / obs_mean
# Variability Ratio, or the ratio of simulated CV to observed CV
gam = sim_cv / obs_cv
if obs_mean != 0 and obs_sigma != 0 and sim_mean != 0:
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (gam - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
if sim_mean == 0:
warnings.warn(
'Warning: The simulated data mean is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, gam, beta, kge
else:
return kge
def lm_index(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""
Compute the Legate-McCabe Efficiency Index.
.. image:: /pictures/E1p.png
**Range:** 0 ≤ E1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.lm_index(sim, obs)
0.6949152542372882
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
mean_obs = np.mean(observed_array)
if obs_bar_p is not None:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def d1_p(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""Compute the Legate-McCabe Index of Agreement.
.. image:: /pictures/D1p.png
**Range:** 0 ≤ d1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1_p(sim, obs)
0.8434782608695652
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
if obs_bar_p is not None:
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - obs_bar_p) + np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
mean_obs = np.mean(observed_array)
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - mean_obs) + np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def ve(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Volumetric Efficiency (VE).
.. image:: /pictures/VE.png
**Range:** 0 ≤ VE < 1 smaller is better, does not indicate bias.
**Notes:** Represents the error as a percentage of flow.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Volumetric Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ve(sim, obs)
0.8947368421052632
References
----------
- Criss, R.E., Winston, W.E., 2008. Do Nash values have value? Discussion and alternate
proposals. Hydrological Processes 22(14) 2723.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(observed_array)
return 1 - (a / b)
def sa(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Angle (SA).
.. image:: /pictures/SA.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral angle metric measures the angle between the two vectors in hyperspace.
It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Angle value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sa(sim, obs)
0.10816831366492945
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(simulated_array, observed_array)
b = np.linalg.norm(simulated_array) * np.linalg.norm(observed_array)
return np.arccos(a / b)
def sc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Correlation (SC).
.. image:: /pictures/SC.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral correlation metric measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Correlation value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sc(sim, obs)
0.27991341383646606
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(observed_array - np.mean(observed_array), simulated_array - np.mean(simulated_array))
b = np.linalg.norm(observed_array - np.mean(observed_array))
c = np.linalg.norm(simulated_array - np.mean(simulated_array))
e = b * c
return np.arccos(a / e)
def sid(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Information Divergence (SID).
.. image:: /pictures/SID.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral information divergence measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral information divergence value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sid(sim, obs)
0.03517616895318012
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
first = (observed_array / np.mean(observed_array)) - (
simulated_array / np.mean(simulated_array))
second1 = np.log10(observed_array) - np.log10(np.mean(observed_array))
second2 = np.log10(simulated_array) - np.log10(np.mean(simulated_array))
return np.dot(first, second1 - second2)
def sga(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Gradient Angle (SGA).
.. image:: /pictures/SGA.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral gradient angle measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
SG is the gradient of the simulated or observed time series.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Gradient Angle.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sga(sim, obs)
0.26764286472739834
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sgx = observed_array[1:] - observed_array[:observed_array.size - 1]
sgy = simulated_array[1:] - simulated_array[:simulated_array.size - 1]
a = np.dot(sgx, sgy)
b = np.linalg.norm(sgx) * np.linalg.norm(sgy)
return np.arccos(a / b)
####################################################################################################
# H Metrics: Methods from Tornqvist L, Vartia P, and Vartia YO. (1985) #
####################################################################################################
def h1_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the H1 mean error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mhe(sim, obs)
0.002106551840594386
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(h)
def h1_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H1 absolute error.
.. image:: /pictures/H1.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The H1 absolute error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mahe(sim, obs)
0.11639226612630865
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(np.abs(h))
def h1_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H1 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean squared H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_rmshe(sim, obs)
0.12865571253672756
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.sqrt(np.mean(h ** 2))
def h2_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean error.
.. image:: /pictures/H2.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mhe(sim, obs)
-0.015319829424307036
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(h)
def h2_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean absolute error.
.. image:: /pictures/H2.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mahe(sim, obs)
0.11997591408039167
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(np.abs(h))
def h2_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_rmshe(sim, obs)
0.1373586680669673
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.sqrt(np.mean(h ** 2))
def h3_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 mean error.
.. image:: /pictures/H3.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mhe(sim, obs)
-0.006322019630356533
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(h)
def h3_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H3 mean absolute error.
.. image:: /pictures/H3.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mahe(sim, obs)
0.11743831388794855
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(np.abs(h))
def h3_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 root mean square error.
.. image:: /pictures/H3.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.sqrt(np.mean(h ** 2))
def h4_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mhe(sim, obs)
-0.0064637371129817
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(h)
def h4_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H4 mean absolute error.
.. image:: /pictures/H4.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mahe(sim, obs)
0.11781032209144082
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(np.abs(h))
def h4_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_rmshe(sim, obs)
0.13200901963465006
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.sqrt(np.mean(h ** 2))
def h5_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean error.
.. image:: /pictures/H5.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mhe(sim, obs)
-0.006606638791856322
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(h)
def h5_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean absolute error.
.. image:: /pictures/H5.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mahe(sim, obs)
0.11818409010335018
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(np.abs(h))
def h5_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 root mean square error.
.. image:: /pictures/H5.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_rmshe(sim, obs)
0.13254476469410933
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h6_mhe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H6 mean error.
.. image:: /pictures/H6.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mhe(sim, obs)
-0.006322019630356514
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(h)
def h6_mahe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""Compute the H6 mean absolute error.
.. image:: /pictures/H6.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mahe(sim, obs)
0.11743831388794852
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(np.abs(h))
def h6_rmshe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the H6 root mean square error.
.. image:: /pictures/H6.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h7_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean error.
.. image:: /pictures/H7.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mhe(sim, obs)
0.0026331898007430263
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(h)
def h7_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean absolute error.
.. image:: /pictures/H7.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mahe(sim, obs)
0.14549033265788583
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(np.abs(h))
def h7_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 root mean square error.
.. image:: /pictures/H7.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_rmshe(sim, obs)
0.16081964067090945
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
def h8_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H8 mean error.
.. image:: /pictures/H8.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mhe(sim, obs)
0.0018056158633666466
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(h)
def h8_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 mean absolute error.
.. image:: /pictures/H8.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mahe(sim, obs)
0.099764799536836
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(np.abs(h))
def h8_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 root mean square error.
.. image:: /pictures/H8.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_rmshe(sim, obs)
0.11027632503148076
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
# def h9(simulated_array, observed_array, h_type='mhe', k=1):
# h = (simulated_array / observed_array - 1) / \
# np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
# if h_type == 'mhe':
# return h.mean()
# elif h_type == 'ahe':
# return np.abs(h).mean()
# elif h_type == 'rmshe':
# return np.sqrt((h**2).mean())
# else:
# raise RuntimeError("The three types available are 'mhe', 'ahe', and 'rmshe'.")
def h10_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean error.
.. image:: /pictures/H10.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h10_mhe(sim, obs)
-0.0012578676058971154
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(h)
def h10_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean absolute error.
.. image:: /pictures/H10.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_mahe(sim, obs), 6)
0.094636
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(np.abs(h))
def h10_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 root mean square error.
.. image:: /pictures/H10.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_rmshe(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.sqrt(np.mean(h ** 2))
###################################################################################################
# Statistical Error Metrics for Distribution Testing #
###################################################################################################
def g_mean_diff(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the geometric mean difference.
.. image:: /pictures/GMD.png
**Range:**
**Notes:** For the difference of geometric means, the geometric mean is computed for each of
two samples then their difference is taken.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The geometric mean difference value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.g_mean_diff(sim, obs)
0.988855412098022
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.exp(gmean(sim_log) - gmean(obs_log))
def mean_var(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the mean variance.
.. image:: /pictures/MV.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean variance.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.mean_var(sim, obs), 6)
0.010641
References
----------
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.var(np.log1p(observed_array) - np.log1p(simulated_array))
####################################################################################################
# HELPER FUNCTIONS AND API INFORMATION #
####################################################################################################
metric_names = [
'Mean Error', 'Mean Absolute Error', 'Mean Squared Error', 'Mean Log Error',
'Mean Absolute Log Error', 'Mean Squared Log Error', 'Median Error', 'Median Absolute Error',
'Median Squared Error', 'Eclidean Distance', 'Normalized Eclidean Distance',
'Root Mean Square Error', 'Root Mean Squared Log Error',
'Normalized Root Mean Square Error - Range', 'Normalized Root Mean Square Error - Mean',
'Normalized Root Mean Square Error - IQR', 'Inertial Root Mean Square Error',
'Mean Absolute Scaled Error', 'Coefficient of Determination', 'Pearson Correlation Coefficient',
'Spearman Rank Correlation Coefficient', 'Anomaly Correlation Coefficient',
'Mean Absolute Percentage Error', 'Mean Absolute Percentage Deviation',
'Mean Arctangent Absolute Percentage Error', 'Symmetric Mean Absolute Percentage Error (1)',
'Symmetric Mean Absolute Percentage Error (2)', 'Index of Agreement (d)',
'Index of Agreement (d1)', 'Modified Index of Agreement', 'Relative Index of Agreement',
'Index of Agreement Refined (dr)', "Watterson's M", 'Mielke-Berry R',
'Nash-Sutcliffe Efficiency', 'Modified Nash-Sutcliffe Efficiency',
'Relative Nash-Sutcliffe Efficiency', 'Kling-Gupta Efficiency (2009)',
'Kling-Gupta Efficiency (2012)', 'Legate-McCabe Efficiency Index',
'Legate-McCabe Index of Agreement', 'Volumetric Efficiency', 'Spectral Angle',
'Spectral Correlation', 'Spectral Information Divergence', 'Spectral Gradient Angle',
'Mean H1 Error', 'Mean Absolute H1 Error', 'Root Mean Square H1 Error', 'Mean H2 Error',
'Mean Absolute H2 Error', 'Root Mean Square H2 Error', 'Mean H3 Error',
'Mean Absolute H3 Error', 'Root Mean Square H3 Error', 'Mean H4 Error',
'Mean Absolute H4 Error', 'Root Mean Square H4 Error', 'Mean H5 Error',
'Mean Absolute H5 Error', 'Root Mean Square H5 Error', 'Mean H6 Error',
'Mean Absolute H6 Error', 'Root Mean Square H6 Error', 'Mean H7 Error',
'Mean Absolute H7 Error', 'Root Mean Square H7 Error', 'Mean H8 Error',
'Mean Absolute H8 Error', 'Root Mean Square H8 Error', 'Mean H10 Error',
'Mean Absolute H10 Error', 'Root Mean Square H10 Error', 'Geometric Mean Difference',
'Mean Variance'
]
metric_abbr = [
'ME', 'MAE', 'MSE', 'MLE', 'MALE', 'MSLE', 'MdE', 'MdAE', 'MdSE', 'ED', 'NED', 'RMSE', 'RMSLE',
'NRMSE (Range)', 'NRMSE (Mean)', 'NRMSE (IQR)', 'IRMSE', 'MASE', 'r2', 'R (Pearson)',
'R (Spearman)', 'ACC', 'MAPE', 'MAPD', 'MAAPE', 'SMAPE1', 'SMAPE2', 'd', 'd1', 'd (Mod.)',
'd (Rel.)', 'dr', 'M', '(MB) R', 'NSE', 'NSE (Mod.)', 'NSE (Rel.)', 'KGE (2009)', 'KGE (2012)',
"E1'", "D1'", 'VE', 'SA', 'SC', 'SID', 'SGA', 'H1 (MHE)', 'H1 (MAHE)', 'H1 (RMSHE)', 'H2 (MHE)',
'H2 (MAHE)', 'H2 (RMSHE)', 'H3 (MHE)', 'H3 (MAHE)', 'H3 (RMSHE)', 'H4 (MHE)', 'H4 (MAHE)',
'H4 (RMSHE)', 'H5 (MHE)', 'H5 (MAHE)', 'H5 (RMSHE)', 'H6 (MHE)', 'H6 (MAHE)', 'H6 (RMSHE)',
'H7 (MHE)', 'H7 (MAHE)', 'H7 (RMSHE)', 'H8 (MHE)', 'H8 (MAHE)', 'H8 (RMSHE)', 'H10 (MHE)',
'H10 (MAHE)', 'H10 (RMSHE)', 'GMD', 'MV'
]
function_list = [
me, mae, mse, mle, male, msle, mde, mdae, mdse, ed, ned, rmse, rmsle, nrmse_range, nrmse_mean,
nrmse_iqr, irmse, mase, r_squared, pearson_r, spearman_r, acc, mape, mapd, maape, smape1,
smape2, d, d1, dmod, drel, dr, watt_m, mb_r, nse, nse_mod, nse_rel, kge_2009, kge_2012,
lm_index, d1_p, ve, sa, sc, sid, sga, h1_mhe, h1_mahe, h1_rmshe, h2_mhe, h2_mahe, h2_rmshe,
h3_mhe, h3_mahe, h3_rmshe, h4_mhe, h4_mahe, h4_rmshe, h5_mhe, h5_mahe, h5_rmshe, h6_mhe,
h6_mahe, h6_rmshe, h7_mhe, h7_mahe, h7_rmshe, h8_mhe, h8_mahe, h8_rmshe, h10_mhe, h10_mahe,
h10_rmshe, g_mean_diff, mean_var,
]
# Assign some properties to each function for ease of use for users
for i in range(len(function_list)):
function_list[i].name = metric_names[i]
function_list[i].abbr = metric_abbr[i]
def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Removes the nan, negative, and inf values in two numpy arrays"""
sim_copy = np.copy(simulated_array)
obs_copy = np.copy(observed_array)
# Checking to see if the vectors are the same length
assert sim_copy.ndim == 1, "The simulated array is not one dimensional."
assert obs_copy.ndim == 1, "The observed array is not one dimensional."
if sim_copy.size != obs_copy.size:
raise RuntimeError("The two ndarrays are not the same size.")
# Treat missing data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain nan values
all_treatment_array = np.ones(obs_copy.size, dtype=bool)
if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_nan = np.isnan(sim_copy)
obs_nan = np.isnan(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_nan] = replace_nan
obs_copy[obs_nan] = replace_nan
warnings.warn("Elements(s) {} contained NaN values in the simulated array and "
"elements(s) {} contained NaN values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_nan)[0],
np.where(obs_nan)[0]),
UserWarning)
else:
# Getting the indices of the nan values, combining them, and informing user.
nan_indices_fcst = ~np.isnan(sim_copy)
nan_indices_obs = ~np.isnan(obs_copy)
all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)
warnings.warn("Row(s) {} contained NaN values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_nan_indices)[0]),
UserWarning)
if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_inf = np.isinf(sim_copy)
obs_inf = np.isinf(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_inf] = replace_inf
obs_copy[obs_inf] = replace_inf
warnings.warn("Elements(s) {} contained Inf values in the simulated array and "
"elements(s) {} contained Inf values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_inf)[0],
np.where(obs_inf)[0]),
UserWarning)
else:
inf_indices_fcst = ~(np.isinf(sim_copy))
inf_indices_obs = ~np.isinf(obs_copy)
all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)
warnings.warn(
"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows "
"are zero indexed).".format(np.where(~all_inf_indices)[0]),
UserWarning
)
# Treat zero data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain zero values
if remove_zero:
if (obs_copy == 0).any() or (sim_copy == 0).any():
zero_indices_fcst = ~(sim_copy == 0)
zero_indices_obs = ~(obs_copy == 0)
all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)
warnings.warn(
"Row(s) {} contained zero values and the row(s) have been removed (Rows are "
"zero indexed).".format(np.where(~all_zero_indices)[0]),
UserWarning
)
# Treat negative data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain negative values
# Ignore runtime warnings from comparing
if remove_neg:
with np.errstate(invalid='ignore'):
obs_copy_bool = obs_copy < 0
sim_copy_bool = sim_copy < 0
if obs_copy_bool.any() or sim_copy_bool.any():
neg_indices_fcst = ~sim_copy_bool
neg_indices_obs = ~obs_copy_bool
all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)
warnings.warn("Row(s) {} contained negative values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_neg_indices)[0]),
UserWarning)
obs_copy = obs_copy[all_treatment_array]
sim_copy = sim_copy[all_treatment_array]
return sim_copy, obs_copy
if __name__ == "__main__":
pass
|
BYU-Hydroinformatics/HydroErr | HydroErr/HydroErr.py | mdae | python | def mdae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(np.abs(simulated_array - observed_array)) | Compute the median absolute error (MdAE) between the simulated and observed data.
.. image:: /pictures/MdAE.png
**Range** 0 ≤ MdAE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean absolute error (MAE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdae(sim, obs)
0.75
Returns
-------
float
The median absolute error value. | train | https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L585-L656 | [
"def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,\n remove_neg=False, remove_zero=False):\n \"\"\"Removes the nan, negative, and inf values in two numpy arrays\"\"\"\n sim_copy = np.copy(simulated_array)\n obs_copy = np.copy(observed_array)\n\n # Checking to see if the vectors are the same length\n assert sim_copy.ndim == 1, \"The simulated array is not one dimensional.\"\n assert obs_copy.ndim == 1, \"The observed array is not one dimensional.\"\n\n if sim_copy.size != obs_copy.size:\n raise RuntimeError(\"The two ndarrays are not the same size.\")\n\n # Treat missing data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain nan values\n all_treatment_array = np.ones(obs_copy.size, dtype=bool)\n\n if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_nan = np.isnan(sim_copy)\n obs_nan = np.isnan(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_nan] = replace_nan\n obs_copy[obs_nan] = replace_nan\n\n warnings.warn(\"Elements(s) {} contained NaN values in the simulated array and \"\n \"elements(s) {} contained NaN values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_nan)[0],\n np.where(obs_nan)[0]),\n UserWarning)\n else:\n # Getting the indices of the nan values, combining them, and informing user.\n nan_indices_fcst = ~np.isnan(sim_copy)\n nan_indices_obs = ~np.isnan(obs_copy)\n all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)\n\n warnings.warn(\"Row(s) {} contained NaN values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_nan_indices)[0]),\n UserWarning)\n\n if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_inf = np.isinf(sim_copy)\n obs_inf = np.isinf(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_inf] = replace_inf\n obs_copy[obs_inf] = replace_inf\n\n warnings.warn(\"Elements(s) {} contained Inf values in the simulated array and \"\n \"elements(s) {} contained Inf values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_inf)[0],\n np.where(obs_inf)[0]),\n UserWarning)\n else:\n inf_indices_fcst = ~(np.isinf(sim_copy))\n inf_indices_obs = ~np.isinf(obs_copy)\n all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)\n\n warnings.warn(\n \"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows \"\n \"are zero indexed).\".format(np.where(~all_inf_indices)[0]),\n UserWarning\n )\n\n # Treat zero data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain zero values\n if remove_zero:\n if (obs_copy == 0).any() or (sim_copy == 0).any():\n zero_indices_fcst = ~(sim_copy == 0)\n zero_indices_obs = ~(obs_copy == 0)\n all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)\n\n warnings.warn(\n \"Row(s) {} contained zero values and the row(s) have been removed (Rows are \"\n \"zero indexed).\".format(np.where(~all_zero_indices)[0]),\n UserWarning\n )\n\n # Treat negative data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain negative values\n\n # Ignore runtime warnings from comparing\n if remove_neg:\n with np.errstate(invalid='ignore'):\n obs_copy_bool = obs_copy < 0\n sim_copy_bool = sim_copy < 0\n\n if obs_copy_bool.any() or sim_copy_bool.any():\n neg_indices_fcst = ~sim_copy_bool\n neg_indices_obs = ~obs_copy_bool\n all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)\n\n warnings.warn(\"Row(s) {} contained negative values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_neg_indices)[0]),\n UserWarning)\n\n obs_copy = obs_copy[all_treatment_array]\n sim_copy = sim_copy[all_treatment_array]\n\n return sim_copy, obs_copy\n"
] | # -*- coding: utf-8 -*-
"""
HydroErr contains a library of goodness of fit metrics that measure hydrologic skill.
Each metric is contained in function, and every function has the parameters to treat missing values as
well as remove zero and negative values from the timeseries data.
Each function contains two properties, name and abbr. These can be used in the Hydrostats package when creating tables
and adding metrics to the plots. Link to the hydrostats package: https://github.com/BYU-Hydroinformatics/Hydrostats.
An example of this functionality is shown below.
>>> import HydroErr as he
>>>
>>> he.acc.name
'Anomaly Correlation Coefficient'
>>> he.acc.abbr
'ACC'
"""
from __future__ import division
import numpy as np
from scipy.stats import gmean, rankdata
import warnings
__all__ = ['me', 'mae', 'mse', 'mle', 'male', 'msle', 'mde', 'mdae', 'mdse', 'ed', 'ned', 'rmse',
'rmsle', 'nrmse_range', 'nrmse_mean', 'nrmse_iqr', 'irmse', 'mase', 'r_squared',
'pearson_r', 'spearman_r', 'acc', 'mape', 'mapd', 'maape', 'smape1', 'smape2', 'd', 'd1',
'dmod', 'drel', 'dr', 'watt_m', 'mb_r', 'nse', 'nse_mod', 'nse_rel', 'kge_2009',
'kge_2012', 'lm_index', 'd1_p', 've', 'sa', 'sc', 'sid', 'sga', 'h1_mhe', 'h1_mahe',
'h1_rmshe', 'h2_mhe', 'h2_mahe', 'h2_rmshe', 'h3_mhe', 'h3_mahe', 'h3_rmshe', 'h4_mhe',
'h4_mahe', 'h4_rmshe', 'h5_mhe', 'h5_mahe', 'h5_rmshe', 'h6_mhe', 'h6_mahe', 'h6_rmshe',
'h7_mhe', 'h7_mahe', 'h7_rmshe', 'h8_mhe', 'h8_mahe', 'h8_rmshe', 'h10_mhe', 'h10_mahe',
'h10_rmshe', 'g_mean_diff', 'mean_var']
####################################################################################################
# General and Hydrological Error Metrics #
####################################################################################################
def me(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean error of the simulated and observed data.
.. image:: /pictures/ME.png
**Range:** -inf < MAE < inf, data units, closer to zero is better, indicates bias.
**Notes:** The mean error (ME) measures the difference between the simulated data and the
observed data. For the mean error, a smaller number indicates a better fit to the original
data. Note that if the error is in the form of random noise, the mean error will be very small,
which can skew the accuracy of this metric. ME is cumulative and will be small even if there
are large positive and negative errors that balance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean error value.
Examples
--------
Note that in this example the random noise cancels, leaving a very small ME.
>>> import HydroErr as he
>>> import numpy as np
>>> # Seed for reproducibility
>>> np.random.seed(54839)
>>> x = np.arange(100) / 20
>>> sim = np.sin(x) + 2
>>> obs = sim * (((np.random.rand(100) - 0.5) / 10) + 1)
>>> he.me(sim, obs)
-0.006832220968967168
References
----------
- Fisher, R.A., 1920. A Mathematical Examination of the Methods of Determining the Accuracy of
an Observation by the Mean Error, and by the Mean Square Error. Monthly Notices of the Royal
Astronomical Society 80 758 - 770.
"""
# Treating missing values
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero)
return np.mean(simulated_array - observed_array)
def mae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute error of the simulated and observed data.
.. image:: /pictures/MAE.png
**Range:** 0 ≤ MAE < inf, data units, smaller is better.
**Notes:** The ME measures the absolute difference between the simulated data and the observed
data. For the mean abolute error, a smaller number indicates a better fit to the original data.
Also note that random errors do not cancel. Also referred to as an L1-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute error value.
References
----------
- Willmott, Cort J., and Kenji Matsuura. “Advantages of the Mean Absolute Error (MAE) over the
Root Mean Square Error (RMSE) in Assessing Average Model Performance.” Climate Research 30,
no. 1 (2005): 79–82.
- Willmott, Cort J., and Kenji Matsuura. “On the Use of Dimensioned Measures of Error to
Evaluate the Performance of Spatial Interpolators.” International Journal of Geographical
Information Science 20, no. 1 (2006): 89–102.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mae(sim, obs)
0.5666666666666665
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean(np.absolute(simulated_array - observed_array))
def mse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared error of the simulated and observed data.
.. image:: /pictures/MSE.png
**Range:** 0 ≤ MSE < inf, data units squared, smaller is better.
**Notes:** Random errors do not cancel, highlights larger errors, also referred to as a
squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mse(sim, obs)
0.4333333333333333
References
----------
- Wang, Zhou, and Alan C. Bovik. “Mean Squared Error: Love It or Leave It? A New Look at Signal
Fidelity Measures.” IEEE Signal Processing Magazine 26, no. 1 (2009): 98–117.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean((simulated_array - observed_array) ** 2)
def mle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean log error of the simulated and observed data.
.. image:: /pictures/MLE.png
**Range:** -inf < MLE < inf, data units, closer to zero is better.
**Notes** Same as the mean erro (ME) only use log ratios as the error term. Limits the impact of outliers, more
evenly weights high and low data values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mle(sim, obs)
0.002961767058151136
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(sim_log - obs_log)
def male(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean absolute log error of the simulated and observed data.
.. image:: /pictures/MALE.png
**Range:** 0 ≤ MALE < inf, data units squared, smaller is better.
**Notes** Same as MAE only use log ratios as the error term. Limits the impact of outliers,
more evenly weights high and low flows.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.male(sim, obs), 6)
0.090417
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(np.abs(sim_log - obs_log))
def msle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared log error of the simulated and observed data.
.. image:: /pictures/MSLE.png
**Range:** 0 ≤ MSLE < inf, data units squared, smaller is better.
**Notes** Same as the mean squared error (MSE) only use log ratios as the error term. Limits
the impact of outliers, more evenly weights high and low values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.msle(sim, obs), 6)
0.010426
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean((sim_log - obs_log) ** 2)
def mde(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median error (MdE) between the simulated and observed data.
.. image:: /pictures/MdE.png
**Range** -inf < MdE < inf, closer to zero is better.
**Notes** This metric indicates bias. It is similar to the mean error (ME), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mde(sim, obs)
-0.10000000000000009
Returns
-------
float
The median error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(simulated_array - observed_array)
def mdae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median absolute error (MdAE) between the simulated and observed data.
.. image:: /pictures/MdAE.png
**Range** 0 ≤ MdAE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean absolute error (MAE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdae(sim, obs)
0.75
Returns
-------
float
The median absolute error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(np.abs(simulated_array - observed_array))
def mdse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median squared error (MdSE) between the simulated and observed data.
.. image:: /pictures/MdSE.png
**Range** 0 ≤ MdSE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean squared error (MSE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdse(sim, obs)
0.625
Returns
-------
float
The median squared error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median((simulated_array - observed_array) ** 2)
def ed(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Euclidean distance between predicted and observed values in vector space.
.. image:: /pictures/ED.png
**Range** 0 ≤ ED < inf, smaller is better.
**Notes** Also sometimes referred to as the L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ed(sim, obs)
1.63707055437449
Returns
-------
float
The euclidean distance error value.
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.linalg.norm(observed_array - simulated_array)
def ned(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the normalized Euclidian distance between the simulated and observed data in vector
space.
.. image:: /pictures/NED.png
**Range** 0 ≤ NED < inf, smaller is better.
**Notes** Also sometimes referred to as the squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The normalized euclidean distance value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ned(sim, obs)
0.2872053604165771
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array / np.mean(observed_array)
b = simulated_array / np.mean(simulated_array)
return np.linalg.norm(a - b)
def rmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square error between the simulated and observed data.
.. image:: /pictures/RMSE.png
**Range** 0 ≤ RMSE < inf, smaller is better.
**Notes:** The standard deviation of the residuals. A lower spread indicates that the points
are better concentrated around the line of best fit (linear). Random errors do not cancel.
This metric will highlights larger errors.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.rmse(sim, obs)
0.668331255192114
References
----------
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.sqrt(np.mean((simulated_array - observed_array) ** 2))
def rmsle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square log error between the simulated and observed data.
.. image:: /pictures/RMSLE.png
**Range:** 0 ≤ RMSLE < inf. Smaller is better, and it does not indicate bias.
**Notes:** Random errors do not cancel while using this metric. This metric limits the
impact of outliers by more evenly weighting high and low values. To calculate the log values,
each value in the observed and simulated array is increased by one unit in order to avoid
run-time errors and nan values (function np.log1p).
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square log error value.
Examples
--------
Notice that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.rmsle(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
"""
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf, remove_neg=remove_neg,
remove_zero=remove_zero)
return np.sqrt(np.mean(np.power(np.log1p(simulated_array) - np.log1p(observed_array), 2)))
def nrmse_range(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the range normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Range.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the range of the observed time series (x).
Normalizing allows comparison between data sets with different scales. The NRMSErange is the
most sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The range normalized root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_range(sim, obs)
0.0891108340256152
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_max = np.max(observed_array)
obs_min = np.min(observed_array)
return rmse_value / (obs_max - obs_min)
def nrmse_mean(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Mean.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the mean of the observed time series (x).
Normalizing allows comparison between data sets with different scales.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_mean(sim, obs)
0.11725109740212526
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_mean = np.mean(observed_array)
return rmse_value / obs_mean
def nrmse_iqr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the IQR normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_IQR.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the interquartile range of the observed time
series (x). Normalizing allows comparison between data sets with different scales.
The NRMSEquartile is the least sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The IQR normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_iqr(sim, obs)
0.2595461185212093
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
q1 = np.percentile(observed_array, 25)
q3 = np.percentile(observed_array, 75)
iqr = q3 - q1
return rmse_value / iqr
def irmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the inertial root mean square error (IRMSE) between the simulated and observed data.
.. image:: /pictures/IRMSE.png
**Range:** 0 ≤ IRMSE < inf, lower is better.
**Notes:** This metric is the RMSE devided by by the standard deviation of the gradient of the
observed timeseries data. This metric is meant to be help understand the ability of the model
to predict changes in observation.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The inertial root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.irmse(sim, obs)
0.14572738134831856
References
----------
- Daga, M., Deo, M.C., 2009. Alternative data-driven methods to estimate wind from waves by
inverse modeling. Natural Hazards 49(2) 293-310.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Getting the gradient of the observed data
obs_len = observed_array.size
obs_grad = observed_array[1:obs_len] - observed_array[0:obs_len - 1]
# Standard deviation of the gradient
obs_grad_std = np.std(obs_grad, ddof=1)
# Divide RMSE by the standard deviation of the gradient of the observed data
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
return rmse_value / obs_grad_std
def mase(simulated_array, observed_array, m=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute scaled error between the simulated and observed data.
.. image:: /pictures/MASE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
m: int
If given, indicates the seasonal period m. If not given, the default is 1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute scaled error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mase(sim, obs)
0.17341040462427745
References
----------
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
start = m
end = simulated_array.size - m
a = np.mean(np.abs(simulated_array - observed_array))
b = np.abs(observed_array[start:observed_array.size] - observed_array[:end])
return a / (np.sum(b) / end)
def pearson_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the pearson correlation coefficient.
.. image:: /pictures/R_pearson.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The pearson r coefficient measures linear correlation. It is sensitive to outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Pearson correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.pearson_r(sim, obs)
0.9610793632835262
References
----------
- Pearson, K. (1895). Note on regression and inheritance in the case of two parents.
Proceedings of the Royal Society of London, 58, 240-242.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
top = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1 = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2 = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
return top / (bot1 * bot2)
def spearman_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the spearman rank correlation coefficient.
.. image:: /pictures/R_spearman.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The spearman r coefficient measures the monotonic relation between simulated and
observed data. Because it uses a nonparametric measure of rank correlation, it is less sensitive
to outliers compared to the Pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spearman rank correlation coefficient.
Examples
----------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.spearman_r(sim, obs)
0.942857142857143
References
----------
- Spearman C (1904). "The proof and measurement of association between two things". American
Journal of Psychology. 15: 72–101. doi:10.2307/1412159
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rank_sim = rankdata(simulated_array)
rank_obs = rankdata(observed_array)
mean_rank_sim = np.mean(rank_sim)
mean_rank_obs = np.mean(rank_obs)
top = np.mean((rank_obs - mean_rank_obs) * (rank_sim - mean_rank_sim))
bot = np.sqrt(
np.mean((rank_obs - mean_rank_obs) ** 2) * np.mean((rank_sim - mean_rank_sim) ** 2))
return top / bot
def r_squared(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Coefficient of Determination (r2).
.. image:: /pictures/r2.png
**Range:** 0 ≤ r2 ≤ 1. 1 indicates perfect correlation, 0 indicates complete randomness.
**Notes:** The Coefficient of Determination measures the linear relation between simulated and
observed data. Because it is the pearson correlation coefficient squared, it is more heavily
affected by outliers than the pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The coefficient of determination (R^2).
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.r_squared(sim, obs)
0.9236735425294681
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array - np.mean(observed_array)
b = simulated_array - np.mean(simulated_array)
return (np.sum(a * b)) ** 2 / (np.sum(a ** 2) * np.sum(b ** 2))
def acc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the anomaly correlation coefficient (ACC).
.. image:: /pictures/ACC.png
**Range:** -1 ≤ ACC ≤ 1. -1 indicates perfect negative correlation of the variation
pattern of the anomalies, 0 indicates complete randomness of the variation patterns of the
anomalies, 1 indicates perfect correlation of the variation pattern of the anomalies.
**Notes:** Common measure in the verification of spatial fields. Measures the correlation
between the variation pattern of the simulated data compared to the observed data.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The anomaly correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.acc(sim, obs)
0.8008994694029383
References
----------
- Langland, Rolf H., and Ryan N. Maue. “Recent Northern Hemisphere Mid-Latitude Medium-Range
Deterministic Forecast Skill.” Tellus A: Dynamic Meteorology and Oceanography 64,
no. 1 (2012): 17531.
- Miyakoda, K., G. D. Hembree, R. F. Strickler, and I. Shulman. “Cumulative Results of Extended
Forecast Experiments I. Model Performance for Winter Cases.” Monthly Weather Review 100, no.
12(1972): 836–55.
- Murphy, Allan H., and Edward S. Epstein. “Skill Scores and Correlation Coefficients in Model
Verification.” Monthly Weather Review 117, no. 3 (1989): 572–82.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - np.mean(simulated_array)
b = observed_array - np.mean(observed_array)
c = np.std(observed_array, ddof=1) * np.std(simulated_array, ddof=1) * simulated_array.size
return np.dot(a, b / c)
def mape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the mean absolute percentage error (MAPE).
.. image:: /pictures/MAPE.png
**Range:** 0% ≤ MAPE ≤ inf. 0% indicates perfect correlation, a larger error indicates a
larger percent error in the data.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
c = 100 / simulated_array.size
return c * np.sum(b)
def mapd(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the mean absolute percentage deviation (MAPD).
.. image:: /pictures/MAPD.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage deviation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mapd(sim, obs)
0.10526315789473682
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(np.abs(observed_array))
return a / b
def maape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the Mean Arctangent Absolute Percentage Error (MAAPE).
.. image:: /pictures/MAAPE.png
**Range:** 0 ≤ MAAPE < π/2, does not indicate bias, smaller is better.
**Notes:** Represents the mean absolute error as a percentage of the observed values. Handles
0s in the observed data. This metric is not as biased as MAPE by under-over predictions.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean arctangent absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
- Kim, S., Kim, H., 2016. A new metric of absolute percentage error for intermittent demand
forecasts. International Journal of Forecasting 32(3) 669-679.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
return np.mean(np.arctan(b))
def smape1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (1) (SMAPE1).
.. image:: /pictures/SMAPE1.png
**Range:** 0 ≤ SMAPE1 < 100%, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (1).
Examples
--------
Note that if we switch the simulated and observed arrays the result is the same
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape1(sim, obs)
5.871915694397428
>>> he.smape1(obs, sim)
5.871915694397428
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 100 / simulated_array.size
b = np.abs(simulated_array - observed_array)
c = np.abs(simulated_array) + np.abs(observed_array)
return a * np.sum(b / c)
def smape2(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (2) (SMAPE2).
.. image:: /pictures/SMAPE2.png
**Range:** 0 ≤ SMAPE1 < 200%, does not indicate bias, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE with only positive metric values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (2).
Examples
--------
Note that switching the simulated and observed arrays yields the same results
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape2(sim, obs)
11.743831388794856
>>> he.smape2(obs, sim)
11.743831388794856
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = (simulated_array + observed_array) / 2
c = 100 / simulated_array.size
return c * np.sum(np.abs(a / b))
def d(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d).
.. image:: /pictures/d.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d(sim, obs)
0.978477353035657
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (observed_array - simulated_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
return 1 - (np.sum(a) / np.sum((b + c) ** 2))
def d1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d1).
.. image:: /pictures/d1.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric. Compared
to the other index of agreement (d) it has a reduced impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (d1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1(sim, obs)
0.8434782608695652
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
obs_mean = np.mean(observed_array)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.abs(simulated_array - obs_mean)
c = np.abs(observed_array - obs_mean)
return 1 - np.sum(a) / np.sum(b + c)
def dr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the refined index of agreement (dr).
.. image:: /pictures/dr.png
**Range:** -1 ≤ dr < 1, does not indicate bias, larger is better.
**Notes:** Reformulation of Willmott’s index of agreement. This metric was created to address
issues in the index of agreement and the Nash-Sutcliffe efficiency metric. Meant to be a
flexible metric for use in climatology.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The refined index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dr(sim, obs)
0.847457627118644
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = 2 * np.sum(np.abs(observed_array - observed_array.mean()))
if a <= b:
return 1 - (a / b)
else:
return (b / a) - 1
def drel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the relative index of agreement (drel).
.. image:: /pictures/drel.png
**Range:** 0 ≤ drel < 1, does not indicate bias, larger is better.
**Notes:** Instead of absolute differences, this metric uses relative differences.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.drel(sim, obs)
0.9740868625579597
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = ((simulated_array - observed_array) / observed_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = ((b + c) / np.mean(observed_array)) ** 2
return 1 - (np.sum(a) / np.sum(e))
def dmod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the modified index of agreement (dmod).
.. image:: /pictures/dmod.png
**Range:** 0 ≤ dmod < 1, does not indicate bias, larger is better.
**Notes:** When j=1, this metric is the same as d1. As j becomes larger, outliers have a larger
impact on the value.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
Optional input indicating the j values desired. A higher j places more emphasis on
outliers. j is 1 by default.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified index of agreement.
Examples
--------
Note that using the default is the same as calculating the d1 metric. Changing the value of j
modification of the metric.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dmod(sim, obs) # Same as d1
0.8434782608695652
>>> he.dmod(sim, obs, j=1.5)
0.9413310986805733
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = (b + c) ** j
return 1 - (np.sum(a) / np.sum(e))
def watt_m(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute Watterson's M (M).
.. image:: /pictures/M.png
**Range:** -1 ≤ M < 1, does not indicate bias, larger is better.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
Watterson's M value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.watt_m(sim, obs)
0.8307913876595929
References
----------
- Watterson, I.G., 1996. Non‐dimensional measures of climate model performance. International
Journal of Climatology 16(4) 379-391.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 2 / np.pi
b = np.mean((simulated_array - observed_array) ** 2) # MSE
c = np.std(observed_array, ddof=1) ** 2 + np.std(simulated_array, ddof=1) ** 2
e = (np.mean(simulated_array) - np.mean(observed_array)) ** 2
f = c + e
return a * np.arcsin(1 - (b / f))
def mb_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute Mielke-Berry R value (MB R).
.. image:: /pictures/MB_R.png
**Range:** 0 ≤ MB R < 1, does not indicate bias, larger is better.
**Notes:** Compares prediction to probability it arose by chance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Mielke-Berry R value.
Notes
-----
If a more optimized version is desired, the `numba package <http://numba.pydata.org/doc.html>`_ can be implemented
for a much more optimized performance when computing this metric. An example is given below.
>>> from numba import njit, prange
>>> @njit(parallel=True, fastmath=True)
>>> def mb_par_fastmath(pred, obs): # uses LLVM compiler
>>> assert pred.size == obs.size
>>> n = pred.size
>>> tot = 0.0
>>> mae = 0.0
>>> for i in range(n):
>>> for j in prange(n):
>>> tot += abs(pred[i] - obs[j])
>>> mae += abs(pred[i] - obs[i])
>>> mae = mae / n
>>> mb = 1 - ((n ** 2) * mae / tot)
>>>
>>> return mb
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mb_r(sim, obs)
0.7726315789473684
References
----------
- Berry, K.J., Mielke, P.W., 1988. A Generalization of Cohen's Kappa Agreement Measure to
Interval Measurement and Multiple Raters. Educational and Psychological Measurement 48(4)
921-933.
- Mielke, P.W., Berry, K.J., 2007. Permutation methods: a distance function approach.
Springer Science & Business Media.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Calculate metric
n = simulated_array.size
tot = 0.0
for i in range(n):
tot = tot + np.sum(np.abs(simulated_array - observed_array[i]))
mae_val = np.sum(np.abs(simulated_array - observed_array)) / n
mb = 1 - ((n ** 2) * mae_val / tot)
return mb
def nse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Nash-Sutcliffe Efficiency.
.. image:: /pictures/NSE.png
**Range:** -inf < NSE < 1, does not indicate bias, larger is better.
**Notes:** The Nash-Sutcliffe efficiency metric compares prediction values to naive predictions
(i.e. average value). One major flaw of this metric is that it punishes a higher variance in
the observed values (denominator). This metric is analogous to the mean absolute error skill
score (MAESS) using the mean flow as a benchmark.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Nash-Sutcliffe Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse(sim, obs)
0.922093023255814
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
- McCuen, R.H., Knight, Z., Cutter, A.G., 2006. Evaluation of the Nash-Sutcliffe Efficiency
Index. Journal of Hydraulic Engineering.
- Nash, J.E., Sutcliffe, J.V., 1970. River flow forecasting through conceptual models part
I — A discussion of principles. Journal of Hydrology 282-290.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** 2
b = (np.abs(observed_array - np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def nse_mod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the modified Nash-Sutcliffe efficiency (NSE mod).
.. image:: /pictures/NSEmod.png
**Range:** -inf < NSE (mod) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
If given, sets the value of j to the input. j is 1 by default. A higher j gives more
emphasis to outliers
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_mod(sim, obs)
0.6949152542372882
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = (np.abs(observed_array - np.mean(observed_array))) ** j
return 1 - (np.sum(a) / np.sum(b))
def nse_rel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the relative Nash-Sutcliffe efficiency (NSE rel).
.. image:: /pictures/NSErel.png
**Range:** -inf < NSE (rel) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_rel(sim, obs)
0.9062004687708474
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs((simulated_array - observed_array) / observed_array)) ** 2
b = (np.abs((observed_array - np.mean(observed_array)) / np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def kge_2009(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""Compute the Kling-Gupta efficiency (2009).
.. image:: /pictures/KGE_2009.png
**Range:** -inf < KGE (2009) < 1, larger is better.
**Notes:** Gupta et al. (2009) created this metric to demonstrate the relative importance of
the three components of the NSE, which are correlation, bias and variability. This was done
with hydrologic modeling as the context. This metric is meant to address issues with the NSE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), Alpha, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, alpha, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2009) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2009(sim, obs)
0.912223072345668
>>> he.kge_2009(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.927910707932087, 1.0058823529411764, 0.9181073779138655)
References
----------
- Gupta, H. V., Kling, H., Yilmaz, K. K., & Martinez, G. F. (2009). Decomposition of the mean
squared error and NSE performance criteria: Implications for improving hydrological modelling.
Journal of Hydrology, 377(1-2), 80-91.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array, ddof=1)
obs_sigma = np.std(observed_array, ddof=1)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
if obs_mean != 0:
beta = sim_mean / obs_mean
else:
beta = np.nan
# Relative variability between simulated and observed values
if obs_sigma != 0:
alpha = sim_sigma / obs_sigma
else:
alpha = np.nan
if not np.isnan(beta) and not np.isnan(alpha):
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (alpha - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Alpha is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, alpha, beta, kge
else:
return kge
def kge_2012(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""
Compute the Kling-Gupta efficiency (2012).
.. image:: /pictures/KGE_2012.png
**Range:** -inf < KGE (2012) < 1, does not indicate bias, larger is better.
**Notes:** The modified version of the KGE (2009). Kling proposed this version to avoid
cross-correlation between bias and variability ratios.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), gamma, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, gamma, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2012) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2012(sim, obs)
0.9122230723456678
>>> he.kge_2012(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.9224843295231272, 1.0058823529411764, 0.9132923608280753)
References
----------
- Kling, H., Fuchs, M., & Paulin, M. (2012). Runoff conditions in the upper Danube basin under
an ensemble of climate change scenarios. Journal of Hydrology, 424, 264-277.
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array)
obs_sigma = np.std(observed_array)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
beta = sim_mean / obs_mean
# CV is the coefficient of variation (standard deviation / mean)
sim_cv = sim_sigma / sim_mean
obs_cv = obs_sigma / obs_mean
# Variability Ratio, or the ratio of simulated CV to observed CV
gam = sim_cv / obs_cv
if obs_mean != 0 and obs_sigma != 0 and sim_mean != 0:
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (gam - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
if sim_mean == 0:
warnings.warn(
'Warning: The simulated data mean is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, gam, beta, kge
else:
return kge
def lm_index(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""
Compute the Legate-McCabe Efficiency Index.
.. image:: /pictures/E1p.png
**Range:** 0 ≤ E1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.lm_index(sim, obs)
0.6949152542372882
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
mean_obs = np.mean(observed_array)
if obs_bar_p is not None:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def d1_p(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""Compute the Legate-McCabe Index of Agreement.
.. image:: /pictures/D1p.png
**Range:** 0 ≤ d1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1_p(sim, obs)
0.8434782608695652
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
if obs_bar_p is not None:
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - obs_bar_p) + np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
mean_obs = np.mean(observed_array)
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - mean_obs) + np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def ve(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Volumetric Efficiency (VE).
.. image:: /pictures/VE.png
**Range:** 0 ≤ VE < 1 smaller is better, does not indicate bias.
**Notes:** Represents the error as a percentage of flow.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Volumetric Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ve(sim, obs)
0.8947368421052632
References
----------
- Criss, R.E., Winston, W.E., 2008. Do Nash values have value? Discussion and alternate
proposals. Hydrological Processes 22(14) 2723.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(observed_array)
return 1 - (a / b)
def sa(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Angle (SA).
.. image:: /pictures/SA.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral angle metric measures the angle between the two vectors in hyperspace.
It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Angle value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sa(sim, obs)
0.10816831366492945
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(simulated_array, observed_array)
b = np.linalg.norm(simulated_array) * np.linalg.norm(observed_array)
return np.arccos(a / b)
def sc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Correlation (SC).
.. image:: /pictures/SC.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral correlation metric measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Correlation value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sc(sim, obs)
0.27991341383646606
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(observed_array - np.mean(observed_array), simulated_array - np.mean(simulated_array))
b = np.linalg.norm(observed_array - np.mean(observed_array))
c = np.linalg.norm(simulated_array - np.mean(simulated_array))
e = b * c
return np.arccos(a / e)
def sid(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Information Divergence (SID).
.. image:: /pictures/SID.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral information divergence measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral information divergence value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sid(sim, obs)
0.03517616895318012
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
first = (observed_array / np.mean(observed_array)) - (
simulated_array / np.mean(simulated_array))
second1 = np.log10(observed_array) - np.log10(np.mean(observed_array))
second2 = np.log10(simulated_array) - np.log10(np.mean(simulated_array))
return np.dot(first, second1 - second2)
def sga(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Gradient Angle (SGA).
.. image:: /pictures/SGA.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral gradient angle measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
SG is the gradient of the simulated or observed time series.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Gradient Angle.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sga(sim, obs)
0.26764286472739834
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sgx = observed_array[1:] - observed_array[:observed_array.size - 1]
sgy = simulated_array[1:] - simulated_array[:simulated_array.size - 1]
a = np.dot(sgx, sgy)
b = np.linalg.norm(sgx) * np.linalg.norm(sgy)
return np.arccos(a / b)
####################################################################################################
# H Metrics: Methods from Tornqvist L, Vartia P, and Vartia YO. (1985) #
####################################################################################################
def h1_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the H1 mean error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mhe(sim, obs)
0.002106551840594386
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(h)
def h1_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H1 absolute error.
.. image:: /pictures/H1.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The H1 absolute error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mahe(sim, obs)
0.11639226612630865
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(np.abs(h))
def h1_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H1 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean squared H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_rmshe(sim, obs)
0.12865571253672756
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.sqrt(np.mean(h ** 2))
def h2_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean error.
.. image:: /pictures/H2.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mhe(sim, obs)
-0.015319829424307036
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(h)
def h2_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean absolute error.
.. image:: /pictures/H2.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mahe(sim, obs)
0.11997591408039167
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(np.abs(h))
def h2_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_rmshe(sim, obs)
0.1373586680669673
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.sqrt(np.mean(h ** 2))
def h3_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 mean error.
.. image:: /pictures/H3.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mhe(sim, obs)
-0.006322019630356533
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(h)
def h3_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H3 mean absolute error.
.. image:: /pictures/H3.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mahe(sim, obs)
0.11743831388794855
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(np.abs(h))
def h3_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 root mean square error.
.. image:: /pictures/H3.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.sqrt(np.mean(h ** 2))
def h4_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mhe(sim, obs)
-0.0064637371129817
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(h)
def h4_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H4 mean absolute error.
.. image:: /pictures/H4.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mahe(sim, obs)
0.11781032209144082
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(np.abs(h))
def h4_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_rmshe(sim, obs)
0.13200901963465006
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.sqrt(np.mean(h ** 2))
def h5_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean error.
.. image:: /pictures/H5.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mhe(sim, obs)
-0.006606638791856322
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(h)
def h5_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean absolute error.
.. image:: /pictures/H5.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mahe(sim, obs)
0.11818409010335018
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(np.abs(h))
def h5_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 root mean square error.
.. image:: /pictures/H5.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_rmshe(sim, obs)
0.13254476469410933
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h6_mhe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H6 mean error.
.. image:: /pictures/H6.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mhe(sim, obs)
-0.006322019630356514
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(h)
def h6_mahe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""Compute the H6 mean absolute error.
.. image:: /pictures/H6.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mahe(sim, obs)
0.11743831388794852
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(np.abs(h))
def h6_rmshe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the H6 root mean square error.
.. image:: /pictures/H6.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h7_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean error.
.. image:: /pictures/H7.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mhe(sim, obs)
0.0026331898007430263
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(h)
def h7_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean absolute error.
.. image:: /pictures/H7.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mahe(sim, obs)
0.14549033265788583
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(np.abs(h))
def h7_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 root mean square error.
.. image:: /pictures/H7.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_rmshe(sim, obs)
0.16081964067090945
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
def h8_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H8 mean error.
.. image:: /pictures/H8.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mhe(sim, obs)
0.0018056158633666466
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(h)
def h8_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 mean absolute error.
.. image:: /pictures/H8.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mahe(sim, obs)
0.099764799536836
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(np.abs(h))
def h8_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 root mean square error.
.. image:: /pictures/H8.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_rmshe(sim, obs)
0.11027632503148076
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
# def h9(simulated_array, observed_array, h_type='mhe', k=1):
# h = (simulated_array / observed_array - 1) / \
# np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
# if h_type == 'mhe':
# return h.mean()
# elif h_type == 'ahe':
# return np.abs(h).mean()
# elif h_type == 'rmshe':
# return np.sqrt((h**2).mean())
# else:
# raise RuntimeError("The three types available are 'mhe', 'ahe', and 'rmshe'.")
def h10_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean error.
.. image:: /pictures/H10.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h10_mhe(sim, obs)
-0.0012578676058971154
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(h)
def h10_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean absolute error.
.. image:: /pictures/H10.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_mahe(sim, obs), 6)
0.094636
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(np.abs(h))
def h10_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 root mean square error.
.. image:: /pictures/H10.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_rmshe(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.sqrt(np.mean(h ** 2))
###################################################################################################
# Statistical Error Metrics for Distribution Testing #
###################################################################################################
def g_mean_diff(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the geometric mean difference.
.. image:: /pictures/GMD.png
**Range:**
**Notes:** For the difference of geometric means, the geometric mean is computed for each of
two samples then their difference is taken.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The geometric mean difference value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.g_mean_diff(sim, obs)
0.988855412098022
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.exp(gmean(sim_log) - gmean(obs_log))
def mean_var(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the mean variance.
.. image:: /pictures/MV.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean variance.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.mean_var(sim, obs), 6)
0.010641
References
----------
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.var(np.log1p(observed_array) - np.log1p(simulated_array))
####################################################################################################
# HELPER FUNCTIONS AND API INFORMATION #
####################################################################################################
metric_names = [
'Mean Error', 'Mean Absolute Error', 'Mean Squared Error', 'Mean Log Error',
'Mean Absolute Log Error', 'Mean Squared Log Error', 'Median Error', 'Median Absolute Error',
'Median Squared Error', 'Eclidean Distance', 'Normalized Eclidean Distance',
'Root Mean Square Error', 'Root Mean Squared Log Error',
'Normalized Root Mean Square Error - Range', 'Normalized Root Mean Square Error - Mean',
'Normalized Root Mean Square Error - IQR', 'Inertial Root Mean Square Error',
'Mean Absolute Scaled Error', 'Coefficient of Determination', 'Pearson Correlation Coefficient',
'Spearman Rank Correlation Coefficient', 'Anomaly Correlation Coefficient',
'Mean Absolute Percentage Error', 'Mean Absolute Percentage Deviation',
'Mean Arctangent Absolute Percentage Error', 'Symmetric Mean Absolute Percentage Error (1)',
'Symmetric Mean Absolute Percentage Error (2)', 'Index of Agreement (d)',
'Index of Agreement (d1)', 'Modified Index of Agreement', 'Relative Index of Agreement',
'Index of Agreement Refined (dr)', "Watterson's M", 'Mielke-Berry R',
'Nash-Sutcliffe Efficiency', 'Modified Nash-Sutcliffe Efficiency',
'Relative Nash-Sutcliffe Efficiency', 'Kling-Gupta Efficiency (2009)',
'Kling-Gupta Efficiency (2012)', 'Legate-McCabe Efficiency Index',
'Legate-McCabe Index of Agreement', 'Volumetric Efficiency', 'Spectral Angle',
'Spectral Correlation', 'Spectral Information Divergence', 'Spectral Gradient Angle',
'Mean H1 Error', 'Mean Absolute H1 Error', 'Root Mean Square H1 Error', 'Mean H2 Error',
'Mean Absolute H2 Error', 'Root Mean Square H2 Error', 'Mean H3 Error',
'Mean Absolute H3 Error', 'Root Mean Square H3 Error', 'Mean H4 Error',
'Mean Absolute H4 Error', 'Root Mean Square H4 Error', 'Mean H5 Error',
'Mean Absolute H5 Error', 'Root Mean Square H5 Error', 'Mean H6 Error',
'Mean Absolute H6 Error', 'Root Mean Square H6 Error', 'Mean H7 Error',
'Mean Absolute H7 Error', 'Root Mean Square H7 Error', 'Mean H8 Error',
'Mean Absolute H8 Error', 'Root Mean Square H8 Error', 'Mean H10 Error',
'Mean Absolute H10 Error', 'Root Mean Square H10 Error', 'Geometric Mean Difference',
'Mean Variance'
]
metric_abbr = [
'ME', 'MAE', 'MSE', 'MLE', 'MALE', 'MSLE', 'MdE', 'MdAE', 'MdSE', 'ED', 'NED', 'RMSE', 'RMSLE',
'NRMSE (Range)', 'NRMSE (Mean)', 'NRMSE (IQR)', 'IRMSE', 'MASE', 'r2', 'R (Pearson)',
'R (Spearman)', 'ACC', 'MAPE', 'MAPD', 'MAAPE', 'SMAPE1', 'SMAPE2', 'd', 'd1', 'd (Mod.)',
'd (Rel.)', 'dr', 'M', '(MB) R', 'NSE', 'NSE (Mod.)', 'NSE (Rel.)', 'KGE (2009)', 'KGE (2012)',
"E1'", "D1'", 'VE', 'SA', 'SC', 'SID', 'SGA', 'H1 (MHE)', 'H1 (MAHE)', 'H1 (RMSHE)', 'H2 (MHE)',
'H2 (MAHE)', 'H2 (RMSHE)', 'H3 (MHE)', 'H3 (MAHE)', 'H3 (RMSHE)', 'H4 (MHE)', 'H4 (MAHE)',
'H4 (RMSHE)', 'H5 (MHE)', 'H5 (MAHE)', 'H5 (RMSHE)', 'H6 (MHE)', 'H6 (MAHE)', 'H6 (RMSHE)',
'H7 (MHE)', 'H7 (MAHE)', 'H7 (RMSHE)', 'H8 (MHE)', 'H8 (MAHE)', 'H8 (RMSHE)', 'H10 (MHE)',
'H10 (MAHE)', 'H10 (RMSHE)', 'GMD', 'MV'
]
function_list = [
me, mae, mse, mle, male, msle, mde, mdae, mdse, ed, ned, rmse, rmsle, nrmse_range, nrmse_mean,
nrmse_iqr, irmse, mase, r_squared, pearson_r, spearman_r, acc, mape, mapd, maape, smape1,
smape2, d, d1, dmod, drel, dr, watt_m, mb_r, nse, nse_mod, nse_rel, kge_2009, kge_2012,
lm_index, d1_p, ve, sa, sc, sid, sga, h1_mhe, h1_mahe, h1_rmshe, h2_mhe, h2_mahe, h2_rmshe,
h3_mhe, h3_mahe, h3_rmshe, h4_mhe, h4_mahe, h4_rmshe, h5_mhe, h5_mahe, h5_rmshe, h6_mhe,
h6_mahe, h6_rmshe, h7_mhe, h7_mahe, h7_rmshe, h8_mhe, h8_mahe, h8_rmshe, h10_mhe, h10_mahe,
h10_rmshe, g_mean_diff, mean_var,
]
# Assign some properties to each function for ease of use for users
for i in range(len(function_list)):
function_list[i].name = metric_names[i]
function_list[i].abbr = metric_abbr[i]
def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Removes the nan, negative, and inf values in two numpy arrays"""
sim_copy = np.copy(simulated_array)
obs_copy = np.copy(observed_array)
# Checking to see if the vectors are the same length
assert sim_copy.ndim == 1, "The simulated array is not one dimensional."
assert obs_copy.ndim == 1, "The observed array is not one dimensional."
if sim_copy.size != obs_copy.size:
raise RuntimeError("The two ndarrays are not the same size.")
# Treat missing data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain nan values
all_treatment_array = np.ones(obs_copy.size, dtype=bool)
if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_nan = np.isnan(sim_copy)
obs_nan = np.isnan(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_nan] = replace_nan
obs_copy[obs_nan] = replace_nan
warnings.warn("Elements(s) {} contained NaN values in the simulated array and "
"elements(s) {} contained NaN values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_nan)[0],
np.where(obs_nan)[0]),
UserWarning)
else:
# Getting the indices of the nan values, combining them, and informing user.
nan_indices_fcst = ~np.isnan(sim_copy)
nan_indices_obs = ~np.isnan(obs_copy)
all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)
warnings.warn("Row(s) {} contained NaN values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_nan_indices)[0]),
UserWarning)
if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_inf = np.isinf(sim_copy)
obs_inf = np.isinf(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_inf] = replace_inf
obs_copy[obs_inf] = replace_inf
warnings.warn("Elements(s) {} contained Inf values in the simulated array and "
"elements(s) {} contained Inf values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_inf)[0],
np.where(obs_inf)[0]),
UserWarning)
else:
inf_indices_fcst = ~(np.isinf(sim_copy))
inf_indices_obs = ~np.isinf(obs_copy)
all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)
warnings.warn(
"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows "
"are zero indexed).".format(np.where(~all_inf_indices)[0]),
UserWarning
)
# Treat zero data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain zero values
if remove_zero:
if (obs_copy == 0).any() or (sim_copy == 0).any():
zero_indices_fcst = ~(sim_copy == 0)
zero_indices_obs = ~(obs_copy == 0)
all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)
warnings.warn(
"Row(s) {} contained zero values and the row(s) have been removed (Rows are "
"zero indexed).".format(np.where(~all_zero_indices)[0]),
UserWarning
)
# Treat negative data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain negative values
# Ignore runtime warnings from comparing
if remove_neg:
with np.errstate(invalid='ignore'):
obs_copy_bool = obs_copy < 0
sim_copy_bool = sim_copy < 0
if obs_copy_bool.any() or sim_copy_bool.any():
neg_indices_fcst = ~sim_copy_bool
neg_indices_obs = ~obs_copy_bool
all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)
warnings.warn("Row(s) {} contained negative values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_neg_indices)[0]),
UserWarning)
obs_copy = obs_copy[all_treatment_array]
sim_copy = sim_copy[all_treatment_array]
return sim_copy, obs_copy
if __name__ == "__main__":
pass
|
BYU-Hydroinformatics/HydroErr | HydroErr/HydroErr.py | ed | python | def ed(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.linalg.norm(observed_array - simulated_array) | Compute the Euclidean distance between predicted and observed values in vector space.
.. image:: /pictures/ED.png
**Range** 0 ≤ ED < inf, smaller is better.
**Notes** Also sometimes referred to as the L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ed(sim, obs)
1.63707055437449
Returns
-------
float
The euclidean distance error value.
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156. | train | https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L733-L805 | [
"def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,\n remove_neg=False, remove_zero=False):\n \"\"\"Removes the nan, negative, and inf values in two numpy arrays\"\"\"\n sim_copy = np.copy(simulated_array)\n obs_copy = np.copy(observed_array)\n\n # Checking to see if the vectors are the same length\n assert sim_copy.ndim == 1, \"The simulated array is not one dimensional.\"\n assert obs_copy.ndim == 1, \"The observed array is not one dimensional.\"\n\n if sim_copy.size != obs_copy.size:\n raise RuntimeError(\"The two ndarrays are not the same size.\")\n\n # Treat missing data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain nan values\n all_treatment_array = np.ones(obs_copy.size, dtype=bool)\n\n if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_nan = np.isnan(sim_copy)\n obs_nan = np.isnan(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_nan] = replace_nan\n obs_copy[obs_nan] = replace_nan\n\n warnings.warn(\"Elements(s) {} contained NaN values in the simulated array and \"\n \"elements(s) {} contained NaN values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_nan)[0],\n np.where(obs_nan)[0]),\n UserWarning)\n else:\n # Getting the indices of the nan values, combining them, and informing user.\n nan_indices_fcst = ~np.isnan(sim_copy)\n nan_indices_obs = ~np.isnan(obs_copy)\n all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)\n\n warnings.warn(\"Row(s) {} contained NaN values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_nan_indices)[0]),\n UserWarning)\n\n if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_inf = np.isinf(sim_copy)\n obs_inf = np.isinf(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_inf] = replace_inf\n obs_copy[obs_inf] = replace_inf\n\n warnings.warn(\"Elements(s) {} contained Inf values in the simulated array and \"\n \"elements(s) {} contained Inf values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_inf)[0],\n np.where(obs_inf)[0]),\n UserWarning)\n else:\n inf_indices_fcst = ~(np.isinf(sim_copy))\n inf_indices_obs = ~np.isinf(obs_copy)\n all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)\n\n warnings.warn(\n \"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows \"\n \"are zero indexed).\".format(np.where(~all_inf_indices)[0]),\n UserWarning\n )\n\n # Treat zero data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain zero values\n if remove_zero:\n if (obs_copy == 0).any() or (sim_copy == 0).any():\n zero_indices_fcst = ~(sim_copy == 0)\n zero_indices_obs = ~(obs_copy == 0)\n all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)\n\n warnings.warn(\n \"Row(s) {} contained zero values and the row(s) have been removed (Rows are \"\n \"zero indexed).\".format(np.where(~all_zero_indices)[0]),\n UserWarning\n )\n\n # Treat negative data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain negative values\n\n # Ignore runtime warnings from comparing\n if remove_neg:\n with np.errstate(invalid='ignore'):\n obs_copy_bool = obs_copy < 0\n sim_copy_bool = sim_copy < 0\n\n if obs_copy_bool.any() or sim_copy_bool.any():\n neg_indices_fcst = ~sim_copy_bool\n neg_indices_obs = ~obs_copy_bool\n all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)\n\n warnings.warn(\"Row(s) {} contained negative values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_neg_indices)[0]),\n UserWarning)\n\n obs_copy = obs_copy[all_treatment_array]\n sim_copy = sim_copy[all_treatment_array]\n\n return sim_copy, obs_copy\n"
] | # -*- coding: utf-8 -*-
"""
HydroErr contains a library of goodness of fit metrics that measure hydrologic skill.
Each metric is contained in function, and every function has the parameters to treat missing values as
well as remove zero and negative values from the timeseries data.
Each function contains two properties, name and abbr. These can be used in the Hydrostats package when creating tables
and adding metrics to the plots. Link to the hydrostats package: https://github.com/BYU-Hydroinformatics/Hydrostats.
An example of this functionality is shown below.
>>> import HydroErr as he
>>>
>>> he.acc.name
'Anomaly Correlation Coefficient'
>>> he.acc.abbr
'ACC'
"""
from __future__ import division
import numpy as np
from scipy.stats import gmean, rankdata
import warnings
__all__ = ['me', 'mae', 'mse', 'mle', 'male', 'msle', 'mde', 'mdae', 'mdse', 'ed', 'ned', 'rmse',
'rmsle', 'nrmse_range', 'nrmse_mean', 'nrmse_iqr', 'irmse', 'mase', 'r_squared',
'pearson_r', 'spearman_r', 'acc', 'mape', 'mapd', 'maape', 'smape1', 'smape2', 'd', 'd1',
'dmod', 'drel', 'dr', 'watt_m', 'mb_r', 'nse', 'nse_mod', 'nse_rel', 'kge_2009',
'kge_2012', 'lm_index', 'd1_p', 've', 'sa', 'sc', 'sid', 'sga', 'h1_mhe', 'h1_mahe',
'h1_rmshe', 'h2_mhe', 'h2_mahe', 'h2_rmshe', 'h3_mhe', 'h3_mahe', 'h3_rmshe', 'h4_mhe',
'h4_mahe', 'h4_rmshe', 'h5_mhe', 'h5_mahe', 'h5_rmshe', 'h6_mhe', 'h6_mahe', 'h6_rmshe',
'h7_mhe', 'h7_mahe', 'h7_rmshe', 'h8_mhe', 'h8_mahe', 'h8_rmshe', 'h10_mhe', 'h10_mahe',
'h10_rmshe', 'g_mean_diff', 'mean_var']
####################################################################################################
# General and Hydrological Error Metrics #
####################################################################################################
def me(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean error of the simulated and observed data.
.. image:: /pictures/ME.png
**Range:** -inf < MAE < inf, data units, closer to zero is better, indicates bias.
**Notes:** The mean error (ME) measures the difference between the simulated data and the
observed data. For the mean error, a smaller number indicates a better fit to the original
data. Note that if the error is in the form of random noise, the mean error will be very small,
which can skew the accuracy of this metric. ME is cumulative and will be small even if there
are large positive and negative errors that balance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean error value.
Examples
--------
Note that in this example the random noise cancels, leaving a very small ME.
>>> import HydroErr as he
>>> import numpy as np
>>> # Seed for reproducibility
>>> np.random.seed(54839)
>>> x = np.arange(100) / 20
>>> sim = np.sin(x) + 2
>>> obs = sim * (((np.random.rand(100) - 0.5) / 10) + 1)
>>> he.me(sim, obs)
-0.006832220968967168
References
----------
- Fisher, R.A., 1920. A Mathematical Examination of the Methods of Determining the Accuracy of
an Observation by the Mean Error, and by the Mean Square Error. Monthly Notices of the Royal
Astronomical Society 80 758 - 770.
"""
# Treating missing values
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero)
return np.mean(simulated_array - observed_array)
def mae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute error of the simulated and observed data.
.. image:: /pictures/MAE.png
**Range:** 0 ≤ MAE < inf, data units, smaller is better.
**Notes:** The ME measures the absolute difference between the simulated data and the observed
data. For the mean abolute error, a smaller number indicates a better fit to the original data.
Also note that random errors do not cancel. Also referred to as an L1-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute error value.
References
----------
- Willmott, Cort J., and Kenji Matsuura. “Advantages of the Mean Absolute Error (MAE) over the
Root Mean Square Error (RMSE) in Assessing Average Model Performance.” Climate Research 30,
no. 1 (2005): 79–82.
- Willmott, Cort J., and Kenji Matsuura. “On the Use of Dimensioned Measures of Error to
Evaluate the Performance of Spatial Interpolators.” International Journal of Geographical
Information Science 20, no. 1 (2006): 89–102.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mae(sim, obs)
0.5666666666666665
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean(np.absolute(simulated_array - observed_array))
def mse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared error of the simulated and observed data.
.. image:: /pictures/MSE.png
**Range:** 0 ≤ MSE < inf, data units squared, smaller is better.
**Notes:** Random errors do not cancel, highlights larger errors, also referred to as a
squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mse(sim, obs)
0.4333333333333333
References
----------
- Wang, Zhou, and Alan C. Bovik. “Mean Squared Error: Love It or Leave It? A New Look at Signal
Fidelity Measures.” IEEE Signal Processing Magazine 26, no. 1 (2009): 98–117.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean((simulated_array - observed_array) ** 2)
def mle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean log error of the simulated and observed data.
.. image:: /pictures/MLE.png
**Range:** -inf < MLE < inf, data units, closer to zero is better.
**Notes** Same as the mean erro (ME) only use log ratios as the error term. Limits the impact of outliers, more
evenly weights high and low data values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mle(sim, obs)
0.002961767058151136
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(sim_log - obs_log)
def male(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean absolute log error of the simulated and observed data.
.. image:: /pictures/MALE.png
**Range:** 0 ≤ MALE < inf, data units squared, smaller is better.
**Notes** Same as MAE only use log ratios as the error term. Limits the impact of outliers,
more evenly weights high and low flows.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.male(sim, obs), 6)
0.090417
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(np.abs(sim_log - obs_log))
def msle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared log error of the simulated and observed data.
.. image:: /pictures/MSLE.png
**Range:** 0 ≤ MSLE < inf, data units squared, smaller is better.
**Notes** Same as the mean squared error (MSE) only use log ratios as the error term. Limits
the impact of outliers, more evenly weights high and low values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.msle(sim, obs), 6)
0.010426
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean((sim_log - obs_log) ** 2)
def mde(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median error (MdE) between the simulated and observed data.
.. image:: /pictures/MdE.png
**Range** -inf < MdE < inf, closer to zero is better.
**Notes** This metric indicates bias. It is similar to the mean error (ME), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mde(sim, obs)
-0.10000000000000009
Returns
-------
float
The median error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(simulated_array - observed_array)
def mdae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median absolute error (MdAE) between the simulated and observed data.
.. image:: /pictures/MdAE.png
**Range** 0 ≤ MdAE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean absolute error (MAE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdae(sim, obs)
0.75
Returns
-------
float
The median absolute error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(np.abs(simulated_array - observed_array))
def mdse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median squared error (MdSE) between the simulated and observed data.
.. image:: /pictures/MdSE.png
**Range** 0 ≤ MdSE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean squared error (MSE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdse(sim, obs)
0.625
Returns
-------
float
The median squared error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median((simulated_array - observed_array) ** 2)
def ed(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Euclidean distance between predicted and observed values in vector space.
.. image:: /pictures/ED.png
**Range** 0 ≤ ED < inf, smaller is better.
**Notes** Also sometimes referred to as the L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ed(sim, obs)
1.63707055437449
Returns
-------
float
The euclidean distance error value.
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.linalg.norm(observed_array - simulated_array)
def ned(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the normalized Euclidian distance between the simulated and observed data in vector
space.
.. image:: /pictures/NED.png
**Range** 0 ≤ NED < inf, smaller is better.
**Notes** Also sometimes referred to as the squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The normalized euclidean distance value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ned(sim, obs)
0.2872053604165771
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array / np.mean(observed_array)
b = simulated_array / np.mean(simulated_array)
return np.linalg.norm(a - b)
def rmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square error between the simulated and observed data.
.. image:: /pictures/RMSE.png
**Range** 0 ≤ RMSE < inf, smaller is better.
**Notes:** The standard deviation of the residuals. A lower spread indicates that the points
are better concentrated around the line of best fit (linear). Random errors do not cancel.
This metric will highlights larger errors.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.rmse(sim, obs)
0.668331255192114
References
----------
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.sqrt(np.mean((simulated_array - observed_array) ** 2))
def rmsle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square log error between the simulated and observed data.
.. image:: /pictures/RMSLE.png
**Range:** 0 ≤ RMSLE < inf. Smaller is better, and it does not indicate bias.
**Notes:** Random errors do not cancel while using this metric. This metric limits the
impact of outliers by more evenly weighting high and low values. To calculate the log values,
each value in the observed and simulated array is increased by one unit in order to avoid
run-time errors and nan values (function np.log1p).
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square log error value.
Examples
--------
Notice that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.rmsle(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
"""
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf, remove_neg=remove_neg,
remove_zero=remove_zero)
return np.sqrt(np.mean(np.power(np.log1p(simulated_array) - np.log1p(observed_array), 2)))
def nrmse_range(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the range normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Range.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the range of the observed time series (x).
Normalizing allows comparison between data sets with different scales. The NRMSErange is the
most sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The range normalized root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_range(sim, obs)
0.0891108340256152
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_max = np.max(observed_array)
obs_min = np.min(observed_array)
return rmse_value / (obs_max - obs_min)
def nrmse_mean(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Mean.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the mean of the observed time series (x).
Normalizing allows comparison between data sets with different scales.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_mean(sim, obs)
0.11725109740212526
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_mean = np.mean(observed_array)
return rmse_value / obs_mean
def nrmse_iqr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the IQR normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_IQR.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the interquartile range of the observed time
series (x). Normalizing allows comparison between data sets with different scales.
The NRMSEquartile is the least sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The IQR normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_iqr(sim, obs)
0.2595461185212093
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
q1 = np.percentile(observed_array, 25)
q3 = np.percentile(observed_array, 75)
iqr = q3 - q1
return rmse_value / iqr
def irmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the inertial root mean square error (IRMSE) between the simulated and observed data.
.. image:: /pictures/IRMSE.png
**Range:** 0 ≤ IRMSE < inf, lower is better.
**Notes:** This metric is the RMSE devided by by the standard deviation of the gradient of the
observed timeseries data. This metric is meant to be help understand the ability of the model
to predict changes in observation.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The inertial root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.irmse(sim, obs)
0.14572738134831856
References
----------
- Daga, M., Deo, M.C., 2009. Alternative data-driven methods to estimate wind from waves by
inverse modeling. Natural Hazards 49(2) 293-310.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Getting the gradient of the observed data
obs_len = observed_array.size
obs_grad = observed_array[1:obs_len] - observed_array[0:obs_len - 1]
# Standard deviation of the gradient
obs_grad_std = np.std(obs_grad, ddof=1)
# Divide RMSE by the standard deviation of the gradient of the observed data
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
return rmse_value / obs_grad_std
def mase(simulated_array, observed_array, m=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute scaled error between the simulated and observed data.
.. image:: /pictures/MASE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
m: int
If given, indicates the seasonal period m. If not given, the default is 1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute scaled error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mase(sim, obs)
0.17341040462427745
References
----------
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
start = m
end = simulated_array.size - m
a = np.mean(np.abs(simulated_array - observed_array))
b = np.abs(observed_array[start:observed_array.size] - observed_array[:end])
return a / (np.sum(b) / end)
def pearson_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the pearson correlation coefficient.
.. image:: /pictures/R_pearson.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The pearson r coefficient measures linear correlation. It is sensitive to outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Pearson correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.pearson_r(sim, obs)
0.9610793632835262
References
----------
- Pearson, K. (1895). Note on regression and inheritance in the case of two parents.
Proceedings of the Royal Society of London, 58, 240-242.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
top = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1 = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2 = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
return top / (bot1 * bot2)
def spearman_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the spearman rank correlation coefficient.
.. image:: /pictures/R_spearman.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The spearman r coefficient measures the monotonic relation between simulated and
observed data. Because it uses a nonparametric measure of rank correlation, it is less sensitive
to outliers compared to the Pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spearman rank correlation coefficient.
Examples
----------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.spearman_r(sim, obs)
0.942857142857143
References
----------
- Spearman C (1904). "The proof and measurement of association between two things". American
Journal of Psychology. 15: 72–101. doi:10.2307/1412159
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rank_sim = rankdata(simulated_array)
rank_obs = rankdata(observed_array)
mean_rank_sim = np.mean(rank_sim)
mean_rank_obs = np.mean(rank_obs)
top = np.mean((rank_obs - mean_rank_obs) * (rank_sim - mean_rank_sim))
bot = np.sqrt(
np.mean((rank_obs - mean_rank_obs) ** 2) * np.mean((rank_sim - mean_rank_sim) ** 2))
return top / bot
def r_squared(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Coefficient of Determination (r2).
.. image:: /pictures/r2.png
**Range:** 0 ≤ r2 ≤ 1. 1 indicates perfect correlation, 0 indicates complete randomness.
**Notes:** The Coefficient of Determination measures the linear relation between simulated and
observed data. Because it is the pearson correlation coefficient squared, it is more heavily
affected by outliers than the pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The coefficient of determination (R^2).
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.r_squared(sim, obs)
0.9236735425294681
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array - np.mean(observed_array)
b = simulated_array - np.mean(simulated_array)
return (np.sum(a * b)) ** 2 / (np.sum(a ** 2) * np.sum(b ** 2))
def acc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the anomaly correlation coefficient (ACC).
.. image:: /pictures/ACC.png
**Range:** -1 ≤ ACC ≤ 1. -1 indicates perfect negative correlation of the variation
pattern of the anomalies, 0 indicates complete randomness of the variation patterns of the
anomalies, 1 indicates perfect correlation of the variation pattern of the anomalies.
**Notes:** Common measure in the verification of spatial fields. Measures the correlation
between the variation pattern of the simulated data compared to the observed data.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The anomaly correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.acc(sim, obs)
0.8008994694029383
References
----------
- Langland, Rolf H., and Ryan N. Maue. “Recent Northern Hemisphere Mid-Latitude Medium-Range
Deterministic Forecast Skill.” Tellus A: Dynamic Meteorology and Oceanography 64,
no. 1 (2012): 17531.
- Miyakoda, K., G. D. Hembree, R. F. Strickler, and I. Shulman. “Cumulative Results of Extended
Forecast Experiments I. Model Performance for Winter Cases.” Monthly Weather Review 100, no.
12(1972): 836–55.
- Murphy, Allan H., and Edward S. Epstein. “Skill Scores and Correlation Coefficients in Model
Verification.” Monthly Weather Review 117, no. 3 (1989): 572–82.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - np.mean(simulated_array)
b = observed_array - np.mean(observed_array)
c = np.std(observed_array, ddof=1) * np.std(simulated_array, ddof=1) * simulated_array.size
return np.dot(a, b / c)
def mape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the mean absolute percentage error (MAPE).
.. image:: /pictures/MAPE.png
**Range:** 0% ≤ MAPE ≤ inf. 0% indicates perfect correlation, a larger error indicates a
larger percent error in the data.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
c = 100 / simulated_array.size
return c * np.sum(b)
def mapd(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the mean absolute percentage deviation (MAPD).
.. image:: /pictures/MAPD.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage deviation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mapd(sim, obs)
0.10526315789473682
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(np.abs(observed_array))
return a / b
def maape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the Mean Arctangent Absolute Percentage Error (MAAPE).
.. image:: /pictures/MAAPE.png
**Range:** 0 ≤ MAAPE < π/2, does not indicate bias, smaller is better.
**Notes:** Represents the mean absolute error as a percentage of the observed values. Handles
0s in the observed data. This metric is not as biased as MAPE by under-over predictions.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean arctangent absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
- Kim, S., Kim, H., 2016. A new metric of absolute percentage error for intermittent demand
forecasts. International Journal of Forecasting 32(3) 669-679.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
return np.mean(np.arctan(b))
def smape1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (1) (SMAPE1).
.. image:: /pictures/SMAPE1.png
**Range:** 0 ≤ SMAPE1 < 100%, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (1).
Examples
--------
Note that if we switch the simulated and observed arrays the result is the same
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape1(sim, obs)
5.871915694397428
>>> he.smape1(obs, sim)
5.871915694397428
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 100 / simulated_array.size
b = np.abs(simulated_array - observed_array)
c = np.abs(simulated_array) + np.abs(observed_array)
return a * np.sum(b / c)
def smape2(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (2) (SMAPE2).
.. image:: /pictures/SMAPE2.png
**Range:** 0 ≤ SMAPE1 < 200%, does not indicate bias, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE with only positive metric values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (2).
Examples
--------
Note that switching the simulated and observed arrays yields the same results
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape2(sim, obs)
11.743831388794856
>>> he.smape2(obs, sim)
11.743831388794856
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = (simulated_array + observed_array) / 2
c = 100 / simulated_array.size
return c * np.sum(np.abs(a / b))
def d(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d).
.. image:: /pictures/d.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d(sim, obs)
0.978477353035657
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (observed_array - simulated_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
return 1 - (np.sum(a) / np.sum((b + c) ** 2))
def d1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d1).
.. image:: /pictures/d1.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric. Compared
to the other index of agreement (d) it has a reduced impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (d1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1(sim, obs)
0.8434782608695652
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
obs_mean = np.mean(observed_array)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.abs(simulated_array - obs_mean)
c = np.abs(observed_array - obs_mean)
return 1 - np.sum(a) / np.sum(b + c)
def dr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the refined index of agreement (dr).
.. image:: /pictures/dr.png
**Range:** -1 ≤ dr < 1, does not indicate bias, larger is better.
**Notes:** Reformulation of Willmott’s index of agreement. This metric was created to address
issues in the index of agreement and the Nash-Sutcliffe efficiency metric. Meant to be a
flexible metric for use in climatology.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The refined index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dr(sim, obs)
0.847457627118644
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = 2 * np.sum(np.abs(observed_array - observed_array.mean()))
if a <= b:
return 1 - (a / b)
else:
return (b / a) - 1
def drel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the relative index of agreement (drel).
.. image:: /pictures/drel.png
**Range:** 0 ≤ drel < 1, does not indicate bias, larger is better.
**Notes:** Instead of absolute differences, this metric uses relative differences.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.drel(sim, obs)
0.9740868625579597
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = ((simulated_array - observed_array) / observed_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = ((b + c) / np.mean(observed_array)) ** 2
return 1 - (np.sum(a) / np.sum(e))
def dmod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the modified index of agreement (dmod).
.. image:: /pictures/dmod.png
**Range:** 0 ≤ dmod < 1, does not indicate bias, larger is better.
**Notes:** When j=1, this metric is the same as d1. As j becomes larger, outliers have a larger
impact on the value.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
Optional input indicating the j values desired. A higher j places more emphasis on
outliers. j is 1 by default.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified index of agreement.
Examples
--------
Note that using the default is the same as calculating the d1 metric. Changing the value of j
modification of the metric.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dmod(sim, obs) # Same as d1
0.8434782608695652
>>> he.dmod(sim, obs, j=1.5)
0.9413310986805733
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = (b + c) ** j
return 1 - (np.sum(a) / np.sum(e))
def watt_m(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute Watterson's M (M).
.. image:: /pictures/M.png
**Range:** -1 ≤ M < 1, does not indicate bias, larger is better.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
Watterson's M value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.watt_m(sim, obs)
0.8307913876595929
References
----------
- Watterson, I.G., 1996. Non‐dimensional measures of climate model performance. International
Journal of Climatology 16(4) 379-391.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 2 / np.pi
b = np.mean((simulated_array - observed_array) ** 2) # MSE
c = np.std(observed_array, ddof=1) ** 2 + np.std(simulated_array, ddof=1) ** 2
e = (np.mean(simulated_array) - np.mean(observed_array)) ** 2
f = c + e
return a * np.arcsin(1 - (b / f))
def mb_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute Mielke-Berry R value (MB R).
.. image:: /pictures/MB_R.png
**Range:** 0 ≤ MB R < 1, does not indicate bias, larger is better.
**Notes:** Compares prediction to probability it arose by chance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Mielke-Berry R value.
Notes
-----
If a more optimized version is desired, the `numba package <http://numba.pydata.org/doc.html>`_ can be implemented
for a much more optimized performance when computing this metric. An example is given below.
>>> from numba import njit, prange
>>> @njit(parallel=True, fastmath=True)
>>> def mb_par_fastmath(pred, obs): # uses LLVM compiler
>>> assert pred.size == obs.size
>>> n = pred.size
>>> tot = 0.0
>>> mae = 0.0
>>> for i in range(n):
>>> for j in prange(n):
>>> tot += abs(pred[i] - obs[j])
>>> mae += abs(pred[i] - obs[i])
>>> mae = mae / n
>>> mb = 1 - ((n ** 2) * mae / tot)
>>>
>>> return mb
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mb_r(sim, obs)
0.7726315789473684
References
----------
- Berry, K.J., Mielke, P.W., 1988. A Generalization of Cohen's Kappa Agreement Measure to
Interval Measurement and Multiple Raters. Educational and Psychological Measurement 48(4)
921-933.
- Mielke, P.W., Berry, K.J., 2007. Permutation methods: a distance function approach.
Springer Science & Business Media.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Calculate metric
n = simulated_array.size
tot = 0.0
for i in range(n):
tot = tot + np.sum(np.abs(simulated_array - observed_array[i]))
mae_val = np.sum(np.abs(simulated_array - observed_array)) / n
mb = 1 - ((n ** 2) * mae_val / tot)
return mb
def nse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Nash-Sutcliffe Efficiency.
.. image:: /pictures/NSE.png
**Range:** -inf < NSE < 1, does not indicate bias, larger is better.
**Notes:** The Nash-Sutcliffe efficiency metric compares prediction values to naive predictions
(i.e. average value). One major flaw of this metric is that it punishes a higher variance in
the observed values (denominator). This metric is analogous to the mean absolute error skill
score (MAESS) using the mean flow as a benchmark.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Nash-Sutcliffe Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse(sim, obs)
0.922093023255814
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
- McCuen, R.H., Knight, Z., Cutter, A.G., 2006. Evaluation of the Nash-Sutcliffe Efficiency
Index. Journal of Hydraulic Engineering.
- Nash, J.E., Sutcliffe, J.V., 1970. River flow forecasting through conceptual models part
I — A discussion of principles. Journal of Hydrology 282-290.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** 2
b = (np.abs(observed_array - np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def nse_mod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the modified Nash-Sutcliffe efficiency (NSE mod).
.. image:: /pictures/NSEmod.png
**Range:** -inf < NSE (mod) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
If given, sets the value of j to the input. j is 1 by default. A higher j gives more
emphasis to outliers
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_mod(sim, obs)
0.6949152542372882
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = (np.abs(observed_array - np.mean(observed_array))) ** j
return 1 - (np.sum(a) / np.sum(b))
def nse_rel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the relative Nash-Sutcliffe efficiency (NSE rel).
.. image:: /pictures/NSErel.png
**Range:** -inf < NSE (rel) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_rel(sim, obs)
0.9062004687708474
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs((simulated_array - observed_array) / observed_array)) ** 2
b = (np.abs((observed_array - np.mean(observed_array)) / np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def kge_2009(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""Compute the Kling-Gupta efficiency (2009).
.. image:: /pictures/KGE_2009.png
**Range:** -inf < KGE (2009) < 1, larger is better.
**Notes:** Gupta et al. (2009) created this metric to demonstrate the relative importance of
the three components of the NSE, which are correlation, bias and variability. This was done
with hydrologic modeling as the context. This metric is meant to address issues with the NSE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), Alpha, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, alpha, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2009) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2009(sim, obs)
0.912223072345668
>>> he.kge_2009(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.927910707932087, 1.0058823529411764, 0.9181073779138655)
References
----------
- Gupta, H. V., Kling, H., Yilmaz, K. K., & Martinez, G. F. (2009). Decomposition of the mean
squared error and NSE performance criteria: Implications for improving hydrological modelling.
Journal of Hydrology, 377(1-2), 80-91.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array, ddof=1)
obs_sigma = np.std(observed_array, ddof=1)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
if obs_mean != 0:
beta = sim_mean / obs_mean
else:
beta = np.nan
# Relative variability between simulated and observed values
if obs_sigma != 0:
alpha = sim_sigma / obs_sigma
else:
alpha = np.nan
if not np.isnan(beta) and not np.isnan(alpha):
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (alpha - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Alpha is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, alpha, beta, kge
else:
return kge
def kge_2012(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""
Compute the Kling-Gupta efficiency (2012).
.. image:: /pictures/KGE_2012.png
**Range:** -inf < KGE (2012) < 1, does not indicate bias, larger is better.
**Notes:** The modified version of the KGE (2009). Kling proposed this version to avoid
cross-correlation between bias and variability ratios.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), gamma, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, gamma, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2012) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2012(sim, obs)
0.9122230723456678
>>> he.kge_2012(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.9224843295231272, 1.0058823529411764, 0.9132923608280753)
References
----------
- Kling, H., Fuchs, M., & Paulin, M. (2012). Runoff conditions in the upper Danube basin under
an ensemble of climate change scenarios. Journal of Hydrology, 424, 264-277.
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array)
obs_sigma = np.std(observed_array)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
beta = sim_mean / obs_mean
# CV is the coefficient of variation (standard deviation / mean)
sim_cv = sim_sigma / sim_mean
obs_cv = obs_sigma / obs_mean
# Variability Ratio, or the ratio of simulated CV to observed CV
gam = sim_cv / obs_cv
if obs_mean != 0 and obs_sigma != 0 and sim_mean != 0:
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (gam - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
if sim_mean == 0:
warnings.warn(
'Warning: The simulated data mean is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, gam, beta, kge
else:
return kge
def lm_index(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""
Compute the Legate-McCabe Efficiency Index.
.. image:: /pictures/E1p.png
**Range:** 0 ≤ E1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.lm_index(sim, obs)
0.6949152542372882
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
mean_obs = np.mean(observed_array)
if obs_bar_p is not None:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def d1_p(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""Compute the Legate-McCabe Index of Agreement.
.. image:: /pictures/D1p.png
**Range:** 0 ≤ d1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1_p(sim, obs)
0.8434782608695652
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
if obs_bar_p is not None:
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - obs_bar_p) + np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
mean_obs = np.mean(observed_array)
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - mean_obs) + np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def ve(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Volumetric Efficiency (VE).
.. image:: /pictures/VE.png
**Range:** 0 ≤ VE < 1 smaller is better, does not indicate bias.
**Notes:** Represents the error as a percentage of flow.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Volumetric Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ve(sim, obs)
0.8947368421052632
References
----------
- Criss, R.E., Winston, W.E., 2008. Do Nash values have value? Discussion and alternate
proposals. Hydrological Processes 22(14) 2723.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(observed_array)
return 1 - (a / b)
def sa(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Angle (SA).
.. image:: /pictures/SA.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral angle metric measures the angle between the two vectors in hyperspace.
It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Angle value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sa(sim, obs)
0.10816831366492945
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(simulated_array, observed_array)
b = np.linalg.norm(simulated_array) * np.linalg.norm(observed_array)
return np.arccos(a / b)
def sc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Correlation (SC).
.. image:: /pictures/SC.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral correlation metric measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Correlation value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sc(sim, obs)
0.27991341383646606
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(observed_array - np.mean(observed_array), simulated_array - np.mean(simulated_array))
b = np.linalg.norm(observed_array - np.mean(observed_array))
c = np.linalg.norm(simulated_array - np.mean(simulated_array))
e = b * c
return np.arccos(a / e)
def sid(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Information Divergence (SID).
.. image:: /pictures/SID.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral information divergence measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral information divergence value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sid(sim, obs)
0.03517616895318012
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
first = (observed_array / np.mean(observed_array)) - (
simulated_array / np.mean(simulated_array))
second1 = np.log10(observed_array) - np.log10(np.mean(observed_array))
second2 = np.log10(simulated_array) - np.log10(np.mean(simulated_array))
return np.dot(first, second1 - second2)
def sga(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Gradient Angle (SGA).
.. image:: /pictures/SGA.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral gradient angle measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
SG is the gradient of the simulated or observed time series.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Gradient Angle.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sga(sim, obs)
0.26764286472739834
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sgx = observed_array[1:] - observed_array[:observed_array.size - 1]
sgy = simulated_array[1:] - simulated_array[:simulated_array.size - 1]
a = np.dot(sgx, sgy)
b = np.linalg.norm(sgx) * np.linalg.norm(sgy)
return np.arccos(a / b)
####################################################################################################
# H Metrics: Methods from Tornqvist L, Vartia P, and Vartia YO. (1985) #
####################################################################################################
def h1_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the H1 mean error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mhe(sim, obs)
0.002106551840594386
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(h)
def h1_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H1 absolute error.
.. image:: /pictures/H1.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The H1 absolute error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mahe(sim, obs)
0.11639226612630865
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(np.abs(h))
def h1_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H1 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean squared H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_rmshe(sim, obs)
0.12865571253672756
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.sqrt(np.mean(h ** 2))
def h2_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean error.
.. image:: /pictures/H2.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mhe(sim, obs)
-0.015319829424307036
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(h)
def h2_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean absolute error.
.. image:: /pictures/H2.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mahe(sim, obs)
0.11997591408039167
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(np.abs(h))
def h2_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_rmshe(sim, obs)
0.1373586680669673
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.sqrt(np.mean(h ** 2))
def h3_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 mean error.
.. image:: /pictures/H3.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mhe(sim, obs)
-0.006322019630356533
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(h)
def h3_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H3 mean absolute error.
.. image:: /pictures/H3.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mahe(sim, obs)
0.11743831388794855
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(np.abs(h))
def h3_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 root mean square error.
.. image:: /pictures/H3.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.sqrt(np.mean(h ** 2))
def h4_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mhe(sim, obs)
-0.0064637371129817
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(h)
def h4_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H4 mean absolute error.
.. image:: /pictures/H4.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mahe(sim, obs)
0.11781032209144082
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(np.abs(h))
def h4_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_rmshe(sim, obs)
0.13200901963465006
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.sqrt(np.mean(h ** 2))
def h5_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean error.
.. image:: /pictures/H5.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mhe(sim, obs)
-0.006606638791856322
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(h)
def h5_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean absolute error.
.. image:: /pictures/H5.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mahe(sim, obs)
0.11818409010335018
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(np.abs(h))
def h5_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 root mean square error.
.. image:: /pictures/H5.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_rmshe(sim, obs)
0.13254476469410933
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h6_mhe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H6 mean error.
.. image:: /pictures/H6.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mhe(sim, obs)
-0.006322019630356514
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(h)
def h6_mahe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""Compute the H6 mean absolute error.
.. image:: /pictures/H6.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mahe(sim, obs)
0.11743831388794852
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(np.abs(h))
def h6_rmshe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the H6 root mean square error.
.. image:: /pictures/H6.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h7_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean error.
.. image:: /pictures/H7.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mhe(sim, obs)
0.0026331898007430263
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(h)
def h7_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean absolute error.
.. image:: /pictures/H7.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mahe(sim, obs)
0.14549033265788583
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(np.abs(h))
def h7_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 root mean square error.
.. image:: /pictures/H7.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_rmshe(sim, obs)
0.16081964067090945
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
def h8_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H8 mean error.
.. image:: /pictures/H8.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mhe(sim, obs)
0.0018056158633666466
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(h)
def h8_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 mean absolute error.
.. image:: /pictures/H8.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mahe(sim, obs)
0.099764799536836
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(np.abs(h))
def h8_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 root mean square error.
.. image:: /pictures/H8.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_rmshe(sim, obs)
0.11027632503148076
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
# def h9(simulated_array, observed_array, h_type='mhe', k=1):
# h = (simulated_array / observed_array - 1) / \
# np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
# if h_type == 'mhe':
# return h.mean()
# elif h_type == 'ahe':
# return np.abs(h).mean()
# elif h_type == 'rmshe':
# return np.sqrt((h**2).mean())
# else:
# raise RuntimeError("The three types available are 'mhe', 'ahe', and 'rmshe'.")
def h10_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean error.
.. image:: /pictures/H10.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h10_mhe(sim, obs)
-0.0012578676058971154
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(h)
def h10_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean absolute error.
.. image:: /pictures/H10.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_mahe(sim, obs), 6)
0.094636
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(np.abs(h))
def h10_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 root mean square error.
.. image:: /pictures/H10.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_rmshe(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.sqrt(np.mean(h ** 2))
###################################################################################################
# Statistical Error Metrics for Distribution Testing #
###################################################################################################
def g_mean_diff(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the geometric mean difference.
.. image:: /pictures/GMD.png
**Range:**
**Notes:** For the difference of geometric means, the geometric mean is computed for each of
two samples then their difference is taken.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The geometric mean difference value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.g_mean_diff(sim, obs)
0.988855412098022
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.exp(gmean(sim_log) - gmean(obs_log))
def mean_var(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the mean variance.
.. image:: /pictures/MV.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean variance.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.mean_var(sim, obs), 6)
0.010641
References
----------
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.var(np.log1p(observed_array) - np.log1p(simulated_array))
####################################################################################################
# HELPER FUNCTIONS AND API INFORMATION #
####################################################################################################
metric_names = [
'Mean Error', 'Mean Absolute Error', 'Mean Squared Error', 'Mean Log Error',
'Mean Absolute Log Error', 'Mean Squared Log Error', 'Median Error', 'Median Absolute Error',
'Median Squared Error', 'Eclidean Distance', 'Normalized Eclidean Distance',
'Root Mean Square Error', 'Root Mean Squared Log Error',
'Normalized Root Mean Square Error - Range', 'Normalized Root Mean Square Error - Mean',
'Normalized Root Mean Square Error - IQR', 'Inertial Root Mean Square Error',
'Mean Absolute Scaled Error', 'Coefficient of Determination', 'Pearson Correlation Coefficient',
'Spearman Rank Correlation Coefficient', 'Anomaly Correlation Coefficient',
'Mean Absolute Percentage Error', 'Mean Absolute Percentage Deviation',
'Mean Arctangent Absolute Percentage Error', 'Symmetric Mean Absolute Percentage Error (1)',
'Symmetric Mean Absolute Percentage Error (2)', 'Index of Agreement (d)',
'Index of Agreement (d1)', 'Modified Index of Agreement', 'Relative Index of Agreement',
'Index of Agreement Refined (dr)', "Watterson's M", 'Mielke-Berry R',
'Nash-Sutcliffe Efficiency', 'Modified Nash-Sutcliffe Efficiency',
'Relative Nash-Sutcliffe Efficiency', 'Kling-Gupta Efficiency (2009)',
'Kling-Gupta Efficiency (2012)', 'Legate-McCabe Efficiency Index',
'Legate-McCabe Index of Agreement', 'Volumetric Efficiency', 'Spectral Angle',
'Spectral Correlation', 'Spectral Information Divergence', 'Spectral Gradient Angle',
'Mean H1 Error', 'Mean Absolute H1 Error', 'Root Mean Square H1 Error', 'Mean H2 Error',
'Mean Absolute H2 Error', 'Root Mean Square H2 Error', 'Mean H3 Error',
'Mean Absolute H3 Error', 'Root Mean Square H3 Error', 'Mean H4 Error',
'Mean Absolute H4 Error', 'Root Mean Square H4 Error', 'Mean H5 Error',
'Mean Absolute H5 Error', 'Root Mean Square H5 Error', 'Mean H6 Error',
'Mean Absolute H6 Error', 'Root Mean Square H6 Error', 'Mean H7 Error',
'Mean Absolute H7 Error', 'Root Mean Square H7 Error', 'Mean H8 Error',
'Mean Absolute H8 Error', 'Root Mean Square H8 Error', 'Mean H10 Error',
'Mean Absolute H10 Error', 'Root Mean Square H10 Error', 'Geometric Mean Difference',
'Mean Variance'
]
metric_abbr = [
'ME', 'MAE', 'MSE', 'MLE', 'MALE', 'MSLE', 'MdE', 'MdAE', 'MdSE', 'ED', 'NED', 'RMSE', 'RMSLE',
'NRMSE (Range)', 'NRMSE (Mean)', 'NRMSE (IQR)', 'IRMSE', 'MASE', 'r2', 'R (Pearson)',
'R (Spearman)', 'ACC', 'MAPE', 'MAPD', 'MAAPE', 'SMAPE1', 'SMAPE2', 'd', 'd1', 'd (Mod.)',
'd (Rel.)', 'dr', 'M', '(MB) R', 'NSE', 'NSE (Mod.)', 'NSE (Rel.)', 'KGE (2009)', 'KGE (2012)',
"E1'", "D1'", 'VE', 'SA', 'SC', 'SID', 'SGA', 'H1 (MHE)', 'H1 (MAHE)', 'H1 (RMSHE)', 'H2 (MHE)',
'H2 (MAHE)', 'H2 (RMSHE)', 'H3 (MHE)', 'H3 (MAHE)', 'H3 (RMSHE)', 'H4 (MHE)', 'H4 (MAHE)',
'H4 (RMSHE)', 'H5 (MHE)', 'H5 (MAHE)', 'H5 (RMSHE)', 'H6 (MHE)', 'H6 (MAHE)', 'H6 (RMSHE)',
'H7 (MHE)', 'H7 (MAHE)', 'H7 (RMSHE)', 'H8 (MHE)', 'H8 (MAHE)', 'H8 (RMSHE)', 'H10 (MHE)',
'H10 (MAHE)', 'H10 (RMSHE)', 'GMD', 'MV'
]
function_list = [
me, mae, mse, mle, male, msle, mde, mdae, mdse, ed, ned, rmse, rmsle, nrmse_range, nrmse_mean,
nrmse_iqr, irmse, mase, r_squared, pearson_r, spearman_r, acc, mape, mapd, maape, smape1,
smape2, d, d1, dmod, drel, dr, watt_m, mb_r, nse, nse_mod, nse_rel, kge_2009, kge_2012,
lm_index, d1_p, ve, sa, sc, sid, sga, h1_mhe, h1_mahe, h1_rmshe, h2_mhe, h2_mahe, h2_rmshe,
h3_mhe, h3_mahe, h3_rmshe, h4_mhe, h4_mahe, h4_rmshe, h5_mhe, h5_mahe, h5_rmshe, h6_mhe,
h6_mahe, h6_rmshe, h7_mhe, h7_mahe, h7_rmshe, h8_mhe, h8_mahe, h8_rmshe, h10_mhe, h10_mahe,
h10_rmshe, g_mean_diff, mean_var,
]
# Assign some properties to each function for ease of use for users
for i in range(len(function_list)):
function_list[i].name = metric_names[i]
function_list[i].abbr = metric_abbr[i]
def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Removes the nan, negative, and inf values in two numpy arrays"""
sim_copy = np.copy(simulated_array)
obs_copy = np.copy(observed_array)
# Checking to see if the vectors are the same length
assert sim_copy.ndim == 1, "The simulated array is not one dimensional."
assert obs_copy.ndim == 1, "The observed array is not one dimensional."
if sim_copy.size != obs_copy.size:
raise RuntimeError("The two ndarrays are not the same size.")
# Treat missing data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain nan values
all_treatment_array = np.ones(obs_copy.size, dtype=bool)
if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_nan = np.isnan(sim_copy)
obs_nan = np.isnan(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_nan] = replace_nan
obs_copy[obs_nan] = replace_nan
warnings.warn("Elements(s) {} contained NaN values in the simulated array and "
"elements(s) {} contained NaN values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_nan)[0],
np.where(obs_nan)[0]),
UserWarning)
else:
# Getting the indices of the nan values, combining them, and informing user.
nan_indices_fcst = ~np.isnan(sim_copy)
nan_indices_obs = ~np.isnan(obs_copy)
all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)
warnings.warn("Row(s) {} contained NaN values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_nan_indices)[0]),
UserWarning)
if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_inf = np.isinf(sim_copy)
obs_inf = np.isinf(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_inf] = replace_inf
obs_copy[obs_inf] = replace_inf
warnings.warn("Elements(s) {} contained Inf values in the simulated array and "
"elements(s) {} contained Inf values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_inf)[0],
np.where(obs_inf)[0]),
UserWarning)
else:
inf_indices_fcst = ~(np.isinf(sim_copy))
inf_indices_obs = ~np.isinf(obs_copy)
all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)
warnings.warn(
"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows "
"are zero indexed).".format(np.where(~all_inf_indices)[0]),
UserWarning
)
# Treat zero data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain zero values
if remove_zero:
if (obs_copy == 0).any() or (sim_copy == 0).any():
zero_indices_fcst = ~(sim_copy == 0)
zero_indices_obs = ~(obs_copy == 0)
all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)
warnings.warn(
"Row(s) {} contained zero values and the row(s) have been removed (Rows are "
"zero indexed).".format(np.where(~all_zero_indices)[0]),
UserWarning
)
# Treat negative data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain negative values
# Ignore runtime warnings from comparing
if remove_neg:
with np.errstate(invalid='ignore'):
obs_copy_bool = obs_copy < 0
sim_copy_bool = sim_copy < 0
if obs_copy_bool.any() or sim_copy_bool.any():
neg_indices_fcst = ~sim_copy_bool
neg_indices_obs = ~obs_copy_bool
all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)
warnings.warn("Row(s) {} contained negative values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_neg_indices)[0]),
UserWarning)
obs_copy = obs_copy[all_treatment_array]
sim_copy = sim_copy[all_treatment_array]
return sim_copy, obs_copy
if __name__ == "__main__":
pass
|
BYU-Hydroinformatics/HydroErr | HydroErr/HydroErr.py | ned | python | def ned(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array / np.mean(observed_array)
b = simulated_array / np.mean(simulated_array)
return np.linalg.norm(a - b) | Compute the normalized Euclidian distance between the simulated and observed data in vector
space.
.. image:: /pictures/NED.png
**Range** 0 ≤ NED < inf, smaller is better.
**Notes** Also sometimes referred to as the squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The normalized euclidean distance value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ned(sim, obs)
0.2872053604165771
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156. | train | https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L808-L883 | [
"def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,\n remove_neg=False, remove_zero=False):\n \"\"\"Removes the nan, negative, and inf values in two numpy arrays\"\"\"\n sim_copy = np.copy(simulated_array)\n obs_copy = np.copy(observed_array)\n\n # Checking to see if the vectors are the same length\n assert sim_copy.ndim == 1, \"The simulated array is not one dimensional.\"\n assert obs_copy.ndim == 1, \"The observed array is not one dimensional.\"\n\n if sim_copy.size != obs_copy.size:\n raise RuntimeError(\"The two ndarrays are not the same size.\")\n\n # Treat missing data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain nan values\n all_treatment_array = np.ones(obs_copy.size, dtype=bool)\n\n if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_nan = np.isnan(sim_copy)\n obs_nan = np.isnan(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_nan] = replace_nan\n obs_copy[obs_nan] = replace_nan\n\n warnings.warn(\"Elements(s) {} contained NaN values in the simulated array and \"\n \"elements(s) {} contained NaN values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_nan)[0],\n np.where(obs_nan)[0]),\n UserWarning)\n else:\n # Getting the indices of the nan values, combining them, and informing user.\n nan_indices_fcst = ~np.isnan(sim_copy)\n nan_indices_obs = ~np.isnan(obs_copy)\n all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)\n\n warnings.warn(\"Row(s) {} contained NaN values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_nan_indices)[0]),\n UserWarning)\n\n if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_inf = np.isinf(sim_copy)\n obs_inf = np.isinf(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_inf] = replace_inf\n obs_copy[obs_inf] = replace_inf\n\n warnings.warn(\"Elements(s) {} contained Inf values in the simulated array and \"\n \"elements(s) {} contained Inf values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_inf)[0],\n np.where(obs_inf)[0]),\n UserWarning)\n else:\n inf_indices_fcst = ~(np.isinf(sim_copy))\n inf_indices_obs = ~np.isinf(obs_copy)\n all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)\n\n warnings.warn(\n \"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows \"\n \"are zero indexed).\".format(np.where(~all_inf_indices)[0]),\n UserWarning\n )\n\n # Treat zero data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain zero values\n if remove_zero:\n if (obs_copy == 0).any() or (sim_copy == 0).any():\n zero_indices_fcst = ~(sim_copy == 0)\n zero_indices_obs = ~(obs_copy == 0)\n all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)\n\n warnings.warn(\n \"Row(s) {} contained zero values and the row(s) have been removed (Rows are \"\n \"zero indexed).\".format(np.where(~all_zero_indices)[0]),\n UserWarning\n )\n\n # Treat negative data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain negative values\n\n # Ignore runtime warnings from comparing\n if remove_neg:\n with np.errstate(invalid='ignore'):\n obs_copy_bool = obs_copy < 0\n sim_copy_bool = sim_copy < 0\n\n if obs_copy_bool.any() or sim_copy_bool.any():\n neg_indices_fcst = ~sim_copy_bool\n neg_indices_obs = ~obs_copy_bool\n all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)\n\n warnings.warn(\"Row(s) {} contained negative values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_neg_indices)[0]),\n UserWarning)\n\n obs_copy = obs_copy[all_treatment_array]\n sim_copy = sim_copy[all_treatment_array]\n\n return sim_copy, obs_copy\n"
] | # -*- coding: utf-8 -*-
"""
HydroErr contains a library of goodness of fit metrics that measure hydrologic skill.
Each metric is contained in function, and every function has the parameters to treat missing values as
well as remove zero and negative values from the timeseries data.
Each function contains two properties, name and abbr. These can be used in the Hydrostats package when creating tables
and adding metrics to the plots. Link to the hydrostats package: https://github.com/BYU-Hydroinformatics/Hydrostats.
An example of this functionality is shown below.
>>> import HydroErr as he
>>>
>>> he.acc.name
'Anomaly Correlation Coefficient'
>>> he.acc.abbr
'ACC'
"""
from __future__ import division
import numpy as np
from scipy.stats import gmean, rankdata
import warnings
__all__ = ['me', 'mae', 'mse', 'mle', 'male', 'msle', 'mde', 'mdae', 'mdse', 'ed', 'ned', 'rmse',
'rmsle', 'nrmse_range', 'nrmse_mean', 'nrmse_iqr', 'irmse', 'mase', 'r_squared',
'pearson_r', 'spearman_r', 'acc', 'mape', 'mapd', 'maape', 'smape1', 'smape2', 'd', 'd1',
'dmod', 'drel', 'dr', 'watt_m', 'mb_r', 'nse', 'nse_mod', 'nse_rel', 'kge_2009',
'kge_2012', 'lm_index', 'd1_p', 've', 'sa', 'sc', 'sid', 'sga', 'h1_mhe', 'h1_mahe',
'h1_rmshe', 'h2_mhe', 'h2_mahe', 'h2_rmshe', 'h3_mhe', 'h3_mahe', 'h3_rmshe', 'h4_mhe',
'h4_mahe', 'h4_rmshe', 'h5_mhe', 'h5_mahe', 'h5_rmshe', 'h6_mhe', 'h6_mahe', 'h6_rmshe',
'h7_mhe', 'h7_mahe', 'h7_rmshe', 'h8_mhe', 'h8_mahe', 'h8_rmshe', 'h10_mhe', 'h10_mahe',
'h10_rmshe', 'g_mean_diff', 'mean_var']
####################################################################################################
# General and Hydrological Error Metrics #
####################################################################################################
def me(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean error of the simulated and observed data.
.. image:: /pictures/ME.png
**Range:** -inf < MAE < inf, data units, closer to zero is better, indicates bias.
**Notes:** The mean error (ME) measures the difference between the simulated data and the
observed data. For the mean error, a smaller number indicates a better fit to the original
data. Note that if the error is in the form of random noise, the mean error will be very small,
which can skew the accuracy of this metric. ME is cumulative and will be small even if there
are large positive and negative errors that balance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean error value.
Examples
--------
Note that in this example the random noise cancels, leaving a very small ME.
>>> import HydroErr as he
>>> import numpy as np
>>> # Seed for reproducibility
>>> np.random.seed(54839)
>>> x = np.arange(100) / 20
>>> sim = np.sin(x) + 2
>>> obs = sim * (((np.random.rand(100) - 0.5) / 10) + 1)
>>> he.me(sim, obs)
-0.006832220968967168
References
----------
- Fisher, R.A., 1920. A Mathematical Examination of the Methods of Determining the Accuracy of
an Observation by the Mean Error, and by the Mean Square Error. Monthly Notices of the Royal
Astronomical Society 80 758 - 770.
"""
# Treating missing values
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero)
return np.mean(simulated_array - observed_array)
def mae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute error of the simulated and observed data.
.. image:: /pictures/MAE.png
**Range:** 0 ≤ MAE < inf, data units, smaller is better.
**Notes:** The ME measures the absolute difference between the simulated data and the observed
data. For the mean abolute error, a smaller number indicates a better fit to the original data.
Also note that random errors do not cancel. Also referred to as an L1-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute error value.
References
----------
- Willmott, Cort J., and Kenji Matsuura. “Advantages of the Mean Absolute Error (MAE) over the
Root Mean Square Error (RMSE) in Assessing Average Model Performance.” Climate Research 30,
no. 1 (2005): 79–82.
- Willmott, Cort J., and Kenji Matsuura. “On the Use of Dimensioned Measures of Error to
Evaluate the Performance of Spatial Interpolators.” International Journal of Geographical
Information Science 20, no. 1 (2006): 89–102.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mae(sim, obs)
0.5666666666666665
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean(np.absolute(simulated_array - observed_array))
def mse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared error of the simulated and observed data.
.. image:: /pictures/MSE.png
**Range:** 0 ≤ MSE < inf, data units squared, smaller is better.
**Notes:** Random errors do not cancel, highlights larger errors, also referred to as a
squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mse(sim, obs)
0.4333333333333333
References
----------
- Wang, Zhou, and Alan C. Bovik. “Mean Squared Error: Love It or Leave It? A New Look at Signal
Fidelity Measures.” IEEE Signal Processing Magazine 26, no. 1 (2009): 98–117.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean((simulated_array - observed_array) ** 2)
def mle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean log error of the simulated and observed data.
.. image:: /pictures/MLE.png
**Range:** -inf < MLE < inf, data units, closer to zero is better.
**Notes** Same as the mean erro (ME) only use log ratios as the error term. Limits the impact of outliers, more
evenly weights high and low data values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mle(sim, obs)
0.002961767058151136
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(sim_log - obs_log)
def male(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean absolute log error of the simulated and observed data.
.. image:: /pictures/MALE.png
**Range:** 0 ≤ MALE < inf, data units squared, smaller is better.
**Notes** Same as MAE only use log ratios as the error term. Limits the impact of outliers,
more evenly weights high and low flows.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.male(sim, obs), 6)
0.090417
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(np.abs(sim_log - obs_log))
def msle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared log error of the simulated and observed data.
.. image:: /pictures/MSLE.png
**Range:** 0 ≤ MSLE < inf, data units squared, smaller is better.
**Notes** Same as the mean squared error (MSE) only use log ratios as the error term. Limits
the impact of outliers, more evenly weights high and low values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.msle(sim, obs), 6)
0.010426
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean((sim_log - obs_log) ** 2)
def mde(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median error (MdE) between the simulated and observed data.
.. image:: /pictures/MdE.png
**Range** -inf < MdE < inf, closer to zero is better.
**Notes** This metric indicates bias. It is similar to the mean error (ME), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mde(sim, obs)
-0.10000000000000009
Returns
-------
float
The median error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(simulated_array - observed_array)
def mdae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median absolute error (MdAE) between the simulated and observed data.
.. image:: /pictures/MdAE.png
**Range** 0 ≤ MdAE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean absolute error (MAE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdae(sim, obs)
0.75
Returns
-------
float
The median absolute error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(np.abs(simulated_array - observed_array))
def mdse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median squared error (MdSE) between the simulated and observed data.
.. image:: /pictures/MdSE.png
**Range** 0 ≤ MdSE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean squared error (MSE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdse(sim, obs)
0.625
Returns
-------
float
The median squared error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median((simulated_array - observed_array) ** 2)
def ed(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Euclidean distance between predicted and observed values in vector space.
.. image:: /pictures/ED.png
**Range** 0 ≤ ED < inf, smaller is better.
**Notes** Also sometimes referred to as the L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ed(sim, obs)
1.63707055437449
Returns
-------
float
The euclidean distance error value.
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.linalg.norm(observed_array - simulated_array)
def ned(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the normalized Euclidian distance between the simulated and observed data in vector
space.
.. image:: /pictures/NED.png
**Range** 0 ≤ NED < inf, smaller is better.
**Notes** Also sometimes referred to as the squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The normalized euclidean distance value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ned(sim, obs)
0.2872053604165771
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array / np.mean(observed_array)
b = simulated_array / np.mean(simulated_array)
return np.linalg.norm(a - b)
def rmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square error between the simulated and observed data.
.. image:: /pictures/RMSE.png
**Range** 0 ≤ RMSE < inf, smaller is better.
**Notes:** The standard deviation of the residuals. A lower spread indicates that the points
are better concentrated around the line of best fit (linear). Random errors do not cancel.
This metric will highlights larger errors.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.rmse(sim, obs)
0.668331255192114
References
----------
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.sqrt(np.mean((simulated_array - observed_array) ** 2))
def rmsle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square log error between the simulated and observed data.
.. image:: /pictures/RMSLE.png
**Range:** 0 ≤ RMSLE < inf. Smaller is better, and it does not indicate bias.
**Notes:** Random errors do not cancel while using this metric. This metric limits the
impact of outliers by more evenly weighting high and low values. To calculate the log values,
each value in the observed and simulated array is increased by one unit in order to avoid
run-time errors and nan values (function np.log1p).
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square log error value.
Examples
--------
Notice that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.rmsle(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
"""
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf, remove_neg=remove_neg,
remove_zero=remove_zero)
return np.sqrt(np.mean(np.power(np.log1p(simulated_array) - np.log1p(observed_array), 2)))
def nrmse_range(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the range normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Range.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the range of the observed time series (x).
Normalizing allows comparison between data sets with different scales. The NRMSErange is the
most sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The range normalized root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_range(sim, obs)
0.0891108340256152
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_max = np.max(observed_array)
obs_min = np.min(observed_array)
return rmse_value / (obs_max - obs_min)
def nrmse_mean(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Mean.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the mean of the observed time series (x).
Normalizing allows comparison between data sets with different scales.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_mean(sim, obs)
0.11725109740212526
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_mean = np.mean(observed_array)
return rmse_value / obs_mean
def nrmse_iqr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the IQR normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_IQR.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the interquartile range of the observed time
series (x). Normalizing allows comparison between data sets with different scales.
The NRMSEquartile is the least sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The IQR normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_iqr(sim, obs)
0.2595461185212093
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
q1 = np.percentile(observed_array, 25)
q3 = np.percentile(observed_array, 75)
iqr = q3 - q1
return rmse_value / iqr
def irmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the inertial root mean square error (IRMSE) between the simulated and observed data.
.. image:: /pictures/IRMSE.png
**Range:** 0 ≤ IRMSE < inf, lower is better.
**Notes:** This metric is the RMSE devided by by the standard deviation of the gradient of the
observed timeseries data. This metric is meant to be help understand the ability of the model
to predict changes in observation.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The inertial root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.irmse(sim, obs)
0.14572738134831856
References
----------
- Daga, M., Deo, M.C., 2009. Alternative data-driven methods to estimate wind from waves by
inverse modeling. Natural Hazards 49(2) 293-310.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Getting the gradient of the observed data
obs_len = observed_array.size
obs_grad = observed_array[1:obs_len] - observed_array[0:obs_len - 1]
# Standard deviation of the gradient
obs_grad_std = np.std(obs_grad, ddof=1)
# Divide RMSE by the standard deviation of the gradient of the observed data
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
return rmse_value / obs_grad_std
def mase(simulated_array, observed_array, m=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute scaled error between the simulated and observed data.
.. image:: /pictures/MASE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
m: int
If given, indicates the seasonal period m. If not given, the default is 1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute scaled error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mase(sim, obs)
0.17341040462427745
References
----------
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
start = m
end = simulated_array.size - m
a = np.mean(np.abs(simulated_array - observed_array))
b = np.abs(observed_array[start:observed_array.size] - observed_array[:end])
return a / (np.sum(b) / end)
def pearson_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the pearson correlation coefficient.
.. image:: /pictures/R_pearson.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The pearson r coefficient measures linear correlation. It is sensitive to outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Pearson correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.pearson_r(sim, obs)
0.9610793632835262
References
----------
- Pearson, K. (1895). Note on regression and inheritance in the case of two parents.
Proceedings of the Royal Society of London, 58, 240-242.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
top = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1 = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2 = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
return top / (bot1 * bot2)
def spearman_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the spearman rank correlation coefficient.
.. image:: /pictures/R_spearman.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The spearman r coefficient measures the monotonic relation between simulated and
observed data. Because it uses a nonparametric measure of rank correlation, it is less sensitive
to outliers compared to the Pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spearman rank correlation coefficient.
Examples
----------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.spearman_r(sim, obs)
0.942857142857143
References
----------
- Spearman C (1904). "The proof and measurement of association between two things". American
Journal of Psychology. 15: 72–101. doi:10.2307/1412159
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rank_sim = rankdata(simulated_array)
rank_obs = rankdata(observed_array)
mean_rank_sim = np.mean(rank_sim)
mean_rank_obs = np.mean(rank_obs)
top = np.mean((rank_obs - mean_rank_obs) * (rank_sim - mean_rank_sim))
bot = np.sqrt(
np.mean((rank_obs - mean_rank_obs) ** 2) * np.mean((rank_sim - mean_rank_sim) ** 2))
return top / bot
def r_squared(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Coefficient of Determination (r2).
.. image:: /pictures/r2.png
**Range:** 0 ≤ r2 ≤ 1. 1 indicates perfect correlation, 0 indicates complete randomness.
**Notes:** The Coefficient of Determination measures the linear relation between simulated and
observed data. Because it is the pearson correlation coefficient squared, it is more heavily
affected by outliers than the pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The coefficient of determination (R^2).
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.r_squared(sim, obs)
0.9236735425294681
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array - np.mean(observed_array)
b = simulated_array - np.mean(simulated_array)
return (np.sum(a * b)) ** 2 / (np.sum(a ** 2) * np.sum(b ** 2))
def acc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the anomaly correlation coefficient (ACC).
.. image:: /pictures/ACC.png
**Range:** -1 ≤ ACC ≤ 1. -1 indicates perfect negative correlation of the variation
pattern of the anomalies, 0 indicates complete randomness of the variation patterns of the
anomalies, 1 indicates perfect correlation of the variation pattern of the anomalies.
**Notes:** Common measure in the verification of spatial fields. Measures the correlation
between the variation pattern of the simulated data compared to the observed data.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The anomaly correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.acc(sim, obs)
0.8008994694029383
References
----------
- Langland, Rolf H., and Ryan N. Maue. “Recent Northern Hemisphere Mid-Latitude Medium-Range
Deterministic Forecast Skill.” Tellus A: Dynamic Meteorology and Oceanography 64,
no. 1 (2012): 17531.
- Miyakoda, K., G. D. Hembree, R. F. Strickler, and I. Shulman. “Cumulative Results of Extended
Forecast Experiments I. Model Performance for Winter Cases.” Monthly Weather Review 100, no.
12(1972): 836–55.
- Murphy, Allan H., and Edward S. Epstein. “Skill Scores and Correlation Coefficients in Model
Verification.” Monthly Weather Review 117, no. 3 (1989): 572–82.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - np.mean(simulated_array)
b = observed_array - np.mean(observed_array)
c = np.std(observed_array, ddof=1) * np.std(simulated_array, ddof=1) * simulated_array.size
return np.dot(a, b / c)
def mape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the mean absolute percentage error (MAPE).
.. image:: /pictures/MAPE.png
**Range:** 0% ≤ MAPE ≤ inf. 0% indicates perfect correlation, a larger error indicates a
larger percent error in the data.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
c = 100 / simulated_array.size
return c * np.sum(b)
def mapd(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the mean absolute percentage deviation (MAPD).
.. image:: /pictures/MAPD.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage deviation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mapd(sim, obs)
0.10526315789473682
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(np.abs(observed_array))
return a / b
def maape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the Mean Arctangent Absolute Percentage Error (MAAPE).
.. image:: /pictures/MAAPE.png
**Range:** 0 ≤ MAAPE < π/2, does not indicate bias, smaller is better.
**Notes:** Represents the mean absolute error as a percentage of the observed values. Handles
0s in the observed data. This metric is not as biased as MAPE by under-over predictions.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean arctangent absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
- Kim, S., Kim, H., 2016. A new metric of absolute percentage error for intermittent demand
forecasts. International Journal of Forecasting 32(3) 669-679.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
return np.mean(np.arctan(b))
def smape1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (1) (SMAPE1).
.. image:: /pictures/SMAPE1.png
**Range:** 0 ≤ SMAPE1 < 100%, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (1).
Examples
--------
Note that if we switch the simulated and observed arrays the result is the same
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape1(sim, obs)
5.871915694397428
>>> he.smape1(obs, sim)
5.871915694397428
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 100 / simulated_array.size
b = np.abs(simulated_array - observed_array)
c = np.abs(simulated_array) + np.abs(observed_array)
return a * np.sum(b / c)
def smape2(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (2) (SMAPE2).
.. image:: /pictures/SMAPE2.png
**Range:** 0 ≤ SMAPE1 < 200%, does not indicate bias, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE with only positive metric values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (2).
Examples
--------
Note that switching the simulated and observed arrays yields the same results
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape2(sim, obs)
11.743831388794856
>>> he.smape2(obs, sim)
11.743831388794856
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = (simulated_array + observed_array) / 2
c = 100 / simulated_array.size
return c * np.sum(np.abs(a / b))
def d(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d).
.. image:: /pictures/d.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d(sim, obs)
0.978477353035657
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (observed_array - simulated_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
return 1 - (np.sum(a) / np.sum((b + c) ** 2))
def d1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d1).
.. image:: /pictures/d1.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric. Compared
to the other index of agreement (d) it has a reduced impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (d1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1(sim, obs)
0.8434782608695652
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
obs_mean = np.mean(observed_array)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.abs(simulated_array - obs_mean)
c = np.abs(observed_array - obs_mean)
return 1 - np.sum(a) / np.sum(b + c)
def dr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the refined index of agreement (dr).
.. image:: /pictures/dr.png
**Range:** -1 ≤ dr < 1, does not indicate bias, larger is better.
**Notes:** Reformulation of Willmott’s index of agreement. This metric was created to address
issues in the index of agreement and the Nash-Sutcliffe efficiency metric. Meant to be a
flexible metric for use in climatology.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The refined index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dr(sim, obs)
0.847457627118644
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = 2 * np.sum(np.abs(observed_array - observed_array.mean()))
if a <= b:
return 1 - (a / b)
else:
return (b / a) - 1
def drel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the relative index of agreement (drel).
.. image:: /pictures/drel.png
**Range:** 0 ≤ drel < 1, does not indicate bias, larger is better.
**Notes:** Instead of absolute differences, this metric uses relative differences.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.drel(sim, obs)
0.9740868625579597
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = ((simulated_array - observed_array) / observed_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = ((b + c) / np.mean(observed_array)) ** 2
return 1 - (np.sum(a) / np.sum(e))
def dmod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the modified index of agreement (dmod).
.. image:: /pictures/dmod.png
**Range:** 0 ≤ dmod < 1, does not indicate bias, larger is better.
**Notes:** When j=1, this metric is the same as d1. As j becomes larger, outliers have a larger
impact on the value.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
Optional input indicating the j values desired. A higher j places more emphasis on
outliers. j is 1 by default.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified index of agreement.
Examples
--------
Note that using the default is the same as calculating the d1 metric. Changing the value of j
modification of the metric.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dmod(sim, obs) # Same as d1
0.8434782608695652
>>> he.dmod(sim, obs, j=1.5)
0.9413310986805733
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = (b + c) ** j
return 1 - (np.sum(a) / np.sum(e))
def watt_m(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute Watterson's M (M).
.. image:: /pictures/M.png
**Range:** -1 ≤ M < 1, does not indicate bias, larger is better.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
Watterson's M value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.watt_m(sim, obs)
0.8307913876595929
References
----------
- Watterson, I.G., 1996. Non‐dimensional measures of climate model performance. International
Journal of Climatology 16(4) 379-391.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 2 / np.pi
b = np.mean((simulated_array - observed_array) ** 2) # MSE
c = np.std(observed_array, ddof=1) ** 2 + np.std(simulated_array, ddof=1) ** 2
e = (np.mean(simulated_array) - np.mean(observed_array)) ** 2
f = c + e
return a * np.arcsin(1 - (b / f))
def mb_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute Mielke-Berry R value (MB R).
.. image:: /pictures/MB_R.png
**Range:** 0 ≤ MB R < 1, does not indicate bias, larger is better.
**Notes:** Compares prediction to probability it arose by chance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Mielke-Berry R value.
Notes
-----
If a more optimized version is desired, the `numba package <http://numba.pydata.org/doc.html>`_ can be implemented
for a much more optimized performance when computing this metric. An example is given below.
>>> from numba import njit, prange
>>> @njit(parallel=True, fastmath=True)
>>> def mb_par_fastmath(pred, obs): # uses LLVM compiler
>>> assert pred.size == obs.size
>>> n = pred.size
>>> tot = 0.0
>>> mae = 0.0
>>> for i in range(n):
>>> for j in prange(n):
>>> tot += abs(pred[i] - obs[j])
>>> mae += abs(pred[i] - obs[i])
>>> mae = mae / n
>>> mb = 1 - ((n ** 2) * mae / tot)
>>>
>>> return mb
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mb_r(sim, obs)
0.7726315789473684
References
----------
- Berry, K.J., Mielke, P.W., 1988. A Generalization of Cohen's Kappa Agreement Measure to
Interval Measurement and Multiple Raters. Educational and Psychological Measurement 48(4)
921-933.
- Mielke, P.W., Berry, K.J., 2007. Permutation methods: a distance function approach.
Springer Science & Business Media.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Calculate metric
n = simulated_array.size
tot = 0.0
for i in range(n):
tot = tot + np.sum(np.abs(simulated_array - observed_array[i]))
mae_val = np.sum(np.abs(simulated_array - observed_array)) / n
mb = 1 - ((n ** 2) * mae_val / tot)
return mb
def nse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Nash-Sutcliffe Efficiency.
.. image:: /pictures/NSE.png
**Range:** -inf < NSE < 1, does not indicate bias, larger is better.
**Notes:** The Nash-Sutcliffe efficiency metric compares prediction values to naive predictions
(i.e. average value). One major flaw of this metric is that it punishes a higher variance in
the observed values (denominator). This metric is analogous to the mean absolute error skill
score (MAESS) using the mean flow as a benchmark.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Nash-Sutcliffe Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse(sim, obs)
0.922093023255814
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
- McCuen, R.H., Knight, Z., Cutter, A.G., 2006. Evaluation of the Nash-Sutcliffe Efficiency
Index. Journal of Hydraulic Engineering.
- Nash, J.E., Sutcliffe, J.V., 1970. River flow forecasting through conceptual models part
I — A discussion of principles. Journal of Hydrology 282-290.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** 2
b = (np.abs(observed_array - np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def nse_mod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the modified Nash-Sutcliffe efficiency (NSE mod).
.. image:: /pictures/NSEmod.png
**Range:** -inf < NSE (mod) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
If given, sets the value of j to the input. j is 1 by default. A higher j gives more
emphasis to outliers
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_mod(sim, obs)
0.6949152542372882
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = (np.abs(observed_array - np.mean(observed_array))) ** j
return 1 - (np.sum(a) / np.sum(b))
def nse_rel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the relative Nash-Sutcliffe efficiency (NSE rel).
.. image:: /pictures/NSErel.png
**Range:** -inf < NSE (rel) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_rel(sim, obs)
0.9062004687708474
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs((simulated_array - observed_array) / observed_array)) ** 2
b = (np.abs((observed_array - np.mean(observed_array)) / np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def kge_2009(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""Compute the Kling-Gupta efficiency (2009).
.. image:: /pictures/KGE_2009.png
**Range:** -inf < KGE (2009) < 1, larger is better.
**Notes:** Gupta et al. (2009) created this metric to demonstrate the relative importance of
the three components of the NSE, which are correlation, bias and variability. This was done
with hydrologic modeling as the context. This metric is meant to address issues with the NSE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), Alpha, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, alpha, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2009) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2009(sim, obs)
0.912223072345668
>>> he.kge_2009(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.927910707932087, 1.0058823529411764, 0.9181073779138655)
References
----------
- Gupta, H. V., Kling, H., Yilmaz, K. K., & Martinez, G. F. (2009). Decomposition of the mean
squared error and NSE performance criteria: Implications for improving hydrological modelling.
Journal of Hydrology, 377(1-2), 80-91.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array, ddof=1)
obs_sigma = np.std(observed_array, ddof=1)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
if obs_mean != 0:
beta = sim_mean / obs_mean
else:
beta = np.nan
# Relative variability between simulated and observed values
if obs_sigma != 0:
alpha = sim_sigma / obs_sigma
else:
alpha = np.nan
if not np.isnan(beta) and not np.isnan(alpha):
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (alpha - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Alpha is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, alpha, beta, kge
else:
return kge
def kge_2012(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""
Compute the Kling-Gupta efficiency (2012).
.. image:: /pictures/KGE_2012.png
**Range:** -inf < KGE (2012) < 1, does not indicate bias, larger is better.
**Notes:** The modified version of the KGE (2009). Kling proposed this version to avoid
cross-correlation between bias and variability ratios.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), gamma, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, gamma, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2012) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2012(sim, obs)
0.9122230723456678
>>> he.kge_2012(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.9224843295231272, 1.0058823529411764, 0.9132923608280753)
References
----------
- Kling, H., Fuchs, M., & Paulin, M. (2012). Runoff conditions in the upper Danube basin under
an ensemble of climate change scenarios. Journal of Hydrology, 424, 264-277.
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array)
obs_sigma = np.std(observed_array)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
beta = sim_mean / obs_mean
# CV is the coefficient of variation (standard deviation / mean)
sim_cv = sim_sigma / sim_mean
obs_cv = obs_sigma / obs_mean
# Variability Ratio, or the ratio of simulated CV to observed CV
gam = sim_cv / obs_cv
if obs_mean != 0 and obs_sigma != 0 and sim_mean != 0:
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (gam - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
if sim_mean == 0:
warnings.warn(
'Warning: The simulated data mean is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, gam, beta, kge
else:
return kge
def lm_index(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""
Compute the Legate-McCabe Efficiency Index.
.. image:: /pictures/E1p.png
**Range:** 0 ≤ E1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.lm_index(sim, obs)
0.6949152542372882
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
mean_obs = np.mean(observed_array)
if obs_bar_p is not None:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def d1_p(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""Compute the Legate-McCabe Index of Agreement.
.. image:: /pictures/D1p.png
**Range:** 0 ≤ d1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1_p(sim, obs)
0.8434782608695652
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
if obs_bar_p is not None:
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - obs_bar_p) + np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
mean_obs = np.mean(observed_array)
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - mean_obs) + np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def ve(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Volumetric Efficiency (VE).
.. image:: /pictures/VE.png
**Range:** 0 ≤ VE < 1 smaller is better, does not indicate bias.
**Notes:** Represents the error as a percentage of flow.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Volumetric Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ve(sim, obs)
0.8947368421052632
References
----------
- Criss, R.E., Winston, W.E., 2008. Do Nash values have value? Discussion and alternate
proposals. Hydrological Processes 22(14) 2723.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(observed_array)
return 1 - (a / b)
def sa(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Angle (SA).
.. image:: /pictures/SA.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral angle metric measures the angle between the two vectors in hyperspace.
It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Angle value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sa(sim, obs)
0.10816831366492945
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(simulated_array, observed_array)
b = np.linalg.norm(simulated_array) * np.linalg.norm(observed_array)
return np.arccos(a / b)
def sc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Correlation (SC).
.. image:: /pictures/SC.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral correlation metric measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Correlation value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sc(sim, obs)
0.27991341383646606
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(observed_array - np.mean(observed_array), simulated_array - np.mean(simulated_array))
b = np.linalg.norm(observed_array - np.mean(observed_array))
c = np.linalg.norm(simulated_array - np.mean(simulated_array))
e = b * c
return np.arccos(a / e)
def sid(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Information Divergence (SID).
.. image:: /pictures/SID.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral information divergence measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral information divergence value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sid(sim, obs)
0.03517616895318012
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
first = (observed_array / np.mean(observed_array)) - (
simulated_array / np.mean(simulated_array))
second1 = np.log10(observed_array) - np.log10(np.mean(observed_array))
second2 = np.log10(simulated_array) - np.log10(np.mean(simulated_array))
return np.dot(first, second1 - second2)
def sga(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Gradient Angle (SGA).
.. image:: /pictures/SGA.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral gradient angle measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
SG is the gradient of the simulated or observed time series.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Gradient Angle.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sga(sim, obs)
0.26764286472739834
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sgx = observed_array[1:] - observed_array[:observed_array.size - 1]
sgy = simulated_array[1:] - simulated_array[:simulated_array.size - 1]
a = np.dot(sgx, sgy)
b = np.linalg.norm(sgx) * np.linalg.norm(sgy)
return np.arccos(a / b)
####################################################################################################
# H Metrics: Methods from Tornqvist L, Vartia P, and Vartia YO. (1985) #
####################################################################################################
def h1_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the H1 mean error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mhe(sim, obs)
0.002106551840594386
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(h)
def h1_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H1 absolute error.
.. image:: /pictures/H1.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The H1 absolute error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mahe(sim, obs)
0.11639226612630865
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(np.abs(h))
def h1_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H1 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean squared H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_rmshe(sim, obs)
0.12865571253672756
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.sqrt(np.mean(h ** 2))
def h2_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean error.
.. image:: /pictures/H2.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mhe(sim, obs)
-0.015319829424307036
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(h)
def h2_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean absolute error.
.. image:: /pictures/H2.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mahe(sim, obs)
0.11997591408039167
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(np.abs(h))
def h2_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_rmshe(sim, obs)
0.1373586680669673
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.sqrt(np.mean(h ** 2))
def h3_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 mean error.
.. image:: /pictures/H3.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mhe(sim, obs)
-0.006322019630356533
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(h)
def h3_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H3 mean absolute error.
.. image:: /pictures/H3.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mahe(sim, obs)
0.11743831388794855
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(np.abs(h))
def h3_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 root mean square error.
.. image:: /pictures/H3.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.sqrt(np.mean(h ** 2))
def h4_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mhe(sim, obs)
-0.0064637371129817
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(h)
def h4_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H4 mean absolute error.
.. image:: /pictures/H4.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mahe(sim, obs)
0.11781032209144082
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(np.abs(h))
def h4_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_rmshe(sim, obs)
0.13200901963465006
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.sqrt(np.mean(h ** 2))
def h5_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean error.
.. image:: /pictures/H5.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mhe(sim, obs)
-0.006606638791856322
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(h)
def h5_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean absolute error.
.. image:: /pictures/H5.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mahe(sim, obs)
0.11818409010335018
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(np.abs(h))
def h5_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 root mean square error.
.. image:: /pictures/H5.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_rmshe(sim, obs)
0.13254476469410933
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h6_mhe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H6 mean error.
.. image:: /pictures/H6.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mhe(sim, obs)
-0.006322019630356514
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(h)
def h6_mahe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""Compute the H6 mean absolute error.
.. image:: /pictures/H6.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mahe(sim, obs)
0.11743831388794852
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(np.abs(h))
def h6_rmshe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the H6 root mean square error.
.. image:: /pictures/H6.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h7_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean error.
.. image:: /pictures/H7.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mhe(sim, obs)
0.0026331898007430263
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(h)
def h7_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean absolute error.
.. image:: /pictures/H7.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mahe(sim, obs)
0.14549033265788583
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(np.abs(h))
def h7_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 root mean square error.
.. image:: /pictures/H7.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_rmshe(sim, obs)
0.16081964067090945
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
def h8_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H8 mean error.
.. image:: /pictures/H8.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mhe(sim, obs)
0.0018056158633666466
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(h)
def h8_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 mean absolute error.
.. image:: /pictures/H8.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mahe(sim, obs)
0.099764799536836
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(np.abs(h))
def h8_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 root mean square error.
.. image:: /pictures/H8.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_rmshe(sim, obs)
0.11027632503148076
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
# def h9(simulated_array, observed_array, h_type='mhe', k=1):
# h = (simulated_array / observed_array - 1) / \
# np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
# if h_type == 'mhe':
# return h.mean()
# elif h_type == 'ahe':
# return np.abs(h).mean()
# elif h_type == 'rmshe':
# return np.sqrt((h**2).mean())
# else:
# raise RuntimeError("The three types available are 'mhe', 'ahe', and 'rmshe'.")
def h10_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean error.
.. image:: /pictures/H10.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h10_mhe(sim, obs)
-0.0012578676058971154
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(h)
def h10_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean absolute error.
.. image:: /pictures/H10.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_mahe(sim, obs), 6)
0.094636
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(np.abs(h))
def h10_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 root mean square error.
.. image:: /pictures/H10.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_rmshe(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.sqrt(np.mean(h ** 2))
###################################################################################################
# Statistical Error Metrics for Distribution Testing #
###################################################################################################
def g_mean_diff(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the geometric mean difference.
.. image:: /pictures/GMD.png
**Range:**
**Notes:** For the difference of geometric means, the geometric mean is computed for each of
two samples then their difference is taken.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The geometric mean difference value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.g_mean_diff(sim, obs)
0.988855412098022
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.exp(gmean(sim_log) - gmean(obs_log))
def mean_var(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the mean variance.
.. image:: /pictures/MV.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean variance.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.mean_var(sim, obs), 6)
0.010641
References
----------
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.var(np.log1p(observed_array) - np.log1p(simulated_array))
####################################################################################################
# HELPER FUNCTIONS AND API INFORMATION #
####################################################################################################
metric_names = [
'Mean Error', 'Mean Absolute Error', 'Mean Squared Error', 'Mean Log Error',
'Mean Absolute Log Error', 'Mean Squared Log Error', 'Median Error', 'Median Absolute Error',
'Median Squared Error', 'Eclidean Distance', 'Normalized Eclidean Distance',
'Root Mean Square Error', 'Root Mean Squared Log Error',
'Normalized Root Mean Square Error - Range', 'Normalized Root Mean Square Error - Mean',
'Normalized Root Mean Square Error - IQR', 'Inertial Root Mean Square Error',
'Mean Absolute Scaled Error', 'Coefficient of Determination', 'Pearson Correlation Coefficient',
'Spearman Rank Correlation Coefficient', 'Anomaly Correlation Coefficient',
'Mean Absolute Percentage Error', 'Mean Absolute Percentage Deviation',
'Mean Arctangent Absolute Percentage Error', 'Symmetric Mean Absolute Percentage Error (1)',
'Symmetric Mean Absolute Percentage Error (2)', 'Index of Agreement (d)',
'Index of Agreement (d1)', 'Modified Index of Agreement', 'Relative Index of Agreement',
'Index of Agreement Refined (dr)', "Watterson's M", 'Mielke-Berry R',
'Nash-Sutcliffe Efficiency', 'Modified Nash-Sutcliffe Efficiency',
'Relative Nash-Sutcliffe Efficiency', 'Kling-Gupta Efficiency (2009)',
'Kling-Gupta Efficiency (2012)', 'Legate-McCabe Efficiency Index',
'Legate-McCabe Index of Agreement', 'Volumetric Efficiency', 'Spectral Angle',
'Spectral Correlation', 'Spectral Information Divergence', 'Spectral Gradient Angle',
'Mean H1 Error', 'Mean Absolute H1 Error', 'Root Mean Square H1 Error', 'Mean H2 Error',
'Mean Absolute H2 Error', 'Root Mean Square H2 Error', 'Mean H3 Error',
'Mean Absolute H3 Error', 'Root Mean Square H3 Error', 'Mean H4 Error',
'Mean Absolute H4 Error', 'Root Mean Square H4 Error', 'Mean H5 Error',
'Mean Absolute H5 Error', 'Root Mean Square H5 Error', 'Mean H6 Error',
'Mean Absolute H6 Error', 'Root Mean Square H6 Error', 'Mean H7 Error',
'Mean Absolute H7 Error', 'Root Mean Square H7 Error', 'Mean H8 Error',
'Mean Absolute H8 Error', 'Root Mean Square H8 Error', 'Mean H10 Error',
'Mean Absolute H10 Error', 'Root Mean Square H10 Error', 'Geometric Mean Difference',
'Mean Variance'
]
metric_abbr = [
'ME', 'MAE', 'MSE', 'MLE', 'MALE', 'MSLE', 'MdE', 'MdAE', 'MdSE', 'ED', 'NED', 'RMSE', 'RMSLE',
'NRMSE (Range)', 'NRMSE (Mean)', 'NRMSE (IQR)', 'IRMSE', 'MASE', 'r2', 'R (Pearson)',
'R (Spearman)', 'ACC', 'MAPE', 'MAPD', 'MAAPE', 'SMAPE1', 'SMAPE2', 'd', 'd1', 'd (Mod.)',
'd (Rel.)', 'dr', 'M', '(MB) R', 'NSE', 'NSE (Mod.)', 'NSE (Rel.)', 'KGE (2009)', 'KGE (2012)',
"E1'", "D1'", 'VE', 'SA', 'SC', 'SID', 'SGA', 'H1 (MHE)', 'H1 (MAHE)', 'H1 (RMSHE)', 'H2 (MHE)',
'H2 (MAHE)', 'H2 (RMSHE)', 'H3 (MHE)', 'H3 (MAHE)', 'H3 (RMSHE)', 'H4 (MHE)', 'H4 (MAHE)',
'H4 (RMSHE)', 'H5 (MHE)', 'H5 (MAHE)', 'H5 (RMSHE)', 'H6 (MHE)', 'H6 (MAHE)', 'H6 (RMSHE)',
'H7 (MHE)', 'H7 (MAHE)', 'H7 (RMSHE)', 'H8 (MHE)', 'H8 (MAHE)', 'H8 (RMSHE)', 'H10 (MHE)',
'H10 (MAHE)', 'H10 (RMSHE)', 'GMD', 'MV'
]
function_list = [
me, mae, mse, mle, male, msle, mde, mdae, mdse, ed, ned, rmse, rmsle, nrmse_range, nrmse_mean,
nrmse_iqr, irmse, mase, r_squared, pearson_r, spearman_r, acc, mape, mapd, maape, smape1,
smape2, d, d1, dmod, drel, dr, watt_m, mb_r, nse, nse_mod, nse_rel, kge_2009, kge_2012,
lm_index, d1_p, ve, sa, sc, sid, sga, h1_mhe, h1_mahe, h1_rmshe, h2_mhe, h2_mahe, h2_rmshe,
h3_mhe, h3_mahe, h3_rmshe, h4_mhe, h4_mahe, h4_rmshe, h5_mhe, h5_mahe, h5_rmshe, h6_mhe,
h6_mahe, h6_rmshe, h7_mhe, h7_mahe, h7_rmshe, h8_mhe, h8_mahe, h8_rmshe, h10_mhe, h10_mahe,
h10_rmshe, g_mean_diff, mean_var,
]
# Assign some properties to each function for ease of use for users
for i in range(len(function_list)):
function_list[i].name = metric_names[i]
function_list[i].abbr = metric_abbr[i]
def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Removes the nan, negative, and inf values in two numpy arrays"""
sim_copy = np.copy(simulated_array)
obs_copy = np.copy(observed_array)
# Checking to see if the vectors are the same length
assert sim_copy.ndim == 1, "The simulated array is not one dimensional."
assert obs_copy.ndim == 1, "The observed array is not one dimensional."
if sim_copy.size != obs_copy.size:
raise RuntimeError("The two ndarrays are not the same size.")
# Treat missing data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain nan values
all_treatment_array = np.ones(obs_copy.size, dtype=bool)
if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_nan = np.isnan(sim_copy)
obs_nan = np.isnan(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_nan] = replace_nan
obs_copy[obs_nan] = replace_nan
warnings.warn("Elements(s) {} contained NaN values in the simulated array and "
"elements(s) {} contained NaN values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_nan)[0],
np.where(obs_nan)[0]),
UserWarning)
else:
# Getting the indices of the nan values, combining them, and informing user.
nan_indices_fcst = ~np.isnan(sim_copy)
nan_indices_obs = ~np.isnan(obs_copy)
all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)
warnings.warn("Row(s) {} contained NaN values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_nan_indices)[0]),
UserWarning)
if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_inf = np.isinf(sim_copy)
obs_inf = np.isinf(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_inf] = replace_inf
obs_copy[obs_inf] = replace_inf
warnings.warn("Elements(s) {} contained Inf values in the simulated array and "
"elements(s) {} contained Inf values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_inf)[0],
np.where(obs_inf)[0]),
UserWarning)
else:
inf_indices_fcst = ~(np.isinf(sim_copy))
inf_indices_obs = ~np.isinf(obs_copy)
all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)
warnings.warn(
"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows "
"are zero indexed).".format(np.where(~all_inf_indices)[0]),
UserWarning
)
# Treat zero data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain zero values
if remove_zero:
if (obs_copy == 0).any() or (sim_copy == 0).any():
zero_indices_fcst = ~(sim_copy == 0)
zero_indices_obs = ~(obs_copy == 0)
all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)
warnings.warn(
"Row(s) {} contained zero values and the row(s) have been removed (Rows are "
"zero indexed).".format(np.where(~all_zero_indices)[0]),
UserWarning
)
# Treat negative data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain negative values
# Ignore runtime warnings from comparing
if remove_neg:
with np.errstate(invalid='ignore'):
obs_copy_bool = obs_copy < 0
sim_copy_bool = sim_copy < 0
if obs_copy_bool.any() or sim_copy_bool.any():
neg_indices_fcst = ~sim_copy_bool
neg_indices_obs = ~obs_copy_bool
all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)
warnings.warn("Row(s) {} contained negative values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_neg_indices)[0]),
UserWarning)
obs_copy = obs_copy[all_treatment_array]
sim_copy = sim_copy[all_treatment_array]
return sim_copy, obs_copy
if __name__ == "__main__":
pass
|
BYU-Hydroinformatics/HydroErr | HydroErr/HydroErr.py | nrmse_range | python | def nrmse_range(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_max = np.max(observed_array)
obs_min = np.min(observed_array)
return rmse_value / (obs_max - obs_min) | Compute the range normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Range.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the range of the observed time series (x).
Normalizing allows comparison between data sets with different scales. The NRMSErange is the
most sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The range normalized root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_range(sim, obs)
0.0891108340256152
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142. | train | https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L1044-L1121 | [
"def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,\n remove_neg=False, remove_zero=False):\n \"\"\"Removes the nan, negative, and inf values in two numpy arrays\"\"\"\n sim_copy = np.copy(simulated_array)\n obs_copy = np.copy(observed_array)\n\n # Checking to see if the vectors are the same length\n assert sim_copy.ndim == 1, \"The simulated array is not one dimensional.\"\n assert obs_copy.ndim == 1, \"The observed array is not one dimensional.\"\n\n if sim_copy.size != obs_copy.size:\n raise RuntimeError(\"The two ndarrays are not the same size.\")\n\n # Treat missing data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain nan values\n all_treatment_array = np.ones(obs_copy.size, dtype=bool)\n\n if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_nan = np.isnan(sim_copy)\n obs_nan = np.isnan(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_nan] = replace_nan\n obs_copy[obs_nan] = replace_nan\n\n warnings.warn(\"Elements(s) {} contained NaN values in the simulated array and \"\n \"elements(s) {} contained NaN values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_nan)[0],\n np.where(obs_nan)[0]),\n UserWarning)\n else:\n # Getting the indices of the nan values, combining them, and informing user.\n nan_indices_fcst = ~np.isnan(sim_copy)\n nan_indices_obs = ~np.isnan(obs_copy)\n all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)\n\n warnings.warn(\"Row(s) {} contained NaN values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_nan_indices)[0]),\n UserWarning)\n\n if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_inf = np.isinf(sim_copy)\n obs_inf = np.isinf(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_inf] = replace_inf\n obs_copy[obs_inf] = replace_inf\n\n warnings.warn(\"Elements(s) {} contained Inf values in the simulated array and \"\n \"elements(s) {} contained Inf values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_inf)[0],\n np.where(obs_inf)[0]),\n UserWarning)\n else:\n inf_indices_fcst = ~(np.isinf(sim_copy))\n inf_indices_obs = ~np.isinf(obs_copy)\n all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)\n\n warnings.warn(\n \"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows \"\n \"are zero indexed).\".format(np.where(~all_inf_indices)[0]),\n UserWarning\n )\n\n # Treat zero data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain zero values\n if remove_zero:\n if (obs_copy == 0).any() or (sim_copy == 0).any():\n zero_indices_fcst = ~(sim_copy == 0)\n zero_indices_obs = ~(obs_copy == 0)\n all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)\n\n warnings.warn(\n \"Row(s) {} contained zero values and the row(s) have been removed (Rows are \"\n \"zero indexed).\".format(np.where(~all_zero_indices)[0]),\n UserWarning\n )\n\n # Treat negative data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain negative values\n\n # Ignore runtime warnings from comparing\n if remove_neg:\n with np.errstate(invalid='ignore'):\n obs_copy_bool = obs_copy < 0\n sim_copy_bool = sim_copy < 0\n\n if obs_copy_bool.any() or sim_copy_bool.any():\n neg_indices_fcst = ~sim_copy_bool\n neg_indices_obs = ~obs_copy_bool\n all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)\n\n warnings.warn(\"Row(s) {} contained negative values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_neg_indices)[0]),\n UserWarning)\n\n obs_copy = obs_copy[all_treatment_array]\n sim_copy = sim_copy[all_treatment_array]\n\n return sim_copy, obs_copy\n"
] | # -*- coding: utf-8 -*-
"""
HydroErr contains a library of goodness of fit metrics that measure hydrologic skill.
Each metric is contained in function, and every function has the parameters to treat missing values as
well as remove zero and negative values from the timeseries data.
Each function contains two properties, name and abbr. These can be used in the Hydrostats package when creating tables
and adding metrics to the plots. Link to the hydrostats package: https://github.com/BYU-Hydroinformatics/Hydrostats.
An example of this functionality is shown below.
>>> import HydroErr as he
>>>
>>> he.acc.name
'Anomaly Correlation Coefficient'
>>> he.acc.abbr
'ACC'
"""
from __future__ import division
import numpy as np
from scipy.stats import gmean, rankdata
import warnings
__all__ = ['me', 'mae', 'mse', 'mle', 'male', 'msle', 'mde', 'mdae', 'mdse', 'ed', 'ned', 'rmse',
'rmsle', 'nrmse_range', 'nrmse_mean', 'nrmse_iqr', 'irmse', 'mase', 'r_squared',
'pearson_r', 'spearman_r', 'acc', 'mape', 'mapd', 'maape', 'smape1', 'smape2', 'd', 'd1',
'dmod', 'drel', 'dr', 'watt_m', 'mb_r', 'nse', 'nse_mod', 'nse_rel', 'kge_2009',
'kge_2012', 'lm_index', 'd1_p', 've', 'sa', 'sc', 'sid', 'sga', 'h1_mhe', 'h1_mahe',
'h1_rmshe', 'h2_mhe', 'h2_mahe', 'h2_rmshe', 'h3_mhe', 'h3_mahe', 'h3_rmshe', 'h4_mhe',
'h4_mahe', 'h4_rmshe', 'h5_mhe', 'h5_mahe', 'h5_rmshe', 'h6_mhe', 'h6_mahe', 'h6_rmshe',
'h7_mhe', 'h7_mahe', 'h7_rmshe', 'h8_mhe', 'h8_mahe', 'h8_rmshe', 'h10_mhe', 'h10_mahe',
'h10_rmshe', 'g_mean_diff', 'mean_var']
####################################################################################################
# General and Hydrological Error Metrics #
####################################################################################################
def me(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean error of the simulated and observed data.
.. image:: /pictures/ME.png
**Range:** -inf < MAE < inf, data units, closer to zero is better, indicates bias.
**Notes:** The mean error (ME) measures the difference between the simulated data and the
observed data. For the mean error, a smaller number indicates a better fit to the original
data. Note that if the error is in the form of random noise, the mean error will be very small,
which can skew the accuracy of this metric. ME is cumulative and will be small even if there
are large positive and negative errors that balance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean error value.
Examples
--------
Note that in this example the random noise cancels, leaving a very small ME.
>>> import HydroErr as he
>>> import numpy as np
>>> # Seed for reproducibility
>>> np.random.seed(54839)
>>> x = np.arange(100) / 20
>>> sim = np.sin(x) + 2
>>> obs = sim * (((np.random.rand(100) - 0.5) / 10) + 1)
>>> he.me(sim, obs)
-0.006832220968967168
References
----------
- Fisher, R.A., 1920. A Mathematical Examination of the Methods of Determining the Accuracy of
an Observation by the Mean Error, and by the Mean Square Error. Monthly Notices of the Royal
Astronomical Society 80 758 - 770.
"""
# Treating missing values
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero)
return np.mean(simulated_array - observed_array)
def mae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute error of the simulated and observed data.
.. image:: /pictures/MAE.png
**Range:** 0 ≤ MAE < inf, data units, smaller is better.
**Notes:** The ME measures the absolute difference between the simulated data and the observed
data. For the mean abolute error, a smaller number indicates a better fit to the original data.
Also note that random errors do not cancel. Also referred to as an L1-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute error value.
References
----------
- Willmott, Cort J., and Kenji Matsuura. “Advantages of the Mean Absolute Error (MAE) over the
Root Mean Square Error (RMSE) in Assessing Average Model Performance.” Climate Research 30,
no. 1 (2005): 79–82.
- Willmott, Cort J., and Kenji Matsuura. “On the Use of Dimensioned Measures of Error to
Evaluate the Performance of Spatial Interpolators.” International Journal of Geographical
Information Science 20, no. 1 (2006): 89–102.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mae(sim, obs)
0.5666666666666665
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean(np.absolute(simulated_array - observed_array))
def mse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared error of the simulated and observed data.
.. image:: /pictures/MSE.png
**Range:** 0 ≤ MSE < inf, data units squared, smaller is better.
**Notes:** Random errors do not cancel, highlights larger errors, also referred to as a
squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mse(sim, obs)
0.4333333333333333
References
----------
- Wang, Zhou, and Alan C. Bovik. “Mean Squared Error: Love It or Leave It? A New Look at Signal
Fidelity Measures.” IEEE Signal Processing Magazine 26, no. 1 (2009): 98–117.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean((simulated_array - observed_array) ** 2)
def mle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean log error of the simulated and observed data.
.. image:: /pictures/MLE.png
**Range:** -inf < MLE < inf, data units, closer to zero is better.
**Notes** Same as the mean erro (ME) only use log ratios as the error term. Limits the impact of outliers, more
evenly weights high and low data values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mle(sim, obs)
0.002961767058151136
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(sim_log - obs_log)
def male(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean absolute log error of the simulated and observed data.
.. image:: /pictures/MALE.png
**Range:** 0 ≤ MALE < inf, data units squared, smaller is better.
**Notes** Same as MAE only use log ratios as the error term. Limits the impact of outliers,
more evenly weights high and low flows.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.male(sim, obs), 6)
0.090417
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(np.abs(sim_log - obs_log))
def msle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared log error of the simulated and observed data.
.. image:: /pictures/MSLE.png
**Range:** 0 ≤ MSLE < inf, data units squared, smaller is better.
**Notes** Same as the mean squared error (MSE) only use log ratios as the error term. Limits
the impact of outliers, more evenly weights high and low values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.msle(sim, obs), 6)
0.010426
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean((sim_log - obs_log) ** 2)
def mde(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median error (MdE) between the simulated and observed data.
.. image:: /pictures/MdE.png
**Range** -inf < MdE < inf, closer to zero is better.
**Notes** This metric indicates bias. It is similar to the mean error (ME), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mde(sim, obs)
-0.10000000000000009
Returns
-------
float
The median error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(simulated_array - observed_array)
def mdae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median absolute error (MdAE) between the simulated and observed data.
.. image:: /pictures/MdAE.png
**Range** 0 ≤ MdAE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean absolute error (MAE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdae(sim, obs)
0.75
Returns
-------
float
The median absolute error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(np.abs(simulated_array - observed_array))
def mdse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median squared error (MdSE) between the simulated and observed data.
.. image:: /pictures/MdSE.png
**Range** 0 ≤ MdSE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean squared error (MSE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdse(sim, obs)
0.625
Returns
-------
float
The median squared error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median((simulated_array - observed_array) ** 2)
def ed(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Euclidean distance between predicted and observed values in vector space.
.. image:: /pictures/ED.png
**Range** 0 ≤ ED < inf, smaller is better.
**Notes** Also sometimes referred to as the L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ed(sim, obs)
1.63707055437449
Returns
-------
float
The euclidean distance error value.
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.linalg.norm(observed_array - simulated_array)
def ned(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the normalized Euclidian distance between the simulated and observed data in vector
space.
.. image:: /pictures/NED.png
**Range** 0 ≤ NED < inf, smaller is better.
**Notes** Also sometimes referred to as the squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The normalized euclidean distance value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ned(sim, obs)
0.2872053604165771
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array / np.mean(observed_array)
b = simulated_array / np.mean(simulated_array)
return np.linalg.norm(a - b)
def rmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square error between the simulated and observed data.
.. image:: /pictures/RMSE.png
**Range** 0 ≤ RMSE < inf, smaller is better.
**Notes:** The standard deviation of the residuals. A lower spread indicates that the points
are better concentrated around the line of best fit (linear). Random errors do not cancel.
This metric will highlights larger errors.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.rmse(sim, obs)
0.668331255192114
References
----------
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.sqrt(np.mean((simulated_array - observed_array) ** 2))
def rmsle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square log error between the simulated and observed data.
.. image:: /pictures/RMSLE.png
**Range:** 0 ≤ RMSLE < inf. Smaller is better, and it does not indicate bias.
**Notes:** Random errors do not cancel while using this metric. This metric limits the
impact of outliers by more evenly weighting high and low values. To calculate the log values,
each value in the observed and simulated array is increased by one unit in order to avoid
run-time errors and nan values (function np.log1p).
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square log error value.
Examples
--------
Notice that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.rmsle(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
"""
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf, remove_neg=remove_neg,
remove_zero=remove_zero)
return np.sqrt(np.mean(np.power(np.log1p(simulated_array) - np.log1p(observed_array), 2)))
def nrmse_range(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the range normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Range.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the range of the observed time series (x).
Normalizing allows comparison between data sets with different scales. The NRMSErange is the
most sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The range normalized root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_range(sim, obs)
0.0891108340256152
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_max = np.max(observed_array)
obs_min = np.min(observed_array)
return rmse_value / (obs_max - obs_min)
def nrmse_mean(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Mean.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the mean of the observed time series (x).
Normalizing allows comparison between data sets with different scales.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_mean(sim, obs)
0.11725109740212526
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_mean = np.mean(observed_array)
return rmse_value / obs_mean
def nrmse_iqr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the IQR normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_IQR.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the interquartile range of the observed time
series (x). Normalizing allows comparison between data sets with different scales.
The NRMSEquartile is the least sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The IQR normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_iqr(sim, obs)
0.2595461185212093
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
q1 = np.percentile(observed_array, 25)
q3 = np.percentile(observed_array, 75)
iqr = q3 - q1
return rmse_value / iqr
def irmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the inertial root mean square error (IRMSE) between the simulated and observed data.
.. image:: /pictures/IRMSE.png
**Range:** 0 ≤ IRMSE < inf, lower is better.
**Notes:** This metric is the RMSE devided by by the standard deviation of the gradient of the
observed timeseries data. This metric is meant to be help understand the ability of the model
to predict changes in observation.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The inertial root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.irmse(sim, obs)
0.14572738134831856
References
----------
- Daga, M., Deo, M.C., 2009. Alternative data-driven methods to estimate wind from waves by
inverse modeling. Natural Hazards 49(2) 293-310.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Getting the gradient of the observed data
obs_len = observed_array.size
obs_grad = observed_array[1:obs_len] - observed_array[0:obs_len - 1]
# Standard deviation of the gradient
obs_grad_std = np.std(obs_grad, ddof=1)
# Divide RMSE by the standard deviation of the gradient of the observed data
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
return rmse_value / obs_grad_std
def mase(simulated_array, observed_array, m=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute scaled error between the simulated and observed data.
.. image:: /pictures/MASE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
m: int
If given, indicates the seasonal period m. If not given, the default is 1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute scaled error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mase(sim, obs)
0.17341040462427745
References
----------
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
start = m
end = simulated_array.size - m
a = np.mean(np.abs(simulated_array - observed_array))
b = np.abs(observed_array[start:observed_array.size] - observed_array[:end])
return a / (np.sum(b) / end)
def pearson_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the pearson correlation coefficient.
.. image:: /pictures/R_pearson.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The pearson r coefficient measures linear correlation. It is sensitive to outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Pearson correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.pearson_r(sim, obs)
0.9610793632835262
References
----------
- Pearson, K. (1895). Note on regression and inheritance in the case of two parents.
Proceedings of the Royal Society of London, 58, 240-242.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
top = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1 = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2 = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
return top / (bot1 * bot2)
def spearman_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the spearman rank correlation coefficient.
.. image:: /pictures/R_spearman.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The spearman r coefficient measures the monotonic relation between simulated and
observed data. Because it uses a nonparametric measure of rank correlation, it is less sensitive
to outliers compared to the Pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spearman rank correlation coefficient.
Examples
----------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.spearman_r(sim, obs)
0.942857142857143
References
----------
- Spearman C (1904). "The proof and measurement of association between two things". American
Journal of Psychology. 15: 72–101. doi:10.2307/1412159
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rank_sim = rankdata(simulated_array)
rank_obs = rankdata(observed_array)
mean_rank_sim = np.mean(rank_sim)
mean_rank_obs = np.mean(rank_obs)
top = np.mean((rank_obs - mean_rank_obs) * (rank_sim - mean_rank_sim))
bot = np.sqrt(
np.mean((rank_obs - mean_rank_obs) ** 2) * np.mean((rank_sim - mean_rank_sim) ** 2))
return top / bot
def r_squared(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Coefficient of Determination (r2).
.. image:: /pictures/r2.png
**Range:** 0 ≤ r2 ≤ 1. 1 indicates perfect correlation, 0 indicates complete randomness.
**Notes:** The Coefficient of Determination measures the linear relation between simulated and
observed data. Because it is the pearson correlation coefficient squared, it is more heavily
affected by outliers than the pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The coefficient of determination (R^2).
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.r_squared(sim, obs)
0.9236735425294681
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array - np.mean(observed_array)
b = simulated_array - np.mean(simulated_array)
return (np.sum(a * b)) ** 2 / (np.sum(a ** 2) * np.sum(b ** 2))
def acc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the anomaly correlation coefficient (ACC).
.. image:: /pictures/ACC.png
**Range:** -1 ≤ ACC ≤ 1. -1 indicates perfect negative correlation of the variation
pattern of the anomalies, 0 indicates complete randomness of the variation patterns of the
anomalies, 1 indicates perfect correlation of the variation pattern of the anomalies.
**Notes:** Common measure in the verification of spatial fields. Measures the correlation
between the variation pattern of the simulated data compared to the observed data.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The anomaly correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.acc(sim, obs)
0.8008994694029383
References
----------
- Langland, Rolf H., and Ryan N. Maue. “Recent Northern Hemisphere Mid-Latitude Medium-Range
Deterministic Forecast Skill.” Tellus A: Dynamic Meteorology and Oceanography 64,
no. 1 (2012): 17531.
- Miyakoda, K., G. D. Hembree, R. F. Strickler, and I. Shulman. “Cumulative Results of Extended
Forecast Experiments I. Model Performance for Winter Cases.” Monthly Weather Review 100, no.
12(1972): 836–55.
- Murphy, Allan H., and Edward S. Epstein. “Skill Scores and Correlation Coefficients in Model
Verification.” Monthly Weather Review 117, no. 3 (1989): 572–82.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - np.mean(simulated_array)
b = observed_array - np.mean(observed_array)
c = np.std(observed_array, ddof=1) * np.std(simulated_array, ddof=1) * simulated_array.size
return np.dot(a, b / c)
def mape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the mean absolute percentage error (MAPE).
.. image:: /pictures/MAPE.png
**Range:** 0% ≤ MAPE ≤ inf. 0% indicates perfect correlation, a larger error indicates a
larger percent error in the data.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
c = 100 / simulated_array.size
return c * np.sum(b)
def mapd(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the mean absolute percentage deviation (MAPD).
.. image:: /pictures/MAPD.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage deviation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mapd(sim, obs)
0.10526315789473682
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(np.abs(observed_array))
return a / b
def maape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the Mean Arctangent Absolute Percentage Error (MAAPE).
.. image:: /pictures/MAAPE.png
**Range:** 0 ≤ MAAPE < π/2, does not indicate bias, smaller is better.
**Notes:** Represents the mean absolute error as a percentage of the observed values. Handles
0s in the observed data. This metric is not as biased as MAPE by under-over predictions.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean arctangent absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
- Kim, S., Kim, H., 2016. A new metric of absolute percentage error for intermittent demand
forecasts. International Journal of Forecasting 32(3) 669-679.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
return np.mean(np.arctan(b))
def smape1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (1) (SMAPE1).
.. image:: /pictures/SMAPE1.png
**Range:** 0 ≤ SMAPE1 < 100%, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (1).
Examples
--------
Note that if we switch the simulated and observed arrays the result is the same
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape1(sim, obs)
5.871915694397428
>>> he.smape1(obs, sim)
5.871915694397428
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 100 / simulated_array.size
b = np.abs(simulated_array - observed_array)
c = np.abs(simulated_array) + np.abs(observed_array)
return a * np.sum(b / c)
def smape2(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (2) (SMAPE2).
.. image:: /pictures/SMAPE2.png
**Range:** 0 ≤ SMAPE1 < 200%, does not indicate bias, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE with only positive metric values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (2).
Examples
--------
Note that switching the simulated and observed arrays yields the same results
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape2(sim, obs)
11.743831388794856
>>> he.smape2(obs, sim)
11.743831388794856
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = (simulated_array + observed_array) / 2
c = 100 / simulated_array.size
return c * np.sum(np.abs(a / b))
def d(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d).
.. image:: /pictures/d.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d(sim, obs)
0.978477353035657
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (observed_array - simulated_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
return 1 - (np.sum(a) / np.sum((b + c) ** 2))
def d1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d1).
.. image:: /pictures/d1.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric. Compared
to the other index of agreement (d) it has a reduced impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (d1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1(sim, obs)
0.8434782608695652
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
obs_mean = np.mean(observed_array)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.abs(simulated_array - obs_mean)
c = np.abs(observed_array - obs_mean)
return 1 - np.sum(a) / np.sum(b + c)
def dr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the refined index of agreement (dr).
.. image:: /pictures/dr.png
**Range:** -1 ≤ dr < 1, does not indicate bias, larger is better.
**Notes:** Reformulation of Willmott’s index of agreement. This metric was created to address
issues in the index of agreement and the Nash-Sutcliffe efficiency metric. Meant to be a
flexible metric for use in climatology.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The refined index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dr(sim, obs)
0.847457627118644
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = 2 * np.sum(np.abs(observed_array - observed_array.mean()))
if a <= b:
return 1 - (a / b)
else:
return (b / a) - 1
def drel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the relative index of agreement (drel).
.. image:: /pictures/drel.png
**Range:** 0 ≤ drel < 1, does not indicate bias, larger is better.
**Notes:** Instead of absolute differences, this metric uses relative differences.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.drel(sim, obs)
0.9740868625579597
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = ((simulated_array - observed_array) / observed_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = ((b + c) / np.mean(observed_array)) ** 2
return 1 - (np.sum(a) / np.sum(e))
def dmod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the modified index of agreement (dmod).
.. image:: /pictures/dmod.png
**Range:** 0 ≤ dmod < 1, does not indicate bias, larger is better.
**Notes:** When j=1, this metric is the same as d1. As j becomes larger, outliers have a larger
impact on the value.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
Optional input indicating the j values desired. A higher j places more emphasis on
outliers. j is 1 by default.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified index of agreement.
Examples
--------
Note that using the default is the same as calculating the d1 metric. Changing the value of j
modification of the metric.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dmod(sim, obs) # Same as d1
0.8434782608695652
>>> he.dmod(sim, obs, j=1.5)
0.9413310986805733
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = (b + c) ** j
return 1 - (np.sum(a) / np.sum(e))
def watt_m(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute Watterson's M (M).
.. image:: /pictures/M.png
**Range:** -1 ≤ M < 1, does not indicate bias, larger is better.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
Watterson's M value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.watt_m(sim, obs)
0.8307913876595929
References
----------
- Watterson, I.G., 1996. Non‐dimensional measures of climate model performance. International
Journal of Climatology 16(4) 379-391.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 2 / np.pi
b = np.mean((simulated_array - observed_array) ** 2) # MSE
c = np.std(observed_array, ddof=1) ** 2 + np.std(simulated_array, ddof=1) ** 2
e = (np.mean(simulated_array) - np.mean(observed_array)) ** 2
f = c + e
return a * np.arcsin(1 - (b / f))
def mb_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute Mielke-Berry R value (MB R).
.. image:: /pictures/MB_R.png
**Range:** 0 ≤ MB R < 1, does not indicate bias, larger is better.
**Notes:** Compares prediction to probability it arose by chance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Mielke-Berry R value.
Notes
-----
If a more optimized version is desired, the `numba package <http://numba.pydata.org/doc.html>`_ can be implemented
for a much more optimized performance when computing this metric. An example is given below.
>>> from numba import njit, prange
>>> @njit(parallel=True, fastmath=True)
>>> def mb_par_fastmath(pred, obs): # uses LLVM compiler
>>> assert pred.size == obs.size
>>> n = pred.size
>>> tot = 0.0
>>> mae = 0.0
>>> for i in range(n):
>>> for j in prange(n):
>>> tot += abs(pred[i] - obs[j])
>>> mae += abs(pred[i] - obs[i])
>>> mae = mae / n
>>> mb = 1 - ((n ** 2) * mae / tot)
>>>
>>> return mb
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mb_r(sim, obs)
0.7726315789473684
References
----------
- Berry, K.J., Mielke, P.W., 1988. A Generalization of Cohen's Kappa Agreement Measure to
Interval Measurement and Multiple Raters. Educational and Psychological Measurement 48(4)
921-933.
- Mielke, P.W., Berry, K.J., 2007. Permutation methods: a distance function approach.
Springer Science & Business Media.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Calculate metric
n = simulated_array.size
tot = 0.0
for i in range(n):
tot = tot + np.sum(np.abs(simulated_array - observed_array[i]))
mae_val = np.sum(np.abs(simulated_array - observed_array)) / n
mb = 1 - ((n ** 2) * mae_val / tot)
return mb
def nse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Nash-Sutcliffe Efficiency.
.. image:: /pictures/NSE.png
**Range:** -inf < NSE < 1, does not indicate bias, larger is better.
**Notes:** The Nash-Sutcliffe efficiency metric compares prediction values to naive predictions
(i.e. average value). One major flaw of this metric is that it punishes a higher variance in
the observed values (denominator). This metric is analogous to the mean absolute error skill
score (MAESS) using the mean flow as a benchmark.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Nash-Sutcliffe Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse(sim, obs)
0.922093023255814
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
- McCuen, R.H., Knight, Z., Cutter, A.G., 2006. Evaluation of the Nash-Sutcliffe Efficiency
Index. Journal of Hydraulic Engineering.
- Nash, J.E., Sutcliffe, J.V., 1970. River flow forecasting through conceptual models part
I — A discussion of principles. Journal of Hydrology 282-290.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** 2
b = (np.abs(observed_array - np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def nse_mod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the modified Nash-Sutcliffe efficiency (NSE mod).
.. image:: /pictures/NSEmod.png
**Range:** -inf < NSE (mod) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
If given, sets the value of j to the input. j is 1 by default. A higher j gives more
emphasis to outliers
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_mod(sim, obs)
0.6949152542372882
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = (np.abs(observed_array - np.mean(observed_array))) ** j
return 1 - (np.sum(a) / np.sum(b))
def nse_rel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the relative Nash-Sutcliffe efficiency (NSE rel).
.. image:: /pictures/NSErel.png
**Range:** -inf < NSE (rel) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_rel(sim, obs)
0.9062004687708474
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs((simulated_array - observed_array) / observed_array)) ** 2
b = (np.abs((observed_array - np.mean(observed_array)) / np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def kge_2009(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""Compute the Kling-Gupta efficiency (2009).
.. image:: /pictures/KGE_2009.png
**Range:** -inf < KGE (2009) < 1, larger is better.
**Notes:** Gupta et al. (2009) created this metric to demonstrate the relative importance of
the three components of the NSE, which are correlation, bias and variability. This was done
with hydrologic modeling as the context. This metric is meant to address issues with the NSE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), Alpha, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, alpha, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2009) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2009(sim, obs)
0.912223072345668
>>> he.kge_2009(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.927910707932087, 1.0058823529411764, 0.9181073779138655)
References
----------
- Gupta, H. V., Kling, H., Yilmaz, K. K., & Martinez, G. F. (2009). Decomposition of the mean
squared error and NSE performance criteria: Implications for improving hydrological modelling.
Journal of Hydrology, 377(1-2), 80-91.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array, ddof=1)
obs_sigma = np.std(observed_array, ddof=1)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
if obs_mean != 0:
beta = sim_mean / obs_mean
else:
beta = np.nan
# Relative variability between simulated and observed values
if obs_sigma != 0:
alpha = sim_sigma / obs_sigma
else:
alpha = np.nan
if not np.isnan(beta) and not np.isnan(alpha):
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (alpha - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Alpha is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, alpha, beta, kge
else:
return kge
def kge_2012(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""
Compute the Kling-Gupta efficiency (2012).
.. image:: /pictures/KGE_2012.png
**Range:** -inf < KGE (2012) < 1, does not indicate bias, larger is better.
**Notes:** The modified version of the KGE (2009). Kling proposed this version to avoid
cross-correlation between bias and variability ratios.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), gamma, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, gamma, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2012) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2012(sim, obs)
0.9122230723456678
>>> he.kge_2012(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.9224843295231272, 1.0058823529411764, 0.9132923608280753)
References
----------
- Kling, H., Fuchs, M., & Paulin, M. (2012). Runoff conditions in the upper Danube basin under
an ensemble of climate change scenarios. Journal of Hydrology, 424, 264-277.
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array)
obs_sigma = np.std(observed_array)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
beta = sim_mean / obs_mean
# CV is the coefficient of variation (standard deviation / mean)
sim_cv = sim_sigma / sim_mean
obs_cv = obs_sigma / obs_mean
# Variability Ratio, or the ratio of simulated CV to observed CV
gam = sim_cv / obs_cv
if obs_mean != 0 and obs_sigma != 0 and sim_mean != 0:
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (gam - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
if sim_mean == 0:
warnings.warn(
'Warning: The simulated data mean is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, gam, beta, kge
else:
return kge
def lm_index(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""
Compute the Legate-McCabe Efficiency Index.
.. image:: /pictures/E1p.png
**Range:** 0 ≤ E1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.lm_index(sim, obs)
0.6949152542372882
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
mean_obs = np.mean(observed_array)
if obs_bar_p is not None:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def d1_p(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""Compute the Legate-McCabe Index of Agreement.
.. image:: /pictures/D1p.png
**Range:** 0 ≤ d1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1_p(sim, obs)
0.8434782608695652
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
if obs_bar_p is not None:
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - obs_bar_p) + np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
mean_obs = np.mean(observed_array)
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - mean_obs) + np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def ve(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Volumetric Efficiency (VE).
.. image:: /pictures/VE.png
**Range:** 0 ≤ VE < 1 smaller is better, does not indicate bias.
**Notes:** Represents the error as a percentage of flow.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Volumetric Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ve(sim, obs)
0.8947368421052632
References
----------
- Criss, R.E., Winston, W.E., 2008. Do Nash values have value? Discussion and alternate
proposals. Hydrological Processes 22(14) 2723.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(observed_array)
return 1 - (a / b)
def sa(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Angle (SA).
.. image:: /pictures/SA.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral angle metric measures the angle between the two vectors in hyperspace.
It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Angle value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sa(sim, obs)
0.10816831366492945
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(simulated_array, observed_array)
b = np.linalg.norm(simulated_array) * np.linalg.norm(observed_array)
return np.arccos(a / b)
def sc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Correlation (SC).
.. image:: /pictures/SC.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral correlation metric measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Correlation value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sc(sim, obs)
0.27991341383646606
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(observed_array - np.mean(observed_array), simulated_array - np.mean(simulated_array))
b = np.linalg.norm(observed_array - np.mean(observed_array))
c = np.linalg.norm(simulated_array - np.mean(simulated_array))
e = b * c
return np.arccos(a / e)
def sid(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Information Divergence (SID).
.. image:: /pictures/SID.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral information divergence measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral information divergence value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sid(sim, obs)
0.03517616895318012
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
first = (observed_array / np.mean(observed_array)) - (
simulated_array / np.mean(simulated_array))
second1 = np.log10(observed_array) - np.log10(np.mean(observed_array))
second2 = np.log10(simulated_array) - np.log10(np.mean(simulated_array))
return np.dot(first, second1 - second2)
def sga(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Gradient Angle (SGA).
.. image:: /pictures/SGA.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral gradient angle measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
SG is the gradient of the simulated or observed time series.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Gradient Angle.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sga(sim, obs)
0.26764286472739834
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sgx = observed_array[1:] - observed_array[:observed_array.size - 1]
sgy = simulated_array[1:] - simulated_array[:simulated_array.size - 1]
a = np.dot(sgx, sgy)
b = np.linalg.norm(sgx) * np.linalg.norm(sgy)
return np.arccos(a / b)
####################################################################################################
# H Metrics: Methods from Tornqvist L, Vartia P, and Vartia YO. (1985) #
####################################################################################################
def h1_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the H1 mean error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mhe(sim, obs)
0.002106551840594386
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(h)
def h1_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H1 absolute error.
.. image:: /pictures/H1.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The H1 absolute error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mahe(sim, obs)
0.11639226612630865
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(np.abs(h))
def h1_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H1 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean squared H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_rmshe(sim, obs)
0.12865571253672756
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.sqrt(np.mean(h ** 2))
def h2_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean error.
.. image:: /pictures/H2.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mhe(sim, obs)
-0.015319829424307036
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(h)
def h2_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean absolute error.
.. image:: /pictures/H2.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mahe(sim, obs)
0.11997591408039167
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(np.abs(h))
def h2_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_rmshe(sim, obs)
0.1373586680669673
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.sqrt(np.mean(h ** 2))
def h3_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 mean error.
.. image:: /pictures/H3.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mhe(sim, obs)
-0.006322019630356533
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(h)
def h3_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H3 mean absolute error.
.. image:: /pictures/H3.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mahe(sim, obs)
0.11743831388794855
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(np.abs(h))
def h3_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 root mean square error.
.. image:: /pictures/H3.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.sqrt(np.mean(h ** 2))
def h4_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mhe(sim, obs)
-0.0064637371129817
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(h)
def h4_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H4 mean absolute error.
.. image:: /pictures/H4.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mahe(sim, obs)
0.11781032209144082
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(np.abs(h))
def h4_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_rmshe(sim, obs)
0.13200901963465006
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.sqrt(np.mean(h ** 2))
def h5_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean error.
.. image:: /pictures/H5.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mhe(sim, obs)
-0.006606638791856322
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(h)
def h5_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean absolute error.
.. image:: /pictures/H5.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mahe(sim, obs)
0.11818409010335018
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(np.abs(h))
def h5_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 root mean square error.
.. image:: /pictures/H5.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_rmshe(sim, obs)
0.13254476469410933
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h6_mhe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H6 mean error.
.. image:: /pictures/H6.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mhe(sim, obs)
-0.006322019630356514
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(h)
def h6_mahe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""Compute the H6 mean absolute error.
.. image:: /pictures/H6.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mahe(sim, obs)
0.11743831388794852
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(np.abs(h))
def h6_rmshe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the H6 root mean square error.
.. image:: /pictures/H6.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h7_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean error.
.. image:: /pictures/H7.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mhe(sim, obs)
0.0026331898007430263
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(h)
def h7_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean absolute error.
.. image:: /pictures/H7.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mahe(sim, obs)
0.14549033265788583
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(np.abs(h))
def h7_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 root mean square error.
.. image:: /pictures/H7.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_rmshe(sim, obs)
0.16081964067090945
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
def h8_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H8 mean error.
.. image:: /pictures/H8.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mhe(sim, obs)
0.0018056158633666466
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(h)
def h8_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 mean absolute error.
.. image:: /pictures/H8.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mahe(sim, obs)
0.099764799536836
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(np.abs(h))
def h8_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 root mean square error.
.. image:: /pictures/H8.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_rmshe(sim, obs)
0.11027632503148076
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
# def h9(simulated_array, observed_array, h_type='mhe', k=1):
# h = (simulated_array / observed_array - 1) / \
# np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
# if h_type == 'mhe':
# return h.mean()
# elif h_type == 'ahe':
# return np.abs(h).mean()
# elif h_type == 'rmshe':
# return np.sqrt((h**2).mean())
# else:
# raise RuntimeError("The three types available are 'mhe', 'ahe', and 'rmshe'.")
def h10_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean error.
.. image:: /pictures/H10.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h10_mhe(sim, obs)
-0.0012578676058971154
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(h)
def h10_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean absolute error.
.. image:: /pictures/H10.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_mahe(sim, obs), 6)
0.094636
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(np.abs(h))
def h10_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 root mean square error.
.. image:: /pictures/H10.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_rmshe(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.sqrt(np.mean(h ** 2))
###################################################################################################
# Statistical Error Metrics for Distribution Testing #
###################################################################################################
def g_mean_diff(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the geometric mean difference.
.. image:: /pictures/GMD.png
**Range:**
**Notes:** For the difference of geometric means, the geometric mean is computed for each of
two samples then their difference is taken.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The geometric mean difference value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.g_mean_diff(sim, obs)
0.988855412098022
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.exp(gmean(sim_log) - gmean(obs_log))
def mean_var(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the mean variance.
.. image:: /pictures/MV.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean variance.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.mean_var(sim, obs), 6)
0.010641
References
----------
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.var(np.log1p(observed_array) - np.log1p(simulated_array))
####################################################################################################
# HELPER FUNCTIONS AND API INFORMATION #
####################################################################################################
metric_names = [
'Mean Error', 'Mean Absolute Error', 'Mean Squared Error', 'Mean Log Error',
'Mean Absolute Log Error', 'Mean Squared Log Error', 'Median Error', 'Median Absolute Error',
'Median Squared Error', 'Eclidean Distance', 'Normalized Eclidean Distance',
'Root Mean Square Error', 'Root Mean Squared Log Error',
'Normalized Root Mean Square Error - Range', 'Normalized Root Mean Square Error - Mean',
'Normalized Root Mean Square Error - IQR', 'Inertial Root Mean Square Error',
'Mean Absolute Scaled Error', 'Coefficient of Determination', 'Pearson Correlation Coefficient',
'Spearman Rank Correlation Coefficient', 'Anomaly Correlation Coefficient',
'Mean Absolute Percentage Error', 'Mean Absolute Percentage Deviation',
'Mean Arctangent Absolute Percentage Error', 'Symmetric Mean Absolute Percentage Error (1)',
'Symmetric Mean Absolute Percentage Error (2)', 'Index of Agreement (d)',
'Index of Agreement (d1)', 'Modified Index of Agreement', 'Relative Index of Agreement',
'Index of Agreement Refined (dr)', "Watterson's M", 'Mielke-Berry R',
'Nash-Sutcliffe Efficiency', 'Modified Nash-Sutcliffe Efficiency',
'Relative Nash-Sutcliffe Efficiency', 'Kling-Gupta Efficiency (2009)',
'Kling-Gupta Efficiency (2012)', 'Legate-McCabe Efficiency Index',
'Legate-McCabe Index of Agreement', 'Volumetric Efficiency', 'Spectral Angle',
'Spectral Correlation', 'Spectral Information Divergence', 'Spectral Gradient Angle',
'Mean H1 Error', 'Mean Absolute H1 Error', 'Root Mean Square H1 Error', 'Mean H2 Error',
'Mean Absolute H2 Error', 'Root Mean Square H2 Error', 'Mean H3 Error',
'Mean Absolute H3 Error', 'Root Mean Square H3 Error', 'Mean H4 Error',
'Mean Absolute H4 Error', 'Root Mean Square H4 Error', 'Mean H5 Error',
'Mean Absolute H5 Error', 'Root Mean Square H5 Error', 'Mean H6 Error',
'Mean Absolute H6 Error', 'Root Mean Square H6 Error', 'Mean H7 Error',
'Mean Absolute H7 Error', 'Root Mean Square H7 Error', 'Mean H8 Error',
'Mean Absolute H8 Error', 'Root Mean Square H8 Error', 'Mean H10 Error',
'Mean Absolute H10 Error', 'Root Mean Square H10 Error', 'Geometric Mean Difference',
'Mean Variance'
]
metric_abbr = [
'ME', 'MAE', 'MSE', 'MLE', 'MALE', 'MSLE', 'MdE', 'MdAE', 'MdSE', 'ED', 'NED', 'RMSE', 'RMSLE',
'NRMSE (Range)', 'NRMSE (Mean)', 'NRMSE (IQR)', 'IRMSE', 'MASE', 'r2', 'R (Pearson)',
'R (Spearman)', 'ACC', 'MAPE', 'MAPD', 'MAAPE', 'SMAPE1', 'SMAPE2', 'd', 'd1', 'd (Mod.)',
'd (Rel.)', 'dr', 'M', '(MB) R', 'NSE', 'NSE (Mod.)', 'NSE (Rel.)', 'KGE (2009)', 'KGE (2012)',
"E1'", "D1'", 'VE', 'SA', 'SC', 'SID', 'SGA', 'H1 (MHE)', 'H1 (MAHE)', 'H1 (RMSHE)', 'H2 (MHE)',
'H2 (MAHE)', 'H2 (RMSHE)', 'H3 (MHE)', 'H3 (MAHE)', 'H3 (RMSHE)', 'H4 (MHE)', 'H4 (MAHE)',
'H4 (RMSHE)', 'H5 (MHE)', 'H5 (MAHE)', 'H5 (RMSHE)', 'H6 (MHE)', 'H6 (MAHE)', 'H6 (RMSHE)',
'H7 (MHE)', 'H7 (MAHE)', 'H7 (RMSHE)', 'H8 (MHE)', 'H8 (MAHE)', 'H8 (RMSHE)', 'H10 (MHE)',
'H10 (MAHE)', 'H10 (RMSHE)', 'GMD', 'MV'
]
function_list = [
me, mae, mse, mle, male, msle, mde, mdae, mdse, ed, ned, rmse, rmsle, nrmse_range, nrmse_mean,
nrmse_iqr, irmse, mase, r_squared, pearson_r, spearman_r, acc, mape, mapd, maape, smape1,
smape2, d, d1, dmod, drel, dr, watt_m, mb_r, nse, nse_mod, nse_rel, kge_2009, kge_2012,
lm_index, d1_p, ve, sa, sc, sid, sga, h1_mhe, h1_mahe, h1_rmshe, h2_mhe, h2_mahe, h2_rmshe,
h3_mhe, h3_mahe, h3_rmshe, h4_mhe, h4_mahe, h4_rmshe, h5_mhe, h5_mahe, h5_rmshe, h6_mhe,
h6_mahe, h6_rmshe, h7_mhe, h7_mahe, h7_rmshe, h8_mhe, h8_mahe, h8_rmshe, h10_mhe, h10_mahe,
h10_rmshe, g_mean_diff, mean_var,
]
# Assign some properties to each function for ease of use for users
for i in range(len(function_list)):
function_list[i].name = metric_names[i]
function_list[i].abbr = metric_abbr[i]
def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Removes the nan, negative, and inf values in two numpy arrays"""
sim_copy = np.copy(simulated_array)
obs_copy = np.copy(observed_array)
# Checking to see if the vectors are the same length
assert sim_copy.ndim == 1, "The simulated array is not one dimensional."
assert obs_copy.ndim == 1, "The observed array is not one dimensional."
if sim_copy.size != obs_copy.size:
raise RuntimeError("The two ndarrays are not the same size.")
# Treat missing data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain nan values
all_treatment_array = np.ones(obs_copy.size, dtype=bool)
if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_nan = np.isnan(sim_copy)
obs_nan = np.isnan(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_nan] = replace_nan
obs_copy[obs_nan] = replace_nan
warnings.warn("Elements(s) {} contained NaN values in the simulated array and "
"elements(s) {} contained NaN values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_nan)[0],
np.where(obs_nan)[0]),
UserWarning)
else:
# Getting the indices of the nan values, combining them, and informing user.
nan_indices_fcst = ~np.isnan(sim_copy)
nan_indices_obs = ~np.isnan(obs_copy)
all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)
warnings.warn("Row(s) {} contained NaN values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_nan_indices)[0]),
UserWarning)
if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_inf = np.isinf(sim_copy)
obs_inf = np.isinf(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_inf] = replace_inf
obs_copy[obs_inf] = replace_inf
warnings.warn("Elements(s) {} contained Inf values in the simulated array and "
"elements(s) {} contained Inf values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_inf)[0],
np.where(obs_inf)[0]),
UserWarning)
else:
inf_indices_fcst = ~(np.isinf(sim_copy))
inf_indices_obs = ~np.isinf(obs_copy)
all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)
warnings.warn(
"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows "
"are zero indexed).".format(np.where(~all_inf_indices)[0]),
UserWarning
)
# Treat zero data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain zero values
if remove_zero:
if (obs_copy == 0).any() or (sim_copy == 0).any():
zero_indices_fcst = ~(sim_copy == 0)
zero_indices_obs = ~(obs_copy == 0)
all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)
warnings.warn(
"Row(s) {} contained zero values and the row(s) have been removed (Rows are "
"zero indexed).".format(np.where(~all_zero_indices)[0]),
UserWarning
)
# Treat negative data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain negative values
# Ignore runtime warnings from comparing
if remove_neg:
with np.errstate(invalid='ignore'):
obs_copy_bool = obs_copy < 0
sim_copy_bool = sim_copy < 0
if obs_copy_bool.any() or sim_copy_bool.any():
neg_indices_fcst = ~sim_copy_bool
neg_indices_obs = ~obs_copy_bool
all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)
warnings.warn("Row(s) {} contained negative values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_neg_indices)[0]),
UserWarning)
obs_copy = obs_copy[all_treatment_array]
sim_copy = sim_copy[all_treatment_array]
return sim_copy, obs_copy
if __name__ == "__main__":
pass
|
BYU-Hydroinformatics/HydroErr | HydroErr/HydroErr.py | nrmse_mean | python | def nrmse_mean(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_mean = np.mean(observed_array)
return rmse_value / obs_mean | Compute the mean normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Mean.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the mean of the observed time series (x).
Normalizing allows comparison between data sets with different scales.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_mean(sim, obs)
0.11725109740212526
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142. | train | https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L1124-L1200 | [
"def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,\n remove_neg=False, remove_zero=False):\n \"\"\"Removes the nan, negative, and inf values in two numpy arrays\"\"\"\n sim_copy = np.copy(simulated_array)\n obs_copy = np.copy(observed_array)\n\n # Checking to see if the vectors are the same length\n assert sim_copy.ndim == 1, \"The simulated array is not one dimensional.\"\n assert obs_copy.ndim == 1, \"The observed array is not one dimensional.\"\n\n if sim_copy.size != obs_copy.size:\n raise RuntimeError(\"The two ndarrays are not the same size.\")\n\n # Treat missing data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain nan values\n all_treatment_array = np.ones(obs_copy.size, dtype=bool)\n\n if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_nan = np.isnan(sim_copy)\n obs_nan = np.isnan(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_nan] = replace_nan\n obs_copy[obs_nan] = replace_nan\n\n warnings.warn(\"Elements(s) {} contained NaN values in the simulated array and \"\n \"elements(s) {} contained NaN values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_nan)[0],\n np.where(obs_nan)[0]),\n UserWarning)\n else:\n # Getting the indices of the nan values, combining them, and informing user.\n nan_indices_fcst = ~np.isnan(sim_copy)\n nan_indices_obs = ~np.isnan(obs_copy)\n all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)\n\n warnings.warn(\"Row(s) {} contained NaN values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_nan_indices)[0]),\n UserWarning)\n\n if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_inf = np.isinf(sim_copy)\n obs_inf = np.isinf(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_inf] = replace_inf\n obs_copy[obs_inf] = replace_inf\n\n warnings.warn(\"Elements(s) {} contained Inf values in the simulated array and \"\n \"elements(s) {} contained Inf values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_inf)[0],\n np.where(obs_inf)[0]),\n UserWarning)\n else:\n inf_indices_fcst = ~(np.isinf(sim_copy))\n inf_indices_obs = ~np.isinf(obs_copy)\n all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)\n\n warnings.warn(\n \"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows \"\n \"are zero indexed).\".format(np.where(~all_inf_indices)[0]),\n UserWarning\n )\n\n # Treat zero data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain zero values\n if remove_zero:\n if (obs_copy == 0).any() or (sim_copy == 0).any():\n zero_indices_fcst = ~(sim_copy == 0)\n zero_indices_obs = ~(obs_copy == 0)\n all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)\n\n warnings.warn(\n \"Row(s) {} contained zero values and the row(s) have been removed (Rows are \"\n \"zero indexed).\".format(np.where(~all_zero_indices)[0]),\n UserWarning\n )\n\n # Treat negative data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain negative values\n\n # Ignore runtime warnings from comparing\n if remove_neg:\n with np.errstate(invalid='ignore'):\n obs_copy_bool = obs_copy < 0\n sim_copy_bool = sim_copy < 0\n\n if obs_copy_bool.any() or sim_copy_bool.any():\n neg_indices_fcst = ~sim_copy_bool\n neg_indices_obs = ~obs_copy_bool\n all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)\n\n warnings.warn(\"Row(s) {} contained negative values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_neg_indices)[0]),\n UserWarning)\n\n obs_copy = obs_copy[all_treatment_array]\n sim_copy = sim_copy[all_treatment_array]\n\n return sim_copy, obs_copy\n"
] | # -*- coding: utf-8 -*-
"""
HydroErr contains a library of goodness of fit metrics that measure hydrologic skill.
Each metric is contained in function, and every function has the parameters to treat missing values as
well as remove zero and negative values from the timeseries data.
Each function contains two properties, name and abbr. These can be used in the Hydrostats package when creating tables
and adding metrics to the plots. Link to the hydrostats package: https://github.com/BYU-Hydroinformatics/Hydrostats.
An example of this functionality is shown below.
>>> import HydroErr as he
>>>
>>> he.acc.name
'Anomaly Correlation Coefficient'
>>> he.acc.abbr
'ACC'
"""
from __future__ import division
import numpy as np
from scipy.stats import gmean, rankdata
import warnings
__all__ = ['me', 'mae', 'mse', 'mle', 'male', 'msle', 'mde', 'mdae', 'mdse', 'ed', 'ned', 'rmse',
'rmsle', 'nrmse_range', 'nrmse_mean', 'nrmse_iqr', 'irmse', 'mase', 'r_squared',
'pearson_r', 'spearman_r', 'acc', 'mape', 'mapd', 'maape', 'smape1', 'smape2', 'd', 'd1',
'dmod', 'drel', 'dr', 'watt_m', 'mb_r', 'nse', 'nse_mod', 'nse_rel', 'kge_2009',
'kge_2012', 'lm_index', 'd1_p', 've', 'sa', 'sc', 'sid', 'sga', 'h1_mhe', 'h1_mahe',
'h1_rmshe', 'h2_mhe', 'h2_mahe', 'h2_rmshe', 'h3_mhe', 'h3_mahe', 'h3_rmshe', 'h4_mhe',
'h4_mahe', 'h4_rmshe', 'h5_mhe', 'h5_mahe', 'h5_rmshe', 'h6_mhe', 'h6_mahe', 'h6_rmshe',
'h7_mhe', 'h7_mahe', 'h7_rmshe', 'h8_mhe', 'h8_mahe', 'h8_rmshe', 'h10_mhe', 'h10_mahe',
'h10_rmshe', 'g_mean_diff', 'mean_var']
####################################################################################################
# General and Hydrological Error Metrics #
####################################################################################################
def me(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean error of the simulated and observed data.
.. image:: /pictures/ME.png
**Range:** -inf < MAE < inf, data units, closer to zero is better, indicates bias.
**Notes:** The mean error (ME) measures the difference between the simulated data and the
observed data. For the mean error, a smaller number indicates a better fit to the original
data. Note that if the error is in the form of random noise, the mean error will be very small,
which can skew the accuracy of this metric. ME is cumulative and will be small even if there
are large positive and negative errors that balance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean error value.
Examples
--------
Note that in this example the random noise cancels, leaving a very small ME.
>>> import HydroErr as he
>>> import numpy as np
>>> # Seed for reproducibility
>>> np.random.seed(54839)
>>> x = np.arange(100) / 20
>>> sim = np.sin(x) + 2
>>> obs = sim * (((np.random.rand(100) - 0.5) / 10) + 1)
>>> he.me(sim, obs)
-0.006832220968967168
References
----------
- Fisher, R.A., 1920. A Mathematical Examination of the Methods of Determining the Accuracy of
an Observation by the Mean Error, and by the Mean Square Error. Monthly Notices of the Royal
Astronomical Society 80 758 - 770.
"""
# Treating missing values
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero)
return np.mean(simulated_array - observed_array)
def mae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute error of the simulated and observed data.
.. image:: /pictures/MAE.png
**Range:** 0 ≤ MAE < inf, data units, smaller is better.
**Notes:** The ME measures the absolute difference between the simulated data and the observed
data. For the mean abolute error, a smaller number indicates a better fit to the original data.
Also note that random errors do not cancel. Also referred to as an L1-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute error value.
References
----------
- Willmott, Cort J., and Kenji Matsuura. “Advantages of the Mean Absolute Error (MAE) over the
Root Mean Square Error (RMSE) in Assessing Average Model Performance.” Climate Research 30,
no. 1 (2005): 79–82.
- Willmott, Cort J., and Kenji Matsuura. “On the Use of Dimensioned Measures of Error to
Evaluate the Performance of Spatial Interpolators.” International Journal of Geographical
Information Science 20, no. 1 (2006): 89–102.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mae(sim, obs)
0.5666666666666665
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean(np.absolute(simulated_array - observed_array))
def mse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared error of the simulated and observed data.
.. image:: /pictures/MSE.png
**Range:** 0 ≤ MSE < inf, data units squared, smaller is better.
**Notes:** Random errors do not cancel, highlights larger errors, also referred to as a
squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mse(sim, obs)
0.4333333333333333
References
----------
- Wang, Zhou, and Alan C. Bovik. “Mean Squared Error: Love It or Leave It? A New Look at Signal
Fidelity Measures.” IEEE Signal Processing Magazine 26, no. 1 (2009): 98–117.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean((simulated_array - observed_array) ** 2)
def mle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean log error of the simulated and observed data.
.. image:: /pictures/MLE.png
**Range:** -inf < MLE < inf, data units, closer to zero is better.
**Notes** Same as the mean erro (ME) only use log ratios as the error term. Limits the impact of outliers, more
evenly weights high and low data values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mle(sim, obs)
0.002961767058151136
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(sim_log - obs_log)
def male(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean absolute log error of the simulated and observed data.
.. image:: /pictures/MALE.png
**Range:** 0 ≤ MALE < inf, data units squared, smaller is better.
**Notes** Same as MAE only use log ratios as the error term. Limits the impact of outliers,
more evenly weights high and low flows.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.male(sim, obs), 6)
0.090417
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(np.abs(sim_log - obs_log))
def msle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared log error of the simulated and observed data.
.. image:: /pictures/MSLE.png
**Range:** 0 ≤ MSLE < inf, data units squared, smaller is better.
**Notes** Same as the mean squared error (MSE) only use log ratios as the error term. Limits
the impact of outliers, more evenly weights high and low values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.msle(sim, obs), 6)
0.010426
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean((sim_log - obs_log) ** 2)
def mde(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median error (MdE) between the simulated and observed data.
.. image:: /pictures/MdE.png
**Range** -inf < MdE < inf, closer to zero is better.
**Notes** This metric indicates bias. It is similar to the mean error (ME), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mde(sim, obs)
-0.10000000000000009
Returns
-------
float
The median error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(simulated_array - observed_array)
def mdae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median absolute error (MdAE) between the simulated and observed data.
.. image:: /pictures/MdAE.png
**Range** 0 ≤ MdAE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean absolute error (MAE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdae(sim, obs)
0.75
Returns
-------
float
The median absolute error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(np.abs(simulated_array - observed_array))
def mdse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median squared error (MdSE) between the simulated and observed data.
.. image:: /pictures/MdSE.png
**Range** 0 ≤ MdSE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean squared error (MSE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdse(sim, obs)
0.625
Returns
-------
float
The median squared error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median((simulated_array - observed_array) ** 2)
def ed(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Euclidean distance between predicted and observed values in vector space.
.. image:: /pictures/ED.png
**Range** 0 ≤ ED < inf, smaller is better.
**Notes** Also sometimes referred to as the L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ed(sim, obs)
1.63707055437449
Returns
-------
float
The euclidean distance error value.
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.linalg.norm(observed_array - simulated_array)
def ned(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the normalized Euclidian distance between the simulated and observed data in vector
space.
.. image:: /pictures/NED.png
**Range** 0 ≤ NED < inf, smaller is better.
**Notes** Also sometimes referred to as the squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The normalized euclidean distance value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ned(sim, obs)
0.2872053604165771
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array / np.mean(observed_array)
b = simulated_array / np.mean(simulated_array)
return np.linalg.norm(a - b)
def rmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square error between the simulated and observed data.
.. image:: /pictures/RMSE.png
**Range** 0 ≤ RMSE < inf, smaller is better.
**Notes:** The standard deviation of the residuals. A lower spread indicates that the points
are better concentrated around the line of best fit (linear). Random errors do not cancel.
This metric will highlights larger errors.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.rmse(sim, obs)
0.668331255192114
References
----------
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.sqrt(np.mean((simulated_array - observed_array) ** 2))
def rmsle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square log error between the simulated and observed data.
.. image:: /pictures/RMSLE.png
**Range:** 0 ≤ RMSLE < inf. Smaller is better, and it does not indicate bias.
**Notes:** Random errors do not cancel while using this metric. This metric limits the
impact of outliers by more evenly weighting high and low values. To calculate the log values,
each value in the observed and simulated array is increased by one unit in order to avoid
run-time errors and nan values (function np.log1p).
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square log error value.
Examples
--------
Notice that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.rmsle(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
"""
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf, remove_neg=remove_neg,
remove_zero=remove_zero)
return np.sqrt(np.mean(np.power(np.log1p(simulated_array) - np.log1p(observed_array), 2)))
def nrmse_range(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the range normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Range.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the range of the observed time series (x).
Normalizing allows comparison between data sets with different scales. The NRMSErange is the
most sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The range normalized root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_range(sim, obs)
0.0891108340256152
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_max = np.max(observed_array)
obs_min = np.min(observed_array)
return rmse_value / (obs_max - obs_min)
def nrmse_mean(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Mean.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the mean of the observed time series (x).
Normalizing allows comparison between data sets with different scales.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_mean(sim, obs)
0.11725109740212526
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_mean = np.mean(observed_array)
return rmse_value / obs_mean
def nrmse_iqr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the IQR normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_IQR.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the interquartile range of the observed time
series (x). Normalizing allows comparison between data sets with different scales.
The NRMSEquartile is the least sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The IQR normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_iqr(sim, obs)
0.2595461185212093
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
q1 = np.percentile(observed_array, 25)
q3 = np.percentile(observed_array, 75)
iqr = q3 - q1
return rmse_value / iqr
def irmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the inertial root mean square error (IRMSE) between the simulated and observed data.
.. image:: /pictures/IRMSE.png
**Range:** 0 ≤ IRMSE < inf, lower is better.
**Notes:** This metric is the RMSE devided by by the standard deviation of the gradient of the
observed timeseries data. This metric is meant to be help understand the ability of the model
to predict changes in observation.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The inertial root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.irmse(sim, obs)
0.14572738134831856
References
----------
- Daga, M., Deo, M.C., 2009. Alternative data-driven methods to estimate wind from waves by
inverse modeling. Natural Hazards 49(2) 293-310.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Getting the gradient of the observed data
obs_len = observed_array.size
obs_grad = observed_array[1:obs_len] - observed_array[0:obs_len - 1]
# Standard deviation of the gradient
obs_grad_std = np.std(obs_grad, ddof=1)
# Divide RMSE by the standard deviation of the gradient of the observed data
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
return rmse_value / obs_grad_std
def mase(simulated_array, observed_array, m=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute scaled error between the simulated and observed data.
.. image:: /pictures/MASE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
m: int
If given, indicates the seasonal period m. If not given, the default is 1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute scaled error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mase(sim, obs)
0.17341040462427745
References
----------
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
start = m
end = simulated_array.size - m
a = np.mean(np.abs(simulated_array - observed_array))
b = np.abs(observed_array[start:observed_array.size] - observed_array[:end])
return a / (np.sum(b) / end)
def pearson_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the pearson correlation coefficient.
.. image:: /pictures/R_pearson.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The pearson r coefficient measures linear correlation. It is sensitive to outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Pearson correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.pearson_r(sim, obs)
0.9610793632835262
References
----------
- Pearson, K. (1895). Note on regression and inheritance in the case of two parents.
Proceedings of the Royal Society of London, 58, 240-242.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
top = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1 = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2 = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
return top / (bot1 * bot2)
def spearman_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the spearman rank correlation coefficient.
.. image:: /pictures/R_spearman.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The spearman r coefficient measures the monotonic relation between simulated and
observed data. Because it uses a nonparametric measure of rank correlation, it is less sensitive
to outliers compared to the Pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spearman rank correlation coefficient.
Examples
----------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.spearman_r(sim, obs)
0.942857142857143
References
----------
- Spearman C (1904). "The proof and measurement of association between two things". American
Journal of Psychology. 15: 72–101. doi:10.2307/1412159
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rank_sim = rankdata(simulated_array)
rank_obs = rankdata(observed_array)
mean_rank_sim = np.mean(rank_sim)
mean_rank_obs = np.mean(rank_obs)
top = np.mean((rank_obs - mean_rank_obs) * (rank_sim - mean_rank_sim))
bot = np.sqrt(
np.mean((rank_obs - mean_rank_obs) ** 2) * np.mean((rank_sim - mean_rank_sim) ** 2))
return top / bot
def r_squared(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Coefficient of Determination (r2).
.. image:: /pictures/r2.png
**Range:** 0 ≤ r2 ≤ 1. 1 indicates perfect correlation, 0 indicates complete randomness.
**Notes:** The Coefficient of Determination measures the linear relation between simulated and
observed data. Because it is the pearson correlation coefficient squared, it is more heavily
affected by outliers than the pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The coefficient of determination (R^2).
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.r_squared(sim, obs)
0.9236735425294681
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array - np.mean(observed_array)
b = simulated_array - np.mean(simulated_array)
return (np.sum(a * b)) ** 2 / (np.sum(a ** 2) * np.sum(b ** 2))
def acc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the anomaly correlation coefficient (ACC).
.. image:: /pictures/ACC.png
**Range:** -1 ≤ ACC ≤ 1. -1 indicates perfect negative correlation of the variation
pattern of the anomalies, 0 indicates complete randomness of the variation patterns of the
anomalies, 1 indicates perfect correlation of the variation pattern of the anomalies.
**Notes:** Common measure in the verification of spatial fields. Measures the correlation
between the variation pattern of the simulated data compared to the observed data.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The anomaly correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.acc(sim, obs)
0.8008994694029383
References
----------
- Langland, Rolf H., and Ryan N. Maue. “Recent Northern Hemisphere Mid-Latitude Medium-Range
Deterministic Forecast Skill.” Tellus A: Dynamic Meteorology and Oceanography 64,
no. 1 (2012): 17531.
- Miyakoda, K., G. D. Hembree, R. F. Strickler, and I. Shulman. “Cumulative Results of Extended
Forecast Experiments I. Model Performance for Winter Cases.” Monthly Weather Review 100, no.
12(1972): 836–55.
- Murphy, Allan H., and Edward S. Epstein. “Skill Scores and Correlation Coefficients in Model
Verification.” Monthly Weather Review 117, no. 3 (1989): 572–82.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - np.mean(simulated_array)
b = observed_array - np.mean(observed_array)
c = np.std(observed_array, ddof=1) * np.std(simulated_array, ddof=1) * simulated_array.size
return np.dot(a, b / c)
def mape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the mean absolute percentage error (MAPE).
.. image:: /pictures/MAPE.png
**Range:** 0% ≤ MAPE ≤ inf. 0% indicates perfect correlation, a larger error indicates a
larger percent error in the data.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
c = 100 / simulated_array.size
return c * np.sum(b)
def mapd(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the mean absolute percentage deviation (MAPD).
.. image:: /pictures/MAPD.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage deviation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mapd(sim, obs)
0.10526315789473682
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(np.abs(observed_array))
return a / b
def maape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the Mean Arctangent Absolute Percentage Error (MAAPE).
.. image:: /pictures/MAAPE.png
**Range:** 0 ≤ MAAPE < π/2, does not indicate bias, smaller is better.
**Notes:** Represents the mean absolute error as a percentage of the observed values. Handles
0s in the observed data. This metric is not as biased as MAPE by under-over predictions.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean arctangent absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
- Kim, S., Kim, H., 2016. A new metric of absolute percentage error for intermittent demand
forecasts. International Journal of Forecasting 32(3) 669-679.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
return np.mean(np.arctan(b))
def smape1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (1) (SMAPE1).
.. image:: /pictures/SMAPE1.png
**Range:** 0 ≤ SMAPE1 < 100%, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (1).
Examples
--------
Note that if we switch the simulated and observed arrays the result is the same
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape1(sim, obs)
5.871915694397428
>>> he.smape1(obs, sim)
5.871915694397428
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 100 / simulated_array.size
b = np.abs(simulated_array - observed_array)
c = np.abs(simulated_array) + np.abs(observed_array)
return a * np.sum(b / c)
def smape2(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (2) (SMAPE2).
.. image:: /pictures/SMAPE2.png
**Range:** 0 ≤ SMAPE1 < 200%, does not indicate bias, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE with only positive metric values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (2).
Examples
--------
Note that switching the simulated and observed arrays yields the same results
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape2(sim, obs)
11.743831388794856
>>> he.smape2(obs, sim)
11.743831388794856
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = (simulated_array + observed_array) / 2
c = 100 / simulated_array.size
return c * np.sum(np.abs(a / b))
def d(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d).
.. image:: /pictures/d.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d(sim, obs)
0.978477353035657
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (observed_array - simulated_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
return 1 - (np.sum(a) / np.sum((b + c) ** 2))
def d1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d1).
.. image:: /pictures/d1.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric. Compared
to the other index of agreement (d) it has a reduced impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (d1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1(sim, obs)
0.8434782608695652
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
obs_mean = np.mean(observed_array)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.abs(simulated_array - obs_mean)
c = np.abs(observed_array - obs_mean)
return 1 - np.sum(a) / np.sum(b + c)
def dr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the refined index of agreement (dr).
.. image:: /pictures/dr.png
**Range:** -1 ≤ dr < 1, does not indicate bias, larger is better.
**Notes:** Reformulation of Willmott’s index of agreement. This metric was created to address
issues in the index of agreement and the Nash-Sutcliffe efficiency metric. Meant to be a
flexible metric for use in climatology.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The refined index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dr(sim, obs)
0.847457627118644
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = 2 * np.sum(np.abs(observed_array - observed_array.mean()))
if a <= b:
return 1 - (a / b)
else:
return (b / a) - 1
def drel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the relative index of agreement (drel).
.. image:: /pictures/drel.png
**Range:** 0 ≤ drel < 1, does not indicate bias, larger is better.
**Notes:** Instead of absolute differences, this metric uses relative differences.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.drel(sim, obs)
0.9740868625579597
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = ((simulated_array - observed_array) / observed_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = ((b + c) / np.mean(observed_array)) ** 2
return 1 - (np.sum(a) / np.sum(e))
def dmod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the modified index of agreement (dmod).
.. image:: /pictures/dmod.png
**Range:** 0 ≤ dmod < 1, does not indicate bias, larger is better.
**Notes:** When j=1, this metric is the same as d1. As j becomes larger, outliers have a larger
impact on the value.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
Optional input indicating the j values desired. A higher j places more emphasis on
outliers. j is 1 by default.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified index of agreement.
Examples
--------
Note that using the default is the same as calculating the d1 metric. Changing the value of j
modification of the metric.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dmod(sim, obs) # Same as d1
0.8434782608695652
>>> he.dmod(sim, obs, j=1.5)
0.9413310986805733
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = (b + c) ** j
return 1 - (np.sum(a) / np.sum(e))
def watt_m(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute Watterson's M (M).
.. image:: /pictures/M.png
**Range:** -1 ≤ M < 1, does not indicate bias, larger is better.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
Watterson's M value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.watt_m(sim, obs)
0.8307913876595929
References
----------
- Watterson, I.G., 1996. Non‐dimensional measures of climate model performance. International
Journal of Climatology 16(4) 379-391.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 2 / np.pi
b = np.mean((simulated_array - observed_array) ** 2) # MSE
c = np.std(observed_array, ddof=1) ** 2 + np.std(simulated_array, ddof=1) ** 2
e = (np.mean(simulated_array) - np.mean(observed_array)) ** 2
f = c + e
return a * np.arcsin(1 - (b / f))
def mb_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute Mielke-Berry R value (MB R).
.. image:: /pictures/MB_R.png
**Range:** 0 ≤ MB R < 1, does not indicate bias, larger is better.
**Notes:** Compares prediction to probability it arose by chance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Mielke-Berry R value.
Notes
-----
If a more optimized version is desired, the `numba package <http://numba.pydata.org/doc.html>`_ can be implemented
for a much more optimized performance when computing this metric. An example is given below.
>>> from numba import njit, prange
>>> @njit(parallel=True, fastmath=True)
>>> def mb_par_fastmath(pred, obs): # uses LLVM compiler
>>> assert pred.size == obs.size
>>> n = pred.size
>>> tot = 0.0
>>> mae = 0.0
>>> for i in range(n):
>>> for j in prange(n):
>>> tot += abs(pred[i] - obs[j])
>>> mae += abs(pred[i] - obs[i])
>>> mae = mae / n
>>> mb = 1 - ((n ** 2) * mae / tot)
>>>
>>> return mb
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mb_r(sim, obs)
0.7726315789473684
References
----------
- Berry, K.J., Mielke, P.W., 1988. A Generalization of Cohen's Kappa Agreement Measure to
Interval Measurement and Multiple Raters. Educational and Psychological Measurement 48(4)
921-933.
- Mielke, P.W., Berry, K.J., 2007. Permutation methods: a distance function approach.
Springer Science & Business Media.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Calculate metric
n = simulated_array.size
tot = 0.0
for i in range(n):
tot = tot + np.sum(np.abs(simulated_array - observed_array[i]))
mae_val = np.sum(np.abs(simulated_array - observed_array)) / n
mb = 1 - ((n ** 2) * mae_val / tot)
return mb
def nse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Nash-Sutcliffe Efficiency.
.. image:: /pictures/NSE.png
**Range:** -inf < NSE < 1, does not indicate bias, larger is better.
**Notes:** The Nash-Sutcliffe efficiency metric compares prediction values to naive predictions
(i.e. average value). One major flaw of this metric is that it punishes a higher variance in
the observed values (denominator). This metric is analogous to the mean absolute error skill
score (MAESS) using the mean flow as a benchmark.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Nash-Sutcliffe Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse(sim, obs)
0.922093023255814
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
- McCuen, R.H., Knight, Z., Cutter, A.G., 2006. Evaluation of the Nash-Sutcliffe Efficiency
Index. Journal of Hydraulic Engineering.
- Nash, J.E., Sutcliffe, J.V., 1970. River flow forecasting through conceptual models part
I — A discussion of principles. Journal of Hydrology 282-290.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** 2
b = (np.abs(observed_array - np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def nse_mod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the modified Nash-Sutcliffe efficiency (NSE mod).
.. image:: /pictures/NSEmod.png
**Range:** -inf < NSE (mod) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
If given, sets the value of j to the input. j is 1 by default. A higher j gives more
emphasis to outliers
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_mod(sim, obs)
0.6949152542372882
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = (np.abs(observed_array - np.mean(observed_array))) ** j
return 1 - (np.sum(a) / np.sum(b))
def nse_rel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the relative Nash-Sutcliffe efficiency (NSE rel).
.. image:: /pictures/NSErel.png
**Range:** -inf < NSE (rel) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_rel(sim, obs)
0.9062004687708474
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs((simulated_array - observed_array) / observed_array)) ** 2
b = (np.abs((observed_array - np.mean(observed_array)) / np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def kge_2009(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""Compute the Kling-Gupta efficiency (2009).
.. image:: /pictures/KGE_2009.png
**Range:** -inf < KGE (2009) < 1, larger is better.
**Notes:** Gupta et al. (2009) created this metric to demonstrate the relative importance of
the three components of the NSE, which are correlation, bias and variability. This was done
with hydrologic modeling as the context. This metric is meant to address issues with the NSE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), Alpha, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, alpha, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2009) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2009(sim, obs)
0.912223072345668
>>> he.kge_2009(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.927910707932087, 1.0058823529411764, 0.9181073779138655)
References
----------
- Gupta, H. V., Kling, H., Yilmaz, K. K., & Martinez, G. F. (2009). Decomposition of the mean
squared error and NSE performance criteria: Implications for improving hydrological modelling.
Journal of Hydrology, 377(1-2), 80-91.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array, ddof=1)
obs_sigma = np.std(observed_array, ddof=1)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
if obs_mean != 0:
beta = sim_mean / obs_mean
else:
beta = np.nan
# Relative variability between simulated and observed values
if obs_sigma != 0:
alpha = sim_sigma / obs_sigma
else:
alpha = np.nan
if not np.isnan(beta) and not np.isnan(alpha):
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (alpha - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Alpha is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, alpha, beta, kge
else:
return kge
def kge_2012(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""
Compute the Kling-Gupta efficiency (2012).
.. image:: /pictures/KGE_2012.png
**Range:** -inf < KGE (2012) < 1, does not indicate bias, larger is better.
**Notes:** The modified version of the KGE (2009). Kling proposed this version to avoid
cross-correlation between bias and variability ratios.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), gamma, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, gamma, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2012) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2012(sim, obs)
0.9122230723456678
>>> he.kge_2012(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.9224843295231272, 1.0058823529411764, 0.9132923608280753)
References
----------
- Kling, H., Fuchs, M., & Paulin, M. (2012). Runoff conditions in the upper Danube basin under
an ensemble of climate change scenarios. Journal of Hydrology, 424, 264-277.
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array)
obs_sigma = np.std(observed_array)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
beta = sim_mean / obs_mean
# CV is the coefficient of variation (standard deviation / mean)
sim_cv = sim_sigma / sim_mean
obs_cv = obs_sigma / obs_mean
# Variability Ratio, or the ratio of simulated CV to observed CV
gam = sim_cv / obs_cv
if obs_mean != 0 and obs_sigma != 0 and sim_mean != 0:
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (gam - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
if sim_mean == 0:
warnings.warn(
'Warning: The simulated data mean is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, gam, beta, kge
else:
return kge
def lm_index(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""
Compute the Legate-McCabe Efficiency Index.
.. image:: /pictures/E1p.png
**Range:** 0 ≤ E1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.lm_index(sim, obs)
0.6949152542372882
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
mean_obs = np.mean(observed_array)
if obs_bar_p is not None:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def d1_p(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""Compute the Legate-McCabe Index of Agreement.
.. image:: /pictures/D1p.png
**Range:** 0 ≤ d1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1_p(sim, obs)
0.8434782608695652
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
if obs_bar_p is not None:
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - obs_bar_p) + np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
mean_obs = np.mean(observed_array)
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - mean_obs) + np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def ve(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Volumetric Efficiency (VE).
.. image:: /pictures/VE.png
**Range:** 0 ≤ VE < 1 smaller is better, does not indicate bias.
**Notes:** Represents the error as a percentage of flow.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Volumetric Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ve(sim, obs)
0.8947368421052632
References
----------
- Criss, R.E., Winston, W.E., 2008. Do Nash values have value? Discussion and alternate
proposals. Hydrological Processes 22(14) 2723.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(observed_array)
return 1 - (a / b)
def sa(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Angle (SA).
.. image:: /pictures/SA.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral angle metric measures the angle between the two vectors in hyperspace.
It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Angle value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sa(sim, obs)
0.10816831366492945
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(simulated_array, observed_array)
b = np.linalg.norm(simulated_array) * np.linalg.norm(observed_array)
return np.arccos(a / b)
def sc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Correlation (SC).
.. image:: /pictures/SC.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral correlation metric measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Correlation value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sc(sim, obs)
0.27991341383646606
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(observed_array - np.mean(observed_array), simulated_array - np.mean(simulated_array))
b = np.linalg.norm(observed_array - np.mean(observed_array))
c = np.linalg.norm(simulated_array - np.mean(simulated_array))
e = b * c
return np.arccos(a / e)
def sid(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Information Divergence (SID).
.. image:: /pictures/SID.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral information divergence measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral information divergence value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sid(sim, obs)
0.03517616895318012
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
first = (observed_array / np.mean(observed_array)) - (
simulated_array / np.mean(simulated_array))
second1 = np.log10(observed_array) - np.log10(np.mean(observed_array))
second2 = np.log10(simulated_array) - np.log10(np.mean(simulated_array))
return np.dot(first, second1 - second2)
def sga(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Gradient Angle (SGA).
.. image:: /pictures/SGA.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral gradient angle measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
SG is the gradient of the simulated or observed time series.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Gradient Angle.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sga(sim, obs)
0.26764286472739834
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sgx = observed_array[1:] - observed_array[:observed_array.size - 1]
sgy = simulated_array[1:] - simulated_array[:simulated_array.size - 1]
a = np.dot(sgx, sgy)
b = np.linalg.norm(sgx) * np.linalg.norm(sgy)
return np.arccos(a / b)
####################################################################################################
# H Metrics: Methods from Tornqvist L, Vartia P, and Vartia YO. (1985) #
####################################################################################################
def h1_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the H1 mean error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mhe(sim, obs)
0.002106551840594386
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(h)
def h1_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H1 absolute error.
.. image:: /pictures/H1.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The H1 absolute error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mahe(sim, obs)
0.11639226612630865
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(np.abs(h))
def h1_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H1 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean squared H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_rmshe(sim, obs)
0.12865571253672756
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.sqrt(np.mean(h ** 2))
def h2_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean error.
.. image:: /pictures/H2.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mhe(sim, obs)
-0.015319829424307036
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(h)
def h2_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean absolute error.
.. image:: /pictures/H2.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mahe(sim, obs)
0.11997591408039167
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(np.abs(h))
def h2_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_rmshe(sim, obs)
0.1373586680669673
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.sqrt(np.mean(h ** 2))
def h3_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 mean error.
.. image:: /pictures/H3.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mhe(sim, obs)
-0.006322019630356533
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(h)
def h3_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H3 mean absolute error.
.. image:: /pictures/H3.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mahe(sim, obs)
0.11743831388794855
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(np.abs(h))
def h3_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 root mean square error.
.. image:: /pictures/H3.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.sqrt(np.mean(h ** 2))
def h4_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mhe(sim, obs)
-0.0064637371129817
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(h)
def h4_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H4 mean absolute error.
.. image:: /pictures/H4.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mahe(sim, obs)
0.11781032209144082
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(np.abs(h))
def h4_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_rmshe(sim, obs)
0.13200901963465006
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.sqrt(np.mean(h ** 2))
def h5_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean error.
.. image:: /pictures/H5.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mhe(sim, obs)
-0.006606638791856322
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(h)
def h5_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean absolute error.
.. image:: /pictures/H5.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mahe(sim, obs)
0.11818409010335018
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(np.abs(h))
def h5_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 root mean square error.
.. image:: /pictures/H5.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_rmshe(sim, obs)
0.13254476469410933
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h6_mhe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H6 mean error.
.. image:: /pictures/H6.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mhe(sim, obs)
-0.006322019630356514
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(h)
def h6_mahe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""Compute the H6 mean absolute error.
.. image:: /pictures/H6.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mahe(sim, obs)
0.11743831388794852
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(np.abs(h))
def h6_rmshe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the H6 root mean square error.
.. image:: /pictures/H6.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h7_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean error.
.. image:: /pictures/H7.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mhe(sim, obs)
0.0026331898007430263
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(h)
def h7_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean absolute error.
.. image:: /pictures/H7.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mahe(sim, obs)
0.14549033265788583
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(np.abs(h))
def h7_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 root mean square error.
.. image:: /pictures/H7.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_rmshe(sim, obs)
0.16081964067090945
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
def h8_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H8 mean error.
.. image:: /pictures/H8.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mhe(sim, obs)
0.0018056158633666466
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(h)
def h8_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 mean absolute error.
.. image:: /pictures/H8.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mahe(sim, obs)
0.099764799536836
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(np.abs(h))
def h8_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 root mean square error.
.. image:: /pictures/H8.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_rmshe(sim, obs)
0.11027632503148076
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
# def h9(simulated_array, observed_array, h_type='mhe', k=1):
# h = (simulated_array / observed_array - 1) / \
# np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
# if h_type == 'mhe':
# return h.mean()
# elif h_type == 'ahe':
# return np.abs(h).mean()
# elif h_type == 'rmshe':
# return np.sqrt((h**2).mean())
# else:
# raise RuntimeError("The three types available are 'mhe', 'ahe', and 'rmshe'.")
def h10_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean error.
.. image:: /pictures/H10.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h10_mhe(sim, obs)
-0.0012578676058971154
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(h)
def h10_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean absolute error.
.. image:: /pictures/H10.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_mahe(sim, obs), 6)
0.094636
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(np.abs(h))
def h10_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 root mean square error.
.. image:: /pictures/H10.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_rmshe(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.sqrt(np.mean(h ** 2))
###################################################################################################
# Statistical Error Metrics for Distribution Testing #
###################################################################################################
def g_mean_diff(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the geometric mean difference.
.. image:: /pictures/GMD.png
**Range:**
**Notes:** For the difference of geometric means, the geometric mean is computed for each of
two samples then their difference is taken.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The geometric mean difference value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.g_mean_diff(sim, obs)
0.988855412098022
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.exp(gmean(sim_log) - gmean(obs_log))
def mean_var(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the mean variance.
.. image:: /pictures/MV.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean variance.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.mean_var(sim, obs), 6)
0.010641
References
----------
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.var(np.log1p(observed_array) - np.log1p(simulated_array))
####################################################################################################
# HELPER FUNCTIONS AND API INFORMATION #
####################################################################################################
metric_names = [
'Mean Error', 'Mean Absolute Error', 'Mean Squared Error', 'Mean Log Error',
'Mean Absolute Log Error', 'Mean Squared Log Error', 'Median Error', 'Median Absolute Error',
'Median Squared Error', 'Eclidean Distance', 'Normalized Eclidean Distance',
'Root Mean Square Error', 'Root Mean Squared Log Error',
'Normalized Root Mean Square Error - Range', 'Normalized Root Mean Square Error - Mean',
'Normalized Root Mean Square Error - IQR', 'Inertial Root Mean Square Error',
'Mean Absolute Scaled Error', 'Coefficient of Determination', 'Pearson Correlation Coefficient',
'Spearman Rank Correlation Coefficient', 'Anomaly Correlation Coefficient',
'Mean Absolute Percentage Error', 'Mean Absolute Percentage Deviation',
'Mean Arctangent Absolute Percentage Error', 'Symmetric Mean Absolute Percentage Error (1)',
'Symmetric Mean Absolute Percentage Error (2)', 'Index of Agreement (d)',
'Index of Agreement (d1)', 'Modified Index of Agreement', 'Relative Index of Agreement',
'Index of Agreement Refined (dr)', "Watterson's M", 'Mielke-Berry R',
'Nash-Sutcliffe Efficiency', 'Modified Nash-Sutcliffe Efficiency',
'Relative Nash-Sutcliffe Efficiency', 'Kling-Gupta Efficiency (2009)',
'Kling-Gupta Efficiency (2012)', 'Legate-McCabe Efficiency Index',
'Legate-McCabe Index of Agreement', 'Volumetric Efficiency', 'Spectral Angle',
'Spectral Correlation', 'Spectral Information Divergence', 'Spectral Gradient Angle',
'Mean H1 Error', 'Mean Absolute H1 Error', 'Root Mean Square H1 Error', 'Mean H2 Error',
'Mean Absolute H2 Error', 'Root Mean Square H2 Error', 'Mean H3 Error',
'Mean Absolute H3 Error', 'Root Mean Square H3 Error', 'Mean H4 Error',
'Mean Absolute H4 Error', 'Root Mean Square H4 Error', 'Mean H5 Error',
'Mean Absolute H5 Error', 'Root Mean Square H5 Error', 'Mean H6 Error',
'Mean Absolute H6 Error', 'Root Mean Square H6 Error', 'Mean H7 Error',
'Mean Absolute H7 Error', 'Root Mean Square H7 Error', 'Mean H8 Error',
'Mean Absolute H8 Error', 'Root Mean Square H8 Error', 'Mean H10 Error',
'Mean Absolute H10 Error', 'Root Mean Square H10 Error', 'Geometric Mean Difference',
'Mean Variance'
]
metric_abbr = [
'ME', 'MAE', 'MSE', 'MLE', 'MALE', 'MSLE', 'MdE', 'MdAE', 'MdSE', 'ED', 'NED', 'RMSE', 'RMSLE',
'NRMSE (Range)', 'NRMSE (Mean)', 'NRMSE (IQR)', 'IRMSE', 'MASE', 'r2', 'R (Pearson)',
'R (Spearman)', 'ACC', 'MAPE', 'MAPD', 'MAAPE', 'SMAPE1', 'SMAPE2', 'd', 'd1', 'd (Mod.)',
'd (Rel.)', 'dr', 'M', '(MB) R', 'NSE', 'NSE (Mod.)', 'NSE (Rel.)', 'KGE (2009)', 'KGE (2012)',
"E1'", "D1'", 'VE', 'SA', 'SC', 'SID', 'SGA', 'H1 (MHE)', 'H1 (MAHE)', 'H1 (RMSHE)', 'H2 (MHE)',
'H2 (MAHE)', 'H2 (RMSHE)', 'H3 (MHE)', 'H3 (MAHE)', 'H3 (RMSHE)', 'H4 (MHE)', 'H4 (MAHE)',
'H4 (RMSHE)', 'H5 (MHE)', 'H5 (MAHE)', 'H5 (RMSHE)', 'H6 (MHE)', 'H6 (MAHE)', 'H6 (RMSHE)',
'H7 (MHE)', 'H7 (MAHE)', 'H7 (RMSHE)', 'H8 (MHE)', 'H8 (MAHE)', 'H8 (RMSHE)', 'H10 (MHE)',
'H10 (MAHE)', 'H10 (RMSHE)', 'GMD', 'MV'
]
function_list = [
me, mae, mse, mle, male, msle, mde, mdae, mdse, ed, ned, rmse, rmsle, nrmse_range, nrmse_mean,
nrmse_iqr, irmse, mase, r_squared, pearson_r, spearman_r, acc, mape, mapd, maape, smape1,
smape2, d, d1, dmod, drel, dr, watt_m, mb_r, nse, nse_mod, nse_rel, kge_2009, kge_2012,
lm_index, d1_p, ve, sa, sc, sid, sga, h1_mhe, h1_mahe, h1_rmshe, h2_mhe, h2_mahe, h2_rmshe,
h3_mhe, h3_mahe, h3_rmshe, h4_mhe, h4_mahe, h4_rmshe, h5_mhe, h5_mahe, h5_rmshe, h6_mhe,
h6_mahe, h6_rmshe, h7_mhe, h7_mahe, h7_rmshe, h8_mhe, h8_mahe, h8_rmshe, h10_mhe, h10_mahe,
h10_rmshe, g_mean_diff, mean_var,
]
# Assign some properties to each function for ease of use for users
for i in range(len(function_list)):
function_list[i].name = metric_names[i]
function_list[i].abbr = metric_abbr[i]
def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Removes the nan, negative, and inf values in two numpy arrays"""
sim_copy = np.copy(simulated_array)
obs_copy = np.copy(observed_array)
# Checking to see if the vectors are the same length
assert sim_copy.ndim == 1, "The simulated array is not one dimensional."
assert obs_copy.ndim == 1, "The observed array is not one dimensional."
if sim_copy.size != obs_copy.size:
raise RuntimeError("The two ndarrays are not the same size.")
# Treat missing data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain nan values
all_treatment_array = np.ones(obs_copy.size, dtype=bool)
if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_nan = np.isnan(sim_copy)
obs_nan = np.isnan(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_nan] = replace_nan
obs_copy[obs_nan] = replace_nan
warnings.warn("Elements(s) {} contained NaN values in the simulated array and "
"elements(s) {} contained NaN values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_nan)[0],
np.where(obs_nan)[0]),
UserWarning)
else:
# Getting the indices of the nan values, combining them, and informing user.
nan_indices_fcst = ~np.isnan(sim_copy)
nan_indices_obs = ~np.isnan(obs_copy)
all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)
warnings.warn("Row(s) {} contained NaN values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_nan_indices)[0]),
UserWarning)
if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_inf = np.isinf(sim_copy)
obs_inf = np.isinf(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_inf] = replace_inf
obs_copy[obs_inf] = replace_inf
warnings.warn("Elements(s) {} contained Inf values in the simulated array and "
"elements(s) {} contained Inf values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_inf)[0],
np.where(obs_inf)[0]),
UserWarning)
else:
inf_indices_fcst = ~(np.isinf(sim_copy))
inf_indices_obs = ~np.isinf(obs_copy)
all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)
warnings.warn(
"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows "
"are zero indexed).".format(np.where(~all_inf_indices)[0]),
UserWarning
)
# Treat zero data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain zero values
if remove_zero:
if (obs_copy == 0).any() or (sim_copy == 0).any():
zero_indices_fcst = ~(sim_copy == 0)
zero_indices_obs = ~(obs_copy == 0)
all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)
warnings.warn(
"Row(s) {} contained zero values and the row(s) have been removed (Rows are "
"zero indexed).".format(np.where(~all_zero_indices)[0]),
UserWarning
)
# Treat negative data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain negative values
# Ignore runtime warnings from comparing
if remove_neg:
with np.errstate(invalid='ignore'):
obs_copy_bool = obs_copy < 0
sim_copy_bool = sim_copy < 0
if obs_copy_bool.any() or sim_copy_bool.any():
neg_indices_fcst = ~sim_copy_bool
neg_indices_obs = ~obs_copy_bool
all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)
warnings.warn("Row(s) {} contained negative values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_neg_indices)[0]),
UserWarning)
obs_copy = obs_copy[all_treatment_array]
sim_copy = sim_copy[all_treatment_array]
return sim_copy, obs_copy
if __name__ == "__main__":
pass
|
BYU-Hydroinformatics/HydroErr | HydroErr/HydroErr.py | nrmse_iqr | python | def nrmse_iqr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
q1 = np.percentile(observed_array, 25)
q3 = np.percentile(observed_array, 75)
iqr = q3 - q1
return rmse_value / iqr | Compute the IQR normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_IQR.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the interquartile range of the observed time
series (x). Normalizing allows comparison between data sets with different scales.
The NRMSEquartile is the least sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The IQR normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_iqr(sim, obs)
0.2595461185212093
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142. | train | https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L1203-L1282 | [
"def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,\n remove_neg=False, remove_zero=False):\n \"\"\"Removes the nan, negative, and inf values in two numpy arrays\"\"\"\n sim_copy = np.copy(simulated_array)\n obs_copy = np.copy(observed_array)\n\n # Checking to see if the vectors are the same length\n assert sim_copy.ndim == 1, \"The simulated array is not one dimensional.\"\n assert obs_copy.ndim == 1, \"The observed array is not one dimensional.\"\n\n if sim_copy.size != obs_copy.size:\n raise RuntimeError(\"The two ndarrays are not the same size.\")\n\n # Treat missing data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain nan values\n all_treatment_array = np.ones(obs_copy.size, dtype=bool)\n\n if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_nan = np.isnan(sim_copy)\n obs_nan = np.isnan(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_nan] = replace_nan\n obs_copy[obs_nan] = replace_nan\n\n warnings.warn(\"Elements(s) {} contained NaN values in the simulated array and \"\n \"elements(s) {} contained NaN values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_nan)[0],\n np.where(obs_nan)[0]),\n UserWarning)\n else:\n # Getting the indices of the nan values, combining them, and informing user.\n nan_indices_fcst = ~np.isnan(sim_copy)\n nan_indices_obs = ~np.isnan(obs_copy)\n all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)\n\n warnings.warn(\"Row(s) {} contained NaN values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_nan_indices)[0]),\n UserWarning)\n\n if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_inf = np.isinf(sim_copy)\n obs_inf = np.isinf(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_inf] = replace_inf\n obs_copy[obs_inf] = replace_inf\n\n warnings.warn(\"Elements(s) {} contained Inf values in the simulated array and \"\n \"elements(s) {} contained Inf values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_inf)[0],\n np.where(obs_inf)[0]),\n UserWarning)\n else:\n inf_indices_fcst = ~(np.isinf(sim_copy))\n inf_indices_obs = ~np.isinf(obs_copy)\n all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)\n\n warnings.warn(\n \"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows \"\n \"are zero indexed).\".format(np.where(~all_inf_indices)[0]),\n UserWarning\n )\n\n # Treat zero data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain zero values\n if remove_zero:\n if (obs_copy == 0).any() or (sim_copy == 0).any():\n zero_indices_fcst = ~(sim_copy == 0)\n zero_indices_obs = ~(obs_copy == 0)\n all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)\n\n warnings.warn(\n \"Row(s) {} contained zero values and the row(s) have been removed (Rows are \"\n \"zero indexed).\".format(np.where(~all_zero_indices)[0]),\n UserWarning\n )\n\n # Treat negative data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain negative values\n\n # Ignore runtime warnings from comparing\n if remove_neg:\n with np.errstate(invalid='ignore'):\n obs_copy_bool = obs_copy < 0\n sim_copy_bool = sim_copy < 0\n\n if obs_copy_bool.any() or sim_copy_bool.any():\n neg_indices_fcst = ~sim_copy_bool\n neg_indices_obs = ~obs_copy_bool\n all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)\n\n warnings.warn(\"Row(s) {} contained negative values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_neg_indices)[0]),\n UserWarning)\n\n obs_copy = obs_copy[all_treatment_array]\n sim_copy = sim_copy[all_treatment_array]\n\n return sim_copy, obs_copy\n"
] | # -*- coding: utf-8 -*-
"""
HydroErr contains a library of goodness of fit metrics that measure hydrologic skill.
Each metric is contained in function, and every function has the parameters to treat missing values as
well as remove zero and negative values from the timeseries data.
Each function contains two properties, name and abbr. These can be used in the Hydrostats package when creating tables
and adding metrics to the plots. Link to the hydrostats package: https://github.com/BYU-Hydroinformatics/Hydrostats.
An example of this functionality is shown below.
>>> import HydroErr as he
>>>
>>> he.acc.name
'Anomaly Correlation Coefficient'
>>> he.acc.abbr
'ACC'
"""
from __future__ import division
import numpy as np
from scipy.stats import gmean, rankdata
import warnings
__all__ = ['me', 'mae', 'mse', 'mle', 'male', 'msle', 'mde', 'mdae', 'mdse', 'ed', 'ned', 'rmse',
'rmsle', 'nrmse_range', 'nrmse_mean', 'nrmse_iqr', 'irmse', 'mase', 'r_squared',
'pearson_r', 'spearman_r', 'acc', 'mape', 'mapd', 'maape', 'smape1', 'smape2', 'd', 'd1',
'dmod', 'drel', 'dr', 'watt_m', 'mb_r', 'nse', 'nse_mod', 'nse_rel', 'kge_2009',
'kge_2012', 'lm_index', 'd1_p', 've', 'sa', 'sc', 'sid', 'sga', 'h1_mhe', 'h1_mahe',
'h1_rmshe', 'h2_mhe', 'h2_mahe', 'h2_rmshe', 'h3_mhe', 'h3_mahe', 'h3_rmshe', 'h4_mhe',
'h4_mahe', 'h4_rmshe', 'h5_mhe', 'h5_mahe', 'h5_rmshe', 'h6_mhe', 'h6_mahe', 'h6_rmshe',
'h7_mhe', 'h7_mahe', 'h7_rmshe', 'h8_mhe', 'h8_mahe', 'h8_rmshe', 'h10_mhe', 'h10_mahe',
'h10_rmshe', 'g_mean_diff', 'mean_var']
####################################################################################################
# General and Hydrological Error Metrics #
####################################################################################################
def me(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean error of the simulated and observed data.
.. image:: /pictures/ME.png
**Range:** -inf < MAE < inf, data units, closer to zero is better, indicates bias.
**Notes:** The mean error (ME) measures the difference between the simulated data and the
observed data. For the mean error, a smaller number indicates a better fit to the original
data. Note that if the error is in the form of random noise, the mean error will be very small,
which can skew the accuracy of this metric. ME is cumulative and will be small even if there
are large positive and negative errors that balance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean error value.
Examples
--------
Note that in this example the random noise cancels, leaving a very small ME.
>>> import HydroErr as he
>>> import numpy as np
>>> # Seed for reproducibility
>>> np.random.seed(54839)
>>> x = np.arange(100) / 20
>>> sim = np.sin(x) + 2
>>> obs = sim * (((np.random.rand(100) - 0.5) / 10) + 1)
>>> he.me(sim, obs)
-0.006832220968967168
References
----------
- Fisher, R.A., 1920. A Mathematical Examination of the Methods of Determining the Accuracy of
an Observation by the Mean Error, and by the Mean Square Error. Monthly Notices of the Royal
Astronomical Society 80 758 - 770.
"""
# Treating missing values
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero)
return np.mean(simulated_array - observed_array)
def mae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute error of the simulated and observed data.
.. image:: /pictures/MAE.png
**Range:** 0 ≤ MAE < inf, data units, smaller is better.
**Notes:** The ME measures the absolute difference between the simulated data and the observed
data. For the mean abolute error, a smaller number indicates a better fit to the original data.
Also note that random errors do not cancel. Also referred to as an L1-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute error value.
References
----------
- Willmott, Cort J., and Kenji Matsuura. “Advantages of the Mean Absolute Error (MAE) over the
Root Mean Square Error (RMSE) in Assessing Average Model Performance.” Climate Research 30,
no. 1 (2005): 79–82.
- Willmott, Cort J., and Kenji Matsuura. “On the Use of Dimensioned Measures of Error to
Evaluate the Performance of Spatial Interpolators.” International Journal of Geographical
Information Science 20, no. 1 (2006): 89–102.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mae(sim, obs)
0.5666666666666665
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean(np.absolute(simulated_array - observed_array))
def mse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared error of the simulated and observed data.
.. image:: /pictures/MSE.png
**Range:** 0 ≤ MSE < inf, data units squared, smaller is better.
**Notes:** Random errors do not cancel, highlights larger errors, also referred to as a
squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mse(sim, obs)
0.4333333333333333
References
----------
- Wang, Zhou, and Alan C. Bovik. “Mean Squared Error: Love It or Leave It? A New Look at Signal
Fidelity Measures.” IEEE Signal Processing Magazine 26, no. 1 (2009): 98–117.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean((simulated_array - observed_array) ** 2)
def mle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean log error of the simulated and observed data.
.. image:: /pictures/MLE.png
**Range:** -inf < MLE < inf, data units, closer to zero is better.
**Notes** Same as the mean erro (ME) only use log ratios as the error term. Limits the impact of outliers, more
evenly weights high and low data values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mle(sim, obs)
0.002961767058151136
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(sim_log - obs_log)
def male(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean absolute log error of the simulated and observed data.
.. image:: /pictures/MALE.png
**Range:** 0 ≤ MALE < inf, data units squared, smaller is better.
**Notes** Same as MAE only use log ratios as the error term. Limits the impact of outliers,
more evenly weights high and low flows.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.male(sim, obs), 6)
0.090417
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(np.abs(sim_log - obs_log))
def msle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared log error of the simulated and observed data.
.. image:: /pictures/MSLE.png
**Range:** 0 ≤ MSLE < inf, data units squared, smaller is better.
**Notes** Same as the mean squared error (MSE) only use log ratios as the error term. Limits
the impact of outliers, more evenly weights high and low values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.msle(sim, obs), 6)
0.010426
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean((sim_log - obs_log) ** 2)
def mde(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median error (MdE) between the simulated and observed data.
.. image:: /pictures/MdE.png
**Range** -inf < MdE < inf, closer to zero is better.
**Notes** This metric indicates bias. It is similar to the mean error (ME), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mde(sim, obs)
-0.10000000000000009
Returns
-------
float
The median error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(simulated_array - observed_array)
def mdae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median absolute error (MdAE) between the simulated and observed data.
.. image:: /pictures/MdAE.png
**Range** 0 ≤ MdAE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean absolute error (MAE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdae(sim, obs)
0.75
Returns
-------
float
The median absolute error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(np.abs(simulated_array - observed_array))
def mdse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median squared error (MdSE) between the simulated and observed data.
.. image:: /pictures/MdSE.png
**Range** 0 ≤ MdSE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean squared error (MSE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdse(sim, obs)
0.625
Returns
-------
float
The median squared error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median((simulated_array - observed_array) ** 2)
def ed(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Euclidean distance between predicted and observed values in vector space.
.. image:: /pictures/ED.png
**Range** 0 ≤ ED < inf, smaller is better.
**Notes** Also sometimes referred to as the L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ed(sim, obs)
1.63707055437449
Returns
-------
float
The euclidean distance error value.
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.linalg.norm(observed_array - simulated_array)
def ned(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the normalized Euclidian distance between the simulated and observed data in vector
space.
.. image:: /pictures/NED.png
**Range** 0 ≤ NED < inf, smaller is better.
**Notes** Also sometimes referred to as the squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The normalized euclidean distance value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ned(sim, obs)
0.2872053604165771
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array / np.mean(observed_array)
b = simulated_array / np.mean(simulated_array)
return np.linalg.norm(a - b)
def rmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square error between the simulated and observed data.
.. image:: /pictures/RMSE.png
**Range** 0 ≤ RMSE < inf, smaller is better.
**Notes:** The standard deviation of the residuals. A lower spread indicates that the points
are better concentrated around the line of best fit (linear). Random errors do not cancel.
This metric will highlights larger errors.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.rmse(sim, obs)
0.668331255192114
References
----------
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.sqrt(np.mean((simulated_array - observed_array) ** 2))
def rmsle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square log error between the simulated and observed data.
.. image:: /pictures/RMSLE.png
**Range:** 0 ≤ RMSLE < inf. Smaller is better, and it does not indicate bias.
**Notes:** Random errors do not cancel while using this metric. This metric limits the
impact of outliers by more evenly weighting high and low values. To calculate the log values,
each value in the observed and simulated array is increased by one unit in order to avoid
run-time errors and nan values (function np.log1p).
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square log error value.
Examples
--------
Notice that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.rmsle(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
"""
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf, remove_neg=remove_neg,
remove_zero=remove_zero)
return np.sqrt(np.mean(np.power(np.log1p(simulated_array) - np.log1p(observed_array), 2)))
def nrmse_range(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the range normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Range.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the range of the observed time series (x).
Normalizing allows comparison between data sets with different scales. The NRMSErange is the
most sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The range normalized root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_range(sim, obs)
0.0891108340256152
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_max = np.max(observed_array)
obs_min = np.min(observed_array)
return rmse_value / (obs_max - obs_min)
def nrmse_mean(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Mean.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the mean of the observed time series (x).
Normalizing allows comparison between data sets with different scales.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_mean(sim, obs)
0.11725109740212526
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_mean = np.mean(observed_array)
return rmse_value / obs_mean
def nrmse_iqr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the IQR normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_IQR.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the interquartile range of the observed time
series (x). Normalizing allows comparison between data sets with different scales.
The NRMSEquartile is the least sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The IQR normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_iqr(sim, obs)
0.2595461185212093
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
q1 = np.percentile(observed_array, 25)
q3 = np.percentile(observed_array, 75)
iqr = q3 - q1
return rmse_value / iqr
def irmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the inertial root mean square error (IRMSE) between the simulated and observed data.
.. image:: /pictures/IRMSE.png
**Range:** 0 ≤ IRMSE < inf, lower is better.
**Notes:** This metric is the RMSE devided by by the standard deviation of the gradient of the
observed timeseries data. This metric is meant to be help understand the ability of the model
to predict changes in observation.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The inertial root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.irmse(sim, obs)
0.14572738134831856
References
----------
- Daga, M., Deo, M.C., 2009. Alternative data-driven methods to estimate wind from waves by
inverse modeling. Natural Hazards 49(2) 293-310.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Getting the gradient of the observed data
obs_len = observed_array.size
obs_grad = observed_array[1:obs_len] - observed_array[0:obs_len - 1]
# Standard deviation of the gradient
obs_grad_std = np.std(obs_grad, ddof=1)
# Divide RMSE by the standard deviation of the gradient of the observed data
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
return rmse_value / obs_grad_std
def mase(simulated_array, observed_array, m=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute scaled error between the simulated and observed data.
.. image:: /pictures/MASE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
m: int
If given, indicates the seasonal period m. If not given, the default is 1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute scaled error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mase(sim, obs)
0.17341040462427745
References
----------
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
start = m
end = simulated_array.size - m
a = np.mean(np.abs(simulated_array - observed_array))
b = np.abs(observed_array[start:observed_array.size] - observed_array[:end])
return a / (np.sum(b) / end)
def pearson_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the pearson correlation coefficient.
.. image:: /pictures/R_pearson.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The pearson r coefficient measures linear correlation. It is sensitive to outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Pearson correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.pearson_r(sim, obs)
0.9610793632835262
References
----------
- Pearson, K. (1895). Note on regression and inheritance in the case of two parents.
Proceedings of the Royal Society of London, 58, 240-242.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
top = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1 = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2 = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
return top / (bot1 * bot2)
def spearman_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the spearman rank correlation coefficient.
.. image:: /pictures/R_spearman.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The spearman r coefficient measures the monotonic relation between simulated and
observed data. Because it uses a nonparametric measure of rank correlation, it is less sensitive
to outliers compared to the Pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spearman rank correlation coefficient.
Examples
----------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.spearman_r(sim, obs)
0.942857142857143
References
----------
- Spearman C (1904). "The proof and measurement of association between two things". American
Journal of Psychology. 15: 72–101. doi:10.2307/1412159
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rank_sim = rankdata(simulated_array)
rank_obs = rankdata(observed_array)
mean_rank_sim = np.mean(rank_sim)
mean_rank_obs = np.mean(rank_obs)
top = np.mean((rank_obs - mean_rank_obs) * (rank_sim - mean_rank_sim))
bot = np.sqrt(
np.mean((rank_obs - mean_rank_obs) ** 2) * np.mean((rank_sim - mean_rank_sim) ** 2))
return top / bot
def r_squared(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Coefficient of Determination (r2).
.. image:: /pictures/r2.png
**Range:** 0 ≤ r2 ≤ 1. 1 indicates perfect correlation, 0 indicates complete randomness.
**Notes:** The Coefficient of Determination measures the linear relation between simulated and
observed data. Because it is the pearson correlation coefficient squared, it is more heavily
affected by outliers than the pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The coefficient of determination (R^2).
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.r_squared(sim, obs)
0.9236735425294681
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array - np.mean(observed_array)
b = simulated_array - np.mean(simulated_array)
return (np.sum(a * b)) ** 2 / (np.sum(a ** 2) * np.sum(b ** 2))
def acc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the anomaly correlation coefficient (ACC).
.. image:: /pictures/ACC.png
**Range:** -1 ≤ ACC ≤ 1. -1 indicates perfect negative correlation of the variation
pattern of the anomalies, 0 indicates complete randomness of the variation patterns of the
anomalies, 1 indicates perfect correlation of the variation pattern of the anomalies.
**Notes:** Common measure in the verification of spatial fields. Measures the correlation
between the variation pattern of the simulated data compared to the observed data.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The anomaly correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.acc(sim, obs)
0.8008994694029383
References
----------
- Langland, Rolf H., and Ryan N. Maue. “Recent Northern Hemisphere Mid-Latitude Medium-Range
Deterministic Forecast Skill.” Tellus A: Dynamic Meteorology and Oceanography 64,
no. 1 (2012): 17531.
- Miyakoda, K., G. D. Hembree, R. F. Strickler, and I. Shulman. “Cumulative Results of Extended
Forecast Experiments I. Model Performance for Winter Cases.” Monthly Weather Review 100, no.
12(1972): 836–55.
- Murphy, Allan H., and Edward S. Epstein. “Skill Scores and Correlation Coefficients in Model
Verification.” Monthly Weather Review 117, no. 3 (1989): 572–82.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - np.mean(simulated_array)
b = observed_array - np.mean(observed_array)
c = np.std(observed_array, ddof=1) * np.std(simulated_array, ddof=1) * simulated_array.size
return np.dot(a, b / c)
def mape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the mean absolute percentage error (MAPE).
.. image:: /pictures/MAPE.png
**Range:** 0% ≤ MAPE ≤ inf. 0% indicates perfect correlation, a larger error indicates a
larger percent error in the data.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
c = 100 / simulated_array.size
return c * np.sum(b)
def mapd(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the mean absolute percentage deviation (MAPD).
.. image:: /pictures/MAPD.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage deviation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mapd(sim, obs)
0.10526315789473682
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(np.abs(observed_array))
return a / b
def maape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the Mean Arctangent Absolute Percentage Error (MAAPE).
.. image:: /pictures/MAAPE.png
**Range:** 0 ≤ MAAPE < π/2, does not indicate bias, smaller is better.
**Notes:** Represents the mean absolute error as a percentage of the observed values. Handles
0s in the observed data. This metric is not as biased as MAPE by under-over predictions.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean arctangent absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
- Kim, S., Kim, H., 2016. A new metric of absolute percentage error for intermittent demand
forecasts. International Journal of Forecasting 32(3) 669-679.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
return np.mean(np.arctan(b))
def smape1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (1) (SMAPE1).
.. image:: /pictures/SMAPE1.png
**Range:** 0 ≤ SMAPE1 < 100%, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (1).
Examples
--------
Note that if we switch the simulated and observed arrays the result is the same
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape1(sim, obs)
5.871915694397428
>>> he.smape1(obs, sim)
5.871915694397428
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 100 / simulated_array.size
b = np.abs(simulated_array - observed_array)
c = np.abs(simulated_array) + np.abs(observed_array)
return a * np.sum(b / c)
def smape2(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (2) (SMAPE2).
.. image:: /pictures/SMAPE2.png
**Range:** 0 ≤ SMAPE1 < 200%, does not indicate bias, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE with only positive metric values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (2).
Examples
--------
Note that switching the simulated and observed arrays yields the same results
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape2(sim, obs)
11.743831388794856
>>> he.smape2(obs, sim)
11.743831388794856
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = (simulated_array + observed_array) / 2
c = 100 / simulated_array.size
return c * np.sum(np.abs(a / b))
def d(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d).
.. image:: /pictures/d.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d(sim, obs)
0.978477353035657
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (observed_array - simulated_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
return 1 - (np.sum(a) / np.sum((b + c) ** 2))
def d1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d1).
.. image:: /pictures/d1.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric. Compared
to the other index of agreement (d) it has a reduced impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (d1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1(sim, obs)
0.8434782608695652
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
obs_mean = np.mean(observed_array)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.abs(simulated_array - obs_mean)
c = np.abs(observed_array - obs_mean)
return 1 - np.sum(a) / np.sum(b + c)
def dr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the refined index of agreement (dr).
.. image:: /pictures/dr.png
**Range:** -1 ≤ dr < 1, does not indicate bias, larger is better.
**Notes:** Reformulation of Willmott’s index of agreement. This metric was created to address
issues in the index of agreement and the Nash-Sutcliffe efficiency metric. Meant to be a
flexible metric for use in climatology.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The refined index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dr(sim, obs)
0.847457627118644
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = 2 * np.sum(np.abs(observed_array - observed_array.mean()))
if a <= b:
return 1 - (a / b)
else:
return (b / a) - 1
def drel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the relative index of agreement (drel).
.. image:: /pictures/drel.png
**Range:** 0 ≤ drel < 1, does not indicate bias, larger is better.
**Notes:** Instead of absolute differences, this metric uses relative differences.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.drel(sim, obs)
0.9740868625579597
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = ((simulated_array - observed_array) / observed_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = ((b + c) / np.mean(observed_array)) ** 2
return 1 - (np.sum(a) / np.sum(e))
def dmod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the modified index of agreement (dmod).
.. image:: /pictures/dmod.png
**Range:** 0 ≤ dmod < 1, does not indicate bias, larger is better.
**Notes:** When j=1, this metric is the same as d1. As j becomes larger, outliers have a larger
impact on the value.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
Optional input indicating the j values desired. A higher j places more emphasis on
outliers. j is 1 by default.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified index of agreement.
Examples
--------
Note that using the default is the same as calculating the d1 metric. Changing the value of j
modification of the metric.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dmod(sim, obs) # Same as d1
0.8434782608695652
>>> he.dmod(sim, obs, j=1.5)
0.9413310986805733
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = (b + c) ** j
return 1 - (np.sum(a) / np.sum(e))
def watt_m(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute Watterson's M (M).
.. image:: /pictures/M.png
**Range:** -1 ≤ M < 1, does not indicate bias, larger is better.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
Watterson's M value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.watt_m(sim, obs)
0.8307913876595929
References
----------
- Watterson, I.G., 1996. Non‐dimensional measures of climate model performance. International
Journal of Climatology 16(4) 379-391.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 2 / np.pi
b = np.mean((simulated_array - observed_array) ** 2) # MSE
c = np.std(observed_array, ddof=1) ** 2 + np.std(simulated_array, ddof=1) ** 2
e = (np.mean(simulated_array) - np.mean(observed_array)) ** 2
f = c + e
return a * np.arcsin(1 - (b / f))
def mb_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute Mielke-Berry R value (MB R).
.. image:: /pictures/MB_R.png
**Range:** 0 ≤ MB R < 1, does not indicate bias, larger is better.
**Notes:** Compares prediction to probability it arose by chance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Mielke-Berry R value.
Notes
-----
If a more optimized version is desired, the `numba package <http://numba.pydata.org/doc.html>`_ can be implemented
for a much more optimized performance when computing this metric. An example is given below.
>>> from numba import njit, prange
>>> @njit(parallel=True, fastmath=True)
>>> def mb_par_fastmath(pred, obs): # uses LLVM compiler
>>> assert pred.size == obs.size
>>> n = pred.size
>>> tot = 0.0
>>> mae = 0.0
>>> for i in range(n):
>>> for j in prange(n):
>>> tot += abs(pred[i] - obs[j])
>>> mae += abs(pred[i] - obs[i])
>>> mae = mae / n
>>> mb = 1 - ((n ** 2) * mae / tot)
>>>
>>> return mb
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mb_r(sim, obs)
0.7726315789473684
References
----------
- Berry, K.J., Mielke, P.W., 1988. A Generalization of Cohen's Kappa Agreement Measure to
Interval Measurement and Multiple Raters. Educational and Psychological Measurement 48(4)
921-933.
- Mielke, P.W., Berry, K.J., 2007. Permutation methods: a distance function approach.
Springer Science & Business Media.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Calculate metric
n = simulated_array.size
tot = 0.0
for i in range(n):
tot = tot + np.sum(np.abs(simulated_array - observed_array[i]))
mae_val = np.sum(np.abs(simulated_array - observed_array)) / n
mb = 1 - ((n ** 2) * mae_val / tot)
return mb
def nse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Nash-Sutcliffe Efficiency.
.. image:: /pictures/NSE.png
**Range:** -inf < NSE < 1, does not indicate bias, larger is better.
**Notes:** The Nash-Sutcliffe efficiency metric compares prediction values to naive predictions
(i.e. average value). One major flaw of this metric is that it punishes a higher variance in
the observed values (denominator). This metric is analogous to the mean absolute error skill
score (MAESS) using the mean flow as a benchmark.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Nash-Sutcliffe Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse(sim, obs)
0.922093023255814
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
- McCuen, R.H., Knight, Z., Cutter, A.G., 2006. Evaluation of the Nash-Sutcliffe Efficiency
Index. Journal of Hydraulic Engineering.
- Nash, J.E., Sutcliffe, J.V., 1970. River flow forecasting through conceptual models part
I — A discussion of principles. Journal of Hydrology 282-290.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** 2
b = (np.abs(observed_array - np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def nse_mod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the modified Nash-Sutcliffe efficiency (NSE mod).
.. image:: /pictures/NSEmod.png
**Range:** -inf < NSE (mod) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
If given, sets the value of j to the input. j is 1 by default. A higher j gives more
emphasis to outliers
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_mod(sim, obs)
0.6949152542372882
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = (np.abs(observed_array - np.mean(observed_array))) ** j
return 1 - (np.sum(a) / np.sum(b))
def nse_rel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the relative Nash-Sutcliffe efficiency (NSE rel).
.. image:: /pictures/NSErel.png
**Range:** -inf < NSE (rel) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_rel(sim, obs)
0.9062004687708474
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs((simulated_array - observed_array) / observed_array)) ** 2
b = (np.abs((observed_array - np.mean(observed_array)) / np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def kge_2009(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""Compute the Kling-Gupta efficiency (2009).
.. image:: /pictures/KGE_2009.png
**Range:** -inf < KGE (2009) < 1, larger is better.
**Notes:** Gupta et al. (2009) created this metric to demonstrate the relative importance of
the three components of the NSE, which are correlation, bias and variability. This was done
with hydrologic modeling as the context. This metric is meant to address issues with the NSE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), Alpha, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, alpha, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2009) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2009(sim, obs)
0.912223072345668
>>> he.kge_2009(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.927910707932087, 1.0058823529411764, 0.9181073779138655)
References
----------
- Gupta, H. V., Kling, H., Yilmaz, K. K., & Martinez, G. F. (2009). Decomposition of the mean
squared error and NSE performance criteria: Implications for improving hydrological modelling.
Journal of Hydrology, 377(1-2), 80-91.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array, ddof=1)
obs_sigma = np.std(observed_array, ddof=1)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
if obs_mean != 0:
beta = sim_mean / obs_mean
else:
beta = np.nan
# Relative variability between simulated and observed values
if obs_sigma != 0:
alpha = sim_sigma / obs_sigma
else:
alpha = np.nan
if not np.isnan(beta) and not np.isnan(alpha):
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (alpha - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Alpha is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, alpha, beta, kge
else:
return kge
def kge_2012(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""
Compute the Kling-Gupta efficiency (2012).
.. image:: /pictures/KGE_2012.png
**Range:** -inf < KGE (2012) < 1, does not indicate bias, larger is better.
**Notes:** The modified version of the KGE (2009). Kling proposed this version to avoid
cross-correlation between bias and variability ratios.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), gamma, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, gamma, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2012) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2012(sim, obs)
0.9122230723456678
>>> he.kge_2012(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.9224843295231272, 1.0058823529411764, 0.9132923608280753)
References
----------
- Kling, H., Fuchs, M., & Paulin, M. (2012). Runoff conditions in the upper Danube basin under
an ensemble of climate change scenarios. Journal of Hydrology, 424, 264-277.
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array)
obs_sigma = np.std(observed_array)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
beta = sim_mean / obs_mean
# CV is the coefficient of variation (standard deviation / mean)
sim_cv = sim_sigma / sim_mean
obs_cv = obs_sigma / obs_mean
# Variability Ratio, or the ratio of simulated CV to observed CV
gam = sim_cv / obs_cv
if obs_mean != 0 and obs_sigma != 0 and sim_mean != 0:
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (gam - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
if sim_mean == 0:
warnings.warn(
'Warning: The simulated data mean is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, gam, beta, kge
else:
return kge
def lm_index(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""
Compute the Legate-McCabe Efficiency Index.
.. image:: /pictures/E1p.png
**Range:** 0 ≤ E1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.lm_index(sim, obs)
0.6949152542372882
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
mean_obs = np.mean(observed_array)
if obs_bar_p is not None:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def d1_p(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""Compute the Legate-McCabe Index of Agreement.
.. image:: /pictures/D1p.png
**Range:** 0 ≤ d1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1_p(sim, obs)
0.8434782608695652
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
if obs_bar_p is not None:
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - obs_bar_p) + np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
mean_obs = np.mean(observed_array)
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - mean_obs) + np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def ve(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Volumetric Efficiency (VE).
.. image:: /pictures/VE.png
**Range:** 0 ≤ VE < 1 smaller is better, does not indicate bias.
**Notes:** Represents the error as a percentage of flow.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Volumetric Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ve(sim, obs)
0.8947368421052632
References
----------
- Criss, R.E., Winston, W.E., 2008. Do Nash values have value? Discussion and alternate
proposals. Hydrological Processes 22(14) 2723.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(observed_array)
return 1 - (a / b)
def sa(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Angle (SA).
.. image:: /pictures/SA.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral angle metric measures the angle between the two vectors in hyperspace.
It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Angle value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sa(sim, obs)
0.10816831366492945
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(simulated_array, observed_array)
b = np.linalg.norm(simulated_array) * np.linalg.norm(observed_array)
return np.arccos(a / b)
def sc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Correlation (SC).
.. image:: /pictures/SC.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral correlation metric measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Correlation value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sc(sim, obs)
0.27991341383646606
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(observed_array - np.mean(observed_array), simulated_array - np.mean(simulated_array))
b = np.linalg.norm(observed_array - np.mean(observed_array))
c = np.linalg.norm(simulated_array - np.mean(simulated_array))
e = b * c
return np.arccos(a / e)
def sid(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Information Divergence (SID).
.. image:: /pictures/SID.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral information divergence measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral information divergence value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sid(sim, obs)
0.03517616895318012
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
first = (observed_array / np.mean(observed_array)) - (
simulated_array / np.mean(simulated_array))
second1 = np.log10(observed_array) - np.log10(np.mean(observed_array))
second2 = np.log10(simulated_array) - np.log10(np.mean(simulated_array))
return np.dot(first, second1 - second2)
def sga(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Gradient Angle (SGA).
.. image:: /pictures/SGA.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral gradient angle measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
SG is the gradient of the simulated or observed time series.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Gradient Angle.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sga(sim, obs)
0.26764286472739834
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sgx = observed_array[1:] - observed_array[:observed_array.size - 1]
sgy = simulated_array[1:] - simulated_array[:simulated_array.size - 1]
a = np.dot(sgx, sgy)
b = np.linalg.norm(sgx) * np.linalg.norm(sgy)
return np.arccos(a / b)
####################################################################################################
# H Metrics: Methods from Tornqvist L, Vartia P, and Vartia YO. (1985) #
####################################################################################################
def h1_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the H1 mean error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mhe(sim, obs)
0.002106551840594386
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(h)
def h1_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H1 absolute error.
.. image:: /pictures/H1.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The H1 absolute error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mahe(sim, obs)
0.11639226612630865
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(np.abs(h))
def h1_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H1 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean squared H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_rmshe(sim, obs)
0.12865571253672756
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.sqrt(np.mean(h ** 2))
def h2_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean error.
.. image:: /pictures/H2.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mhe(sim, obs)
-0.015319829424307036
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(h)
def h2_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean absolute error.
.. image:: /pictures/H2.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mahe(sim, obs)
0.11997591408039167
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(np.abs(h))
def h2_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_rmshe(sim, obs)
0.1373586680669673
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.sqrt(np.mean(h ** 2))
def h3_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 mean error.
.. image:: /pictures/H3.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mhe(sim, obs)
-0.006322019630356533
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(h)
def h3_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H3 mean absolute error.
.. image:: /pictures/H3.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mahe(sim, obs)
0.11743831388794855
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(np.abs(h))
def h3_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 root mean square error.
.. image:: /pictures/H3.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.sqrt(np.mean(h ** 2))
def h4_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mhe(sim, obs)
-0.0064637371129817
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(h)
def h4_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H4 mean absolute error.
.. image:: /pictures/H4.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mahe(sim, obs)
0.11781032209144082
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(np.abs(h))
def h4_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_rmshe(sim, obs)
0.13200901963465006
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.sqrt(np.mean(h ** 2))
def h5_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean error.
.. image:: /pictures/H5.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mhe(sim, obs)
-0.006606638791856322
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(h)
def h5_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean absolute error.
.. image:: /pictures/H5.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mahe(sim, obs)
0.11818409010335018
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(np.abs(h))
def h5_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 root mean square error.
.. image:: /pictures/H5.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_rmshe(sim, obs)
0.13254476469410933
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h6_mhe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H6 mean error.
.. image:: /pictures/H6.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mhe(sim, obs)
-0.006322019630356514
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(h)
def h6_mahe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""Compute the H6 mean absolute error.
.. image:: /pictures/H6.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mahe(sim, obs)
0.11743831388794852
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(np.abs(h))
def h6_rmshe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the H6 root mean square error.
.. image:: /pictures/H6.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h7_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean error.
.. image:: /pictures/H7.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mhe(sim, obs)
0.0026331898007430263
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(h)
def h7_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean absolute error.
.. image:: /pictures/H7.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mahe(sim, obs)
0.14549033265788583
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(np.abs(h))
def h7_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 root mean square error.
.. image:: /pictures/H7.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_rmshe(sim, obs)
0.16081964067090945
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
def h8_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H8 mean error.
.. image:: /pictures/H8.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mhe(sim, obs)
0.0018056158633666466
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(h)
def h8_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 mean absolute error.
.. image:: /pictures/H8.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mahe(sim, obs)
0.099764799536836
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(np.abs(h))
def h8_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 root mean square error.
.. image:: /pictures/H8.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_rmshe(sim, obs)
0.11027632503148076
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
# def h9(simulated_array, observed_array, h_type='mhe', k=1):
# h = (simulated_array / observed_array - 1) / \
# np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
# if h_type == 'mhe':
# return h.mean()
# elif h_type == 'ahe':
# return np.abs(h).mean()
# elif h_type == 'rmshe':
# return np.sqrt((h**2).mean())
# else:
# raise RuntimeError("The three types available are 'mhe', 'ahe', and 'rmshe'.")
def h10_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean error.
.. image:: /pictures/H10.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h10_mhe(sim, obs)
-0.0012578676058971154
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(h)
def h10_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean absolute error.
.. image:: /pictures/H10.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_mahe(sim, obs), 6)
0.094636
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(np.abs(h))
def h10_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 root mean square error.
.. image:: /pictures/H10.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_rmshe(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.sqrt(np.mean(h ** 2))
###################################################################################################
# Statistical Error Metrics for Distribution Testing #
###################################################################################################
def g_mean_diff(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the geometric mean difference.
.. image:: /pictures/GMD.png
**Range:**
**Notes:** For the difference of geometric means, the geometric mean is computed for each of
two samples then their difference is taken.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The geometric mean difference value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.g_mean_diff(sim, obs)
0.988855412098022
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.exp(gmean(sim_log) - gmean(obs_log))
def mean_var(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the mean variance.
.. image:: /pictures/MV.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean variance.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.mean_var(sim, obs), 6)
0.010641
References
----------
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.var(np.log1p(observed_array) - np.log1p(simulated_array))
####################################################################################################
# HELPER FUNCTIONS AND API INFORMATION #
####################################################################################################
metric_names = [
'Mean Error', 'Mean Absolute Error', 'Mean Squared Error', 'Mean Log Error',
'Mean Absolute Log Error', 'Mean Squared Log Error', 'Median Error', 'Median Absolute Error',
'Median Squared Error', 'Eclidean Distance', 'Normalized Eclidean Distance',
'Root Mean Square Error', 'Root Mean Squared Log Error',
'Normalized Root Mean Square Error - Range', 'Normalized Root Mean Square Error - Mean',
'Normalized Root Mean Square Error - IQR', 'Inertial Root Mean Square Error',
'Mean Absolute Scaled Error', 'Coefficient of Determination', 'Pearson Correlation Coefficient',
'Spearman Rank Correlation Coefficient', 'Anomaly Correlation Coefficient',
'Mean Absolute Percentage Error', 'Mean Absolute Percentage Deviation',
'Mean Arctangent Absolute Percentage Error', 'Symmetric Mean Absolute Percentage Error (1)',
'Symmetric Mean Absolute Percentage Error (2)', 'Index of Agreement (d)',
'Index of Agreement (d1)', 'Modified Index of Agreement', 'Relative Index of Agreement',
'Index of Agreement Refined (dr)', "Watterson's M", 'Mielke-Berry R',
'Nash-Sutcliffe Efficiency', 'Modified Nash-Sutcliffe Efficiency',
'Relative Nash-Sutcliffe Efficiency', 'Kling-Gupta Efficiency (2009)',
'Kling-Gupta Efficiency (2012)', 'Legate-McCabe Efficiency Index',
'Legate-McCabe Index of Agreement', 'Volumetric Efficiency', 'Spectral Angle',
'Spectral Correlation', 'Spectral Information Divergence', 'Spectral Gradient Angle',
'Mean H1 Error', 'Mean Absolute H1 Error', 'Root Mean Square H1 Error', 'Mean H2 Error',
'Mean Absolute H2 Error', 'Root Mean Square H2 Error', 'Mean H3 Error',
'Mean Absolute H3 Error', 'Root Mean Square H3 Error', 'Mean H4 Error',
'Mean Absolute H4 Error', 'Root Mean Square H4 Error', 'Mean H5 Error',
'Mean Absolute H5 Error', 'Root Mean Square H5 Error', 'Mean H6 Error',
'Mean Absolute H6 Error', 'Root Mean Square H6 Error', 'Mean H7 Error',
'Mean Absolute H7 Error', 'Root Mean Square H7 Error', 'Mean H8 Error',
'Mean Absolute H8 Error', 'Root Mean Square H8 Error', 'Mean H10 Error',
'Mean Absolute H10 Error', 'Root Mean Square H10 Error', 'Geometric Mean Difference',
'Mean Variance'
]
metric_abbr = [
'ME', 'MAE', 'MSE', 'MLE', 'MALE', 'MSLE', 'MdE', 'MdAE', 'MdSE', 'ED', 'NED', 'RMSE', 'RMSLE',
'NRMSE (Range)', 'NRMSE (Mean)', 'NRMSE (IQR)', 'IRMSE', 'MASE', 'r2', 'R (Pearson)',
'R (Spearman)', 'ACC', 'MAPE', 'MAPD', 'MAAPE', 'SMAPE1', 'SMAPE2', 'd', 'd1', 'd (Mod.)',
'd (Rel.)', 'dr', 'M', '(MB) R', 'NSE', 'NSE (Mod.)', 'NSE (Rel.)', 'KGE (2009)', 'KGE (2012)',
"E1'", "D1'", 'VE', 'SA', 'SC', 'SID', 'SGA', 'H1 (MHE)', 'H1 (MAHE)', 'H1 (RMSHE)', 'H2 (MHE)',
'H2 (MAHE)', 'H2 (RMSHE)', 'H3 (MHE)', 'H3 (MAHE)', 'H3 (RMSHE)', 'H4 (MHE)', 'H4 (MAHE)',
'H4 (RMSHE)', 'H5 (MHE)', 'H5 (MAHE)', 'H5 (RMSHE)', 'H6 (MHE)', 'H6 (MAHE)', 'H6 (RMSHE)',
'H7 (MHE)', 'H7 (MAHE)', 'H7 (RMSHE)', 'H8 (MHE)', 'H8 (MAHE)', 'H8 (RMSHE)', 'H10 (MHE)',
'H10 (MAHE)', 'H10 (RMSHE)', 'GMD', 'MV'
]
function_list = [
me, mae, mse, mle, male, msle, mde, mdae, mdse, ed, ned, rmse, rmsle, nrmse_range, nrmse_mean,
nrmse_iqr, irmse, mase, r_squared, pearson_r, spearman_r, acc, mape, mapd, maape, smape1,
smape2, d, d1, dmod, drel, dr, watt_m, mb_r, nse, nse_mod, nse_rel, kge_2009, kge_2012,
lm_index, d1_p, ve, sa, sc, sid, sga, h1_mhe, h1_mahe, h1_rmshe, h2_mhe, h2_mahe, h2_rmshe,
h3_mhe, h3_mahe, h3_rmshe, h4_mhe, h4_mahe, h4_rmshe, h5_mhe, h5_mahe, h5_rmshe, h6_mhe,
h6_mahe, h6_rmshe, h7_mhe, h7_mahe, h7_rmshe, h8_mhe, h8_mahe, h8_rmshe, h10_mhe, h10_mahe,
h10_rmshe, g_mean_diff, mean_var,
]
# Assign some properties to each function for ease of use for users
for i in range(len(function_list)):
function_list[i].name = metric_names[i]
function_list[i].abbr = metric_abbr[i]
def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Removes the nan, negative, and inf values in two numpy arrays"""
sim_copy = np.copy(simulated_array)
obs_copy = np.copy(observed_array)
# Checking to see if the vectors are the same length
assert sim_copy.ndim == 1, "The simulated array is not one dimensional."
assert obs_copy.ndim == 1, "The observed array is not one dimensional."
if sim_copy.size != obs_copy.size:
raise RuntimeError("The two ndarrays are not the same size.")
# Treat missing data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain nan values
all_treatment_array = np.ones(obs_copy.size, dtype=bool)
if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_nan = np.isnan(sim_copy)
obs_nan = np.isnan(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_nan] = replace_nan
obs_copy[obs_nan] = replace_nan
warnings.warn("Elements(s) {} contained NaN values in the simulated array and "
"elements(s) {} contained NaN values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_nan)[0],
np.where(obs_nan)[0]),
UserWarning)
else:
# Getting the indices of the nan values, combining them, and informing user.
nan_indices_fcst = ~np.isnan(sim_copy)
nan_indices_obs = ~np.isnan(obs_copy)
all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)
warnings.warn("Row(s) {} contained NaN values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_nan_indices)[0]),
UserWarning)
if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_inf = np.isinf(sim_copy)
obs_inf = np.isinf(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_inf] = replace_inf
obs_copy[obs_inf] = replace_inf
warnings.warn("Elements(s) {} contained Inf values in the simulated array and "
"elements(s) {} contained Inf values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_inf)[0],
np.where(obs_inf)[0]),
UserWarning)
else:
inf_indices_fcst = ~(np.isinf(sim_copy))
inf_indices_obs = ~np.isinf(obs_copy)
all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)
warnings.warn(
"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows "
"are zero indexed).".format(np.where(~all_inf_indices)[0]),
UserWarning
)
# Treat zero data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain zero values
if remove_zero:
if (obs_copy == 0).any() or (sim_copy == 0).any():
zero_indices_fcst = ~(sim_copy == 0)
zero_indices_obs = ~(obs_copy == 0)
all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)
warnings.warn(
"Row(s) {} contained zero values and the row(s) have been removed (Rows are "
"zero indexed).".format(np.where(~all_zero_indices)[0]),
UserWarning
)
# Treat negative data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain negative values
# Ignore runtime warnings from comparing
if remove_neg:
with np.errstate(invalid='ignore'):
obs_copy_bool = obs_copy < 0
sim_copy_bool = sim_copy < 0
if obs_copy_bool.any() or sim_copy_bool.any():
neg_indices_fcst = ~sim_copy_bool
neg_indices_obs = ~obs_copy_bool
all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)
warnings.warn("Row(s) {} contained negative values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_neg_indices)[0]),
UserWarning)
obs_copy = obs_copy[all_treatment_array]
sim_copy = sim_copy[all_treatment_array]
return sim_copy, obs_copy
if __name__ == "__main__":
pass
|
BYU-Hydroinformatics/HydroErr | HydroErr/HydroErr.py | mase | python | def mase(simulated_array, observed_array, m=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
start = m
end = simulated_array.size - m
a = np.mean(np.abs(simulated_array - observed_array))
b = np.abs(observed_array[start:observed_array.size] - observed_array[:end])
return a / (np.sum(b) / end) | Compute the mean absolute scaled error between the simulated and observed data.
.. image:: /pictures/MASE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
m: int
If given, indicates the seasonal period m. If not given, the default is 1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute scaled error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mase(sim, obs)
0.17341040462427745
References
----------
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688. | train | https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L1372-L1450 | [
"def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,\n remove_neg=False, remove_zero=False):\n \"\"\"Removes the nan, negative, and inf values in two numpy arrays\"\"\"\n sim_copy = np.copy(simulated_array)\n obs_copy = np.copy(observed_array)\n\n # Checking to see if the vectors are the same length\n assert sim_copy.ndim == 1, \"The simulated array is not one dimensional.\"\n assert obs_copy.ndim == 1, \"The observed array is not one dimensional.\"\n\n if sim_copy.size != obs_copy.size:\n raise RuntimeError(\"The two ndarrays are not the same size.\")\n\n # Treat missing data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain nan values\n all_treatment_array = np.ones(obs_copy.size, dtype=bool)\n\n if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_nan = np.isnan(sim_copy)\n obs_nan = np.isnan(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_nan] = replace_nan\n obs_copy[obs_nan] = replace_nan\n\n warnings.warn(\"Elements(s) {} contained NaN values in the simulated array and \"\n \"elements(s) {} contained NaN values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_nan)[0],\n np.where(obs_nan)[0]),\n UserWarning)\n else:\n # Getting the indices of the nan values, combining them, and informing user.\n nan_indices_fcst = ~np.isnan(sim_copy)\n nan_indices_obs = ~np.isnan(obs_copy)\n all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)\n\n warnings.warn(\"Row(s) {} contained NaN values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_nan_indices)[0]),\n UserWarning)\n\n if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_inf = np.isinf(sim_copy)\n obs_inf = np.isinf(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_inf] = replace_inf\n obs_copy[obs_inf] = replace_inf\n\n warnings.warn(\"Elements(s) {} contained Inf values in the simulated array and \"\n \"elements(s) {} contained Inf values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_inf)[0],\n np.where(obs_inf)[0]),\n UserWarning)\n else:\n inf_indices_fcst = ~(np.isinf(sim_copy))\n inf_indices_obs = ~np.isinf(obs_copy)\n all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)\n\n warnings.warn(\n \"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows \"\n \"are zero indexed).\".format(np.where(~all_inf_indices)[0]),\n UserWarning\n )\n\n # Treat zero data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain zero values\n if remove_zero:\n if (obs_copy == 0).any() or (sim_copy == 0).any():\n zero_indices_fcst = ~(sim_copy == 0)\n zero_indices_obs = ~(obs_copy == 0)\n all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)\n\n warnings.warn(\n \"Row(s) {} contained zero values and the row(s) have been removed (Rows are \"\n \"zero indexed).\".format(np.where(~all_zero_indices)[0]),\n UserWarning\n )\n\n # Treat negative data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain negative values\n\n # Ignore runtime warnings from comparing\n if remove_neg:\n with np.errstate(invalid='ignore'):\n obs_copy_bool = obs_copy < 0\n sim_copy_bool = sim_copy < 0\n\n if obs_copy_bool.any() or sim_copy_bool.any():\n neg_indices_fcst = ~sim_copy_bool\n neg_indices_obs = ~obs_copy_bool\n all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)\n\n warnings.warn(\"Row(s) {} contained negative values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_neg_indices)[0]),\n UserWarning)\n\n obs_copy = obs_copy[all_treatment_array]\n sim_copy = sim_copy[all_treatment_array]\n\n return sim_copy, obs_copy\n"
] | # -*- coding: utf-8 -*-
"""
HydroErr contains a library of goodness of fit metrics that measure hydrologic skill.
Each metric is contained in function, and every function has the parameters to treat missing values as
well as remove zero and negative values from the timeseries data.
Each function contains two properties, name and abbr. These can be used in the Hydrostats package when creating tables
and adding metrics to the plots. Link to the hydrostats package: https://github.com/BYU-Hydroinformatics/Hydrostats.
An example of this functionality is shown below.
>>> import HydroErr as he
>>>
>>> he.acc.name
'Anomaly Correlation Coefficient'
>>> he.acc.abbr
'ACC'
"""
from __future__ import division
import numpy as np
from scipy.stats import gmean, rankdata
import warnings
__all__ = ['me', 'mae', 'mse', 'mle', 'male', 'msle', 'mde', 'mdae', 'mdse', 'ed', 'ned', 'rmse',
'rmsle', 'nrmse_range', 'nrmse_mean', 'nrmse_iqr', 'irmse', 'mase', 'r_squared',
'pearson_r', 'spearman_r', 'acc', 'mape', 'mapd', 'maape', 'smape1', 'smape2', 'd', 'd1',
'dmod', 'drel', 'dr', 'watt_m', 'mb_r', 'nse', 'nse_mod', 'nse_rel', 'kge_2009',
'kge_2012', 'lm_index', 'd1_p', 've', 'sa', 'sc', 'sid', 'sga', 'h1_mhe', 'h1_mahe',
'h1_rmshe', 'h2_mhe', 'h2_mahe', 'h2_rmshe', 'h3_mhe', 'h3_mahe', 'h3_rmshe', 'h4_mhe',
'h4_mahe', 'h4_rmshe', 'h5_mhe', 'h5_mahe', 'h5_rmshe', 'h6_mhe', 'h6_mahe', 'h6_rmshe',
'h7_mhe', 'h7_mahe', 'h7_rmshe', 'h8_mhe', 'h8_mahe', 'h8_rmshe', 'h10_mhe', 'h10_mahe',
'h10_rmshe', 'g_mean_diff', 'mean_var']
####################################################################################################
# General and Hydrological Error Metrics #
####################################################################################################
def me(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean error of the simulated and observed data.
.. image:: /pictures/ME.png
**Range:** -inf < MAE < inf, data units, closer to zero is better, indicates bias.
**Notes:** The mean error (ME) measures the difference between the simulated data and the
observed data. For the mean error, a smaller number indicates a better fit to the original
data. Note that if the error is in the form of random noise, the mean error will be very small,
which can skew the accuracy of this metric. ME is cumulative and will be small even if there
are large positive and negative errors that balance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean error value.
Examples
--------
Note that in this example the random noise cancels, leaving a very small ME.
>>> import HydroErr as he
>>> import numpy as np
>>> # Seed for reproducibility
>>> np.random.seed(54839)
>>> x = np.arange(100) / 20
>>> sim = np.sin(x) + 2
>>> obs = sim * (((np.random.rand(100) - 0.5) / 10) + 1)
>>> he.me(sim, obs)
-0.006832220968967168
References
----------
- Fisher, R.A., 1920. A Mathematical Examination of the Methods of Determining the Accuracy of
an Observation by the Mean Error, and by the Mean Square Error. Monthly Notices of the Royal
Astronomical Society 80 758 - 770.
"""
# Treating missing values
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero)
return np.mean(simulated_array - observed_array)
def mae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute error of the simulated and observed data.
.. image:: /pictures/MAE.png
**Range:** 0 ≤ MAE < inf, data units, smaller is better.
**Notes:** The ME measures the absolute difference between the simulated data and the observed
data. For the mean abolute error, a smaller number indicates a better fit to the original data.
Also note that random errors do not cancel. Also referred to as an L1-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute error value.
References
----------
- Willmott, Cort J., and Kenji Matsuura. “Advantages of the Mean Absolute Error (MAE) over the
Root Mean Square Error (RMSE) in Assessing Average Model Performance.” Climate Research 30,
no. 1 (2005): 79–82.
- Willmott, Cort J., and Kenji Matsuura. “On the Use of Dimensioned Measures of Error to
Evaluate the Performance of Spatial Interpolators.” International Journal of Geographical
Information Science 20, no. 1 (2006): 89–102.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mae(sim, obs)
0.5666666666666665
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean(np.absolute(simulated_array - observed_array))
def mse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared error of the simulated and observed data.
.. image:: /pictures/MSE.png
**Range:** 0 ≤ MSE < inf, data units squared, smaller is better.
**Notes:** Random errors do not cancel, highlights larger errors, also referred to as a
squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mse(sim, obs)
0.4333333333333333
References
----------
- Wang, Zhou, and Alan C. Bovik. “Mean Squared Error: Love It or Leave It? A New Look at Signal
Fidelity Measures.” IEEE Signal Processing Magazine 26, no. 1 (2009): 98–117.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean((simulated_array - observed_array) ** 2)
def mle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean log error of the simulated and observed data.
.. image:: /pictures/MLE.png
**Range:** -inf < MLE < inf, data units, closer to zero is better.
**Notes** Same as the mean erro (ME) only use log ratios as the error term. Limits the impact of outliers, more
evenly weights high and low data values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mle(sim, obs)
0.002961767058151136
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(sim_log - obs_log)
def male(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean absolute log error of the simulated and observed data.
.. image:: /pictures/MALE.png
**Range:** 0 ≤ MALE < inf, data units squared, smaller is better.
**Notes** Same as MAE only use log ratios as the error term. Limits the impact of outliers,
more evenly weights high and low flows.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.male(sim, obs), 6)
0.090417
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(np.abs(sim_log - obs_log))
def msle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared log error of the simulated and observed data.
.. image:: /pictures/MSLE.png
**Range:** 0 ≤ MSLE < inf, data units squared, smaller is better.
**Notes** Same as the mean squared error (MSE) only use log ratios as the error term. Limits
the impact of outliers, more evenly weights high and low values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.msle(sim, obs), 6)
0.010426
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean((sim_log - obs_log) ** 2)
def mde(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median error (MdE) between the simulated and observed data.
.. image:: /pictures/MdE.png
**Range** -inf < MdE < inf, closer to zero is better.
**Notes** This metric indicates bias. It is similar to the mean error (ME), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mde(sim, obs)
-0.10000000000000009
Returns
-------
float
The median error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(simulated_array - observed_array)
def mdae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median absolute error (MdAE) between the simulated and observed data.
.. image:: /pictures/MdAE.png
**Range** 0 ≤ MdAE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean absolute error (MAE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdae(sim, obs)
0.75
Returns
-------
float
The median absolute error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(np.abs(simulated_array - observed_array))
def mdse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median squared error (MdSE) between the simulated and observed data.
.. image:: /pictures/MdSE.png
**Range** 0 ≤ MdSE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean squared error (MSE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdse(sim, obs)
0.625
Returns
-------
float
The median squared error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median((simulated_array - observed_array) ** 2)
def ed(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Euclidean distance between predicted and observed values in vector space.
.. image:: /pictures/ED.png
**Range** 0 ≤ ED < inf, smaller is better.
**Notes** Also sometimes referred to as the L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ed(sim, obs)
1.63707055437449
Returns
-------
float
The euclidean distance error value.
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.linalg.norm(observed_array - simulated_array)
def ned(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the normalized Euclidian distance between the simulated and observed data in vector
space.
.. image:: /pictures/NED.png
**Range** 0 ≤ NED < inf, smaller is better.
**Notes** Also sometimes referred to as the squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The normalized euclidean distance value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ned(sim, obs)
0.2872053604165771
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array / np.mean(observed_array)
b = simulated_array / np.mean(simulated_array)
return np.linalg.norm(a - b)
def rmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square error between the simulated and observed data.
.. image:: /pictures/RMSE.png
**Range** 0 ≤ RMSE < inf, smaller is better.
**Notes:** The standard deviation of the residuals. A lower spread indicates that the points
are better concentrated around the line of best fit (linear). Random errors do not cancel.
This metric will highlights larger errors.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.rmse(sim, obs)
0.668331255192114
References
----------
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.sqrt(np.mean((simulated_array - observed_array) ** 2))
def rmsle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square log error between the simulated and observed data.
.. image:: /pictures/RMSLE.png
**Range:** 0 ≤ RMSLE < inf. Smaller is better, and it does not indicate bias.
**Notes:** Random errors do not cancel while using this metric. This metric limits the
impact of outliers by more evenly weighting high and low values. To calculate the log values,
each value in the observed and simulated array is increased by one unit in order to avoid
run-time errors and nan values (function np.log1p).
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square log error value.
Examples
--------
Notice that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.rmsle(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
"""
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf, remove_neg=remove_neg,
remove_zero=remove_zero)
return np.sqrt(np.mean(np.power(np.log1p(simulated_array) - np.log1p(observed_array), 2)))
def nrmse_range(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the range normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Range.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the range of the observed time series (x).
Normalizing allows comparison between data sets with different scales. The NRMSErange is the
most sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The range normalized root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_range(sim, obs)
0.0891108340256152
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_max = np.max(observed_array)
obs_min = np.min(observed_array)
return rmse_value / (obs_max - obs_min)
def nrmse_mean(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Mean.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the mean of the observed time series (x).
Normalizing allows comparison between data sets with different scales.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_mean(sim, obs)
0.11725109740212526
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_mean = np.mean(observed_array)
return rmse_value / obs_mean
def nrmse_iqr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the IQR normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_IQR.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the interquartile range of the observed time
series (x). Normalizing allows comparison between data sets with different scales.
The NRMSEquartile is the least sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The IQR normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_iqr(sim, obs)
0.2595461185212093
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
q1 = np.percentile(observed_array, 25)
q3 = np.percentile(observed_array, 75)
iqr = q3 - q1
return rmse_value / iqr
def irmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the inertial root mean square error (IRMSE) between the simulated and observed data.
.. image:: /pictures/IRMSE.png
**Range:** 0 ≤ IRMSE < inf, lower is better.
**Notes:** This metric is the RMSE devided by by the standard deviation of the gradient of the
observed timeseries data. This metric is meant to be help understand the ability of the model
to predict changes in observation.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The inertial root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.irmse(sim, obs)
0.14572738134831856
References
----------
- Daga, M., Deo, M.C., 2009. Alternative data-driven methods to estimate wind from waves by
inverse modeling. Natural Hazards 49(2) 293-310.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Getting the gradient of the observed data
obs_len = observed_array.size
obs_grad = observed_array[1:obs_len] - observed_array[0:obs_len - 1]
# Standard deviation of the gradient
obs_grad_std = np.std(obs_grad, ddof=1)
# Divide RMSE by the standard deviation of the gradient of the observed data
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
return rmse_value / obs_grad_std
def pearson_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the pearson correlation coefficient.
.. image:: /pictures/R_pearson.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The pearson r coefficient measures linear correlation. It is sensitive to outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Pearson correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.pearson_r(sim, obs)
0.9610793632835262
References
----------
- Pearson, K. (1895). Note on regression and inheritance in the case of two parents.
Proceedings of the Royal Society of London, 58, 240-242.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
top = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1 = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2 = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
return top / (bot1 * bot2)
def spearman_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the spearman rank correlation coefficient.
.. image:: /pictures/R_spearman.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The spearman r coefficient measures the monotonic relation between simulated and
observed data. Because it uses a nonparametric measure of rank correlation, it is less sensitive
to outliers compared to the Pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spearman rank correlation coefficient.
Examples
----------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.spearman_r(sim, obs)
0.942857142857143
References
----------
- Spearman C (1904). "The proof and measurement of association between two things". American
Journal of Psychology. 15: 72–101. doi:10.2307/1412159
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rank_sim = rankdata(simulated_array)
rank_obs = rankdata(observed_array)
mean_rank_sim = np.mean(rank_sim)
mean_rank_obs = np.mean(rank_obs)
top = np.mean((rank_obs - mean_rank_obs) * (rank_sim - mean_rank_sim))
bot = np.sqrt(
np.mean((rank_obs - mean_rank_obs) ** 2) * np.mean((rank_sim - mean_rank_sim) ** 2))
return top / bot
def r_squared(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Coefficient of Determination (r2).
.. image:: /pictures/r2.png
**Range:** 0 ≤ r2 ≤ 1. 1 indicates perfect correlation, 0 indicates complete randomness.
**Notes:** The Coefficient of Determination measures the linear relation between simulated and
observed data. Because it is the pearson correlation coefficient squared, it is more heavily
affected by outliers than the pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The coefficient of determination (R^2).
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.r_squared(sim, obs)
0.9236735425294681
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array - np.mean(observed_array)
b = simulated_array - np.mean(simulated_array)
return (np.sum(a * b)) ** 2 / (np.sum(a ** 2) * np.sum(b ** 2))
def acc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the anomaly correlation coefficient (ACC).
.. image:: /pictures/ACC.png
**Range:** -1 ≤ ACC ≤ 1. -1 indicates perfect negative correlation of the variation
pattern of the anomalies, 0 indicates complete randomness of the variation patterns of the
anomalies, 1 indicates perfect correlation of the variation pattern of the anomalies.
**Notes:** Common measure in the verification of spatial fields. Measures the correlation
between the variation pattern of the simulated data compared to the observed data.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The anomaly correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.acc(sim, obs)
0.8008994694029383
References
----------
- Langland, Rolf H., and Ryan N. Maue. “Recent Northern Hemisphere Mid-Latitude Medium-Range
Deterministic Forecast Skill.” Tellus A: Dynamic Meteorology and Oceanography 64,
no. 1 (2012): 17531.
- Miyakoda, K., G. D. Hembree, R. F. Strickler, and I. Shulman. “Cumulative Results of Extended
Forecast Experiments I. Model Performance for Winter Cases.” Monthly Weather Review 100, no.
12(1972): 836–55.
- Murphy, Allan H., and Edward S. Epstein. “Skill Scores and Correlation Coefficients in Model
Verification.” Monthly Weather Review 117, no. 3 (1989): 572–82.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - np.mean(simulated_array)
b = observed_array - np.mean(observed_array)
c = np.std(observed_array, ddof=1) * np.std(simulated_array, ddof=1) * simulated_array.size
return np.dot(a, b / c)
def mape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the mean absolute percentage error (MAPE).
.. image:: /pictures/MAPE.png
**Range:** 0% ≤ MAPE ≤ inf. 0% indicates perfect correlation, a larger error indicates a
larger percent error in the data.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
c = 100 / simulated_array.size
return c * np.sum(b)
def mapd(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the mean absolute percentage deviation (MAPD).
.. image:: /pictures/MAPD.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage deviation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mapd(sim, obs)
0.10526315789473682
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(np.abs(observed_array))
return a / b
def maape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the Mean Arctangent Absolute Percentage Error (MAAPE).
.. image:: /pictures/MAAPE.png
**Range:** 0 ≤ MAAPE < π/2, does not indicate bias, smaller is better.
**Notes:** Represents the mean absolute error as a percentage of the observed values. Handles
0s in the observed data. This metric is not as biased as MAPE by under-over predictions.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean arctangent absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
- Kim, S., Kim, H., 2016. A new metric of absolute percentage error for intermittent demand
forecasts. International Journal of Forecasting 32(3) 669-679.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
return np.mean(np.arctan(b))
def smape1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (1) (SMAPE1).
.. image:: /pictures/SMAPE1.png
**Range:** 0 ≤ SMAPE1 < 100%, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (1).
Examples
--------
Note that if we switch the simulated and observed arrays the result is the same
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape1(sim, obs)
5.871915694397428
>>> he.smape1(obs, sim)
5.871915694397428
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 100 / simulated_array.size
b = np.abs(simulated_array - observed_array)
c = np.abs(simulated_array) + np.abs(observed_array)
return a * np.sum(b / c)
def smape2(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (2) (SMAPE2).
.. image:: /pictures/SMAPE2.png
**Range:** 0 ≤ SMAPE1 < 200%, does not indicate bias, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE with only positive metric values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (2).
Examples
--------
Note that switching the simulated and observed arrays yields the same results
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape2(sim, obs)
11.743831388794856
>>> he.smape2(obs, sim)
11.743831388794856
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = (simulated_array + observed_array) / 2
c = 100 / simulated_array.size
return c * np.sum(np.abs(a / b))
def d(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d).
.. image:: /pictures/d.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d(sim, obs)
0.978477353035657
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (observed_array - simulated_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
return 1 - (np.sum(a) / np.sum((b + c) ** 2))
def d1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d1).
.. image:: /pictures/d1.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric. Compared
to the other index of agreement (d) it has a reduced impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (d1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1(sim, obs)
0.8434782608695652
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
obs_mean = np.mean(observed_array)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.abs(simulated_array - obs_mean)
c = np.abs(observed_array - obs_mean)
return 1 - np.sum(a) / np.sum(b + c)
def dr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the refined index of agreement (dr).
.. image:: /pictures/dr.png
**Range:** -1 ≤ dr < 1, does not indicate bias, larger is better.
**Notes:** Reformulation of Willmott’s index of agreement. This metric was created to address
issues in the index of agreement and the Nash-Sutcliffe efficiency metric. Meant to be a
flexible metric for use in climatology.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The refined index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dr(sim, obs)
0.847457627118644
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = 2 * np.sum(np.abs(observed_array - observed_array.mean()))
if a <= b:
return 1 - (a / b)
else:
return (b / a) - 1
def drel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the relative index of agreement (drel).
.. image:: /pictures/drel.png
**Range:** 0 ≤ drel < 1, does not indicate bias, larger is better.
**Notes:** Instead of absolute differences, this metric uses relative differences.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.drel(sim, obs)
0.9740868625579597
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = ((simulated_array - observed_array) / observed_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = ((b + c) / np.mean(observed_array)) ** 2
return 1 - (np.sum(a) / np.sum(e))
def dmod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the modified index of agreement (dmod).
.. image:: /pictures/dmod.png
**Range:** 0 ≤ dmod < 1, does not indicate bias, larger is better.
**Notes:** When j=1, this metric is the same as d1. As j becomes larger, outliers have a larger
impact on the value.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
Optional input indicating the j values desired. A higher j places more emphasis on
outliers. j is 1 by default.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified index of agreement.
Examples
--------
Note that using the default is the same as calculating the d1 metric. Changing the value of j
modification of the metric.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dmod(sim, obs) # Same as d1
0.8434782608695652
>>> he.dmod(sim, obs, j=1.5)
0.9413310986805733
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = (b + c) ** j
return 1 - (np.sum(a) / np.sum(e))
def watt_m(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute Watterson's M (M).
.. image:: /pictures/M.png
**Range:** -1 ≤ M < 1, does not indicate bias, larger is better.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
Watterson's M value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.watt_m(sim, obs)
0.8307913876595929
References
----------
- Watterson, I.G., 1996. Non‐dimensional measures of climate model performance. International
Journal of Climatology 16(4) 379-391.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 2 / np.pi
b = np.mean((simulated_array - observed_array) ** 2) # MSE
c = np.std(observed_array, ddof=1) ** 2 + np.std(simulated_array, ddof=1) ** 2
e = (np.mean(simulated_array) - np.mean(observed_array)) ** 2
f = c + e
return a * np.arcsin(1 - (b / f))
def mb_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute Mielke-Berry R value (MB R).
.. image:: /pictures/MB_R.png
**Range:** 0 ≤ MB R < 1, does not indicate bias, larger is better.
**Notes:** Compares prediction to probability it arose by chance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Mielke-Berry R value.
Notes
-----
If a more optimized version is desired, the `numba package <http://numba.pydata.org/doc.html>`_ can be implemented
for a much more optimized performance when computing this metric. An example is given below.
>>> from numba import njit, prange
>>> @njit(parallel=True, fastmath=True)
>>> def mb_par_fastmath(pred, obs): # uses LLVM compiler
>>> assert pred.size == obs.size
>>> n = pred.size
>>> tot = 0.0
>>> mae = 0.0
>>> for i in range(n):
>>> for j in prange(n):
>>> tot += abs(pred[i] - obs[j])
>>> mae += abs(pred[i] - obs[i])
>>> mae = mae / n
>>> mb = 1 - ((n ** 2) * mae / tot)
>>>
>>> return mb
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mb_r(sim, obs)
0.7726315789473684
References
----------
- Berry, K.J., Mielke, P.W., 1988. A Generalization of Cohen's Kappa Agreement Measure to
Interval Measurement and Multiple Raters. Educational and Psychological Measurement 48(4)
921-933.
- Mielke, P.W., Berry, K.J., 2007. Permutation methods: a distance function approach.
Springer Science & Business Media.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Calculate metric
n = simulated_array.size
tot = 0.0
for i in range(n):
tot = tot + np.sum(np.abs(simulated_array - observed_array[i]))
mae_val = np.sum(np.abs(simulated_array - observed_array)) / n
mb = 1 - ((n ** 2) * mae_val / tot)
return mb
def nse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Nash-Sutcliffe Efficiency.
.. image:: /pictures/NSE.png
**Range:** -inf < NSE < 1, does not indicate bias, larger is better.
**Notes:** The Nash-Sutcliffe efficiency metric compares prediction values to naive predictions
(i.e. average value). One major flaw of this metric is that it punishes a higher variance in
the observed values (denominator). This metric is analogous to the mean absolute error skill
score (MAESS) using the mean flow as a benchmark.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Nash-Sutcliffe Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse(sim, obs)
0.922093023255814
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
- McCuen, R.H., Knight, Z., Cutter, A.G., 2006. Evaluation of the Nash-Sutcliffe Efficiency
Index. Journal of Hydraulic Engineering.
- Nash, J.E., Sutcliffe, J.V., 1970. River flow forecasting through conceptual models part
I — A discussion of principles. Journal of Hydrology 282-290.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** 2
b = (np.abs(observed_array - np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def nse_mod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the modified Nash-Sutcliffe efficiency (NSE mod).
.. image:: /pictures/NSEmod.png
**Range:** -inf < NSE (mod) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
If given, sets the value of j to the input. j is 1 by default. A higher j gives more
emphasis to outliers
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_mod(sim, obs)
0.6949152542372882
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = (np.abs(observed_array - np.mean(observed_array))) ** j
return 1 - (np.sum(a) / np.sum(b))
def nse_rel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the relative Nash-Sutcliffe efficiency (NSE rel).
.. image:: /pictures/NSErel.png
**Range:** -inf < NSE (rel) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_rel(sim, obs)
0.9062004687708474
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs((simulated_array - observed_array) / observed_array)) ** 2
b = (np.abs((observed_array - np.mean(observed_array)) / np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def kge_2009(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""Compute the Kling-Gupta efficiency (2009).
.. image:: /pictures/KGE_2009.png
**Range:** -inf < KGE (2009) < 1, larger is better.
**Notes:** Gupta et al. (2009) created this metric to demonstrate the relative importance of
the three components of the NSE, which are correlation, bias and variability. This was done
with hydrologic modeling as the context. This metric is meant to address issues with the NSE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), Alpha, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, alpha, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2009) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2009(sim, obs)
0.912223072345668
>>> he.kge_2009(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.927910707932087, 1.0058823529411764, 0.9181073779138655)
References
----------
- Gupta, H. V., Kling, H., Yilmaz, K. K., & Martinez, G. F. (2009). Decomposition of the mean
squared error and NSE performance criteria: Implications for improving hydrological modelling.
Journal of Hydrology, 377(1-2), 80-91.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array, ddof=1)
obs_sigma = np.std(observed_array, ddof=1)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
if obs_mean != 0:
beta = sim_mean / obs_mean
else:
beta = np.nan
# Relative variability between simulated and observed values
if obs_sigma != 0:
alpha = sim_sigma / obs_sigma
else:
alpha = np.nan
if not np.isnan(beta) and not np.isnan(alpha):
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (alpha - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Alpha is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, alpha, beta, kge
else:
return kge
def kge_2012(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""
Compute the Kling-Gupta efficiency (2012).
.. image:: /pictures/KGE_2012.png
**Range:** -inf < KGE (2012) < 1, does not indicate bias, larger is better.
**Notes:** The modified version of the KGE (2009). Kling proposed this version to avoid
cross-correlation between bias and variability ratios.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), gamma, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, gamma, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2012) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2012(sim, obs)
0.9122230723456678
>>> he.kge_2012(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.9224843295231272, 1.0058823529411764, 0.9132923608280753)
References
----------
- Kling, H., Fuchs, M., & Paulin, M. (2012). Runoff conditions in the upper Danube basin under
an ensemble of climate change scenarios. Journal of Hydrology, 424, 264-277.
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array)
obs_sigma = np.std(observed_array)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
beta = sim_mean / obs_mean
# CV is the coefficient of variation (standard deviation / mean)
sim_cv = sim_sigma / sim_mean
obs_cv = obs_sigma / obs_mean
# Variability Ratio, or the ratio of simulated CV to observed CV
gam = sim_cv / obs_cv
if obs_mean != 0 and obs_sigma != 0 and sim_mean != 0:
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (gam - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
if sim_mean == 0:
warnings.warn(
'Warning: The simulated data mean is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, gam, beta, kge
else:
return kge
def lm_index(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""
Compute the Legate-McCabe Efficiency Index.
.. image:: /pictures/E1p.png
**Range:** 0 ≤ E1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.lm_index(sim, obs)
0.6949152542372882
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
mean_obs = np.mean(observed_array)
if obs_bar_p is not None:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def d1_p(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""Compute the Legate-McCabe Index of Agreement.
.. image:: /pictures/D1p.png
**Range:** 0 ≤ d1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1_p(sim, obs)
0.8434782608695652
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
if obs_bar_p is not None:
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - obs_bar_p) + np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
mean_obs = np.mean(observed_array)
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - mean_obs) + np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def ve(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Volumetric Efficiency (VE).
.. image:: /pictures/VE.png
**Range:** 0 ≤ VE < 1 smaller is better, does not indicate bias.
**Notes:** Represents the error as a percentage of flow.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Volumetric Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ve(sim, obs)
0.8947368421052632
References
----------
- Criss, R.E., Winston, W.E., 2008. Do Nash values have value? Discussion and alternate
proposals. Hydrological Processes 22(14) 2723.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(observed_array)
return 1 - (a / b)
def sa(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Angle (SA).
.. image:: /pictures/SA.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral angle metric measures the angle between the two vectors in hyperspace.
It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Angle value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sa(sim, obs)
0.10816831366492945
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(simulated_array, observed_array)
b = np.linalg.norm(simulated_array) * np.linalg.norm(observed_array)
return np.arccos(a / b)
def sc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Correlation (SC).
.. image:: /pictures/SC.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral correlation metric measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Correlation value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sc(sim, obs)
0.27991341383646606
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(observed_array - np.mean(observed_array), simulated_array - np.mean(simulated_array))
b = np.linalg.norm(observed_array - np.mean(observed_array))
c = np.linalg.norm(simulated_array - np.mean(simulated_array))
e = b * c
return np.arccos(a / e)
def sid(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Information Divergence (SID).
.. image:: /pictures/SID.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral information divergence measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral information divergence value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sid(sim, obs)
0.03517616895318012
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
first = (observed_array / np.mean(observed_array)) - (
simulated_array / np.mean(simulated_array))
second1 = np.log10(observed_array) - np.log10(np.mean(observed_array))
second2 = np.log10(simulated_array) - np.log10(np.mean(simulated_array))
return np.dot(first, second1 - second2)
def sga(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Gradient Angle (SGA).
.. image:: /pictures/SGA.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral gradient angle measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
SG is the gradient of the simulated or observed time series.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Gradient Angle.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sga(sim, obs)
0.26764286472739834
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sgx = observed_array[1:] - observed_array[:observed_array.size - 1]
sgy = simulated_array[1:] - simulated_array[:simulated_array.size - 1]
a = np.dot(sgx, sgy)
b = np.linalg.norm(sgx) * np.linalg.norm(sgy)
return np.arccos(a / b)
####################################################################################################
# H Metrics: Methods from Tornqvist L, Vartia P, and Vartia YO. (1985) #
####################################################################################################
def h1_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the H1 mean error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mhe(sim, obs)
0.002106551840594386
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(h)
def h1_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H1 absolute error.
.. image:: /pictures/H1.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The H1 absolute error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mahe(sim, obs)
0.11639226612630865
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(np.abs(h))
def h1_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H1 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean squared H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_rmshe(sim, obs)
0.12865571253672756
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.sqrt(np.mean(h ** 2))
def h2_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean error.
.. image:: /pictures/H2.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mhe(sim, obs)
-0.015319829424307036
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(h)
def h2_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean absolute error.
.. image:: /pictures/H2.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mahe(sim, obs)
0.11997591408039167
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(np.abs(h))
def h2_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_rmshe(sim, obs)
0.1373586680669673
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.sqrt(np.mean(h ** 2))
def h3_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 mean error.
.. image:: /pictures/H3.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mhe(sim, obs)
-0.006322019630356533
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(h)
def h3_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H3 mean absolute error.
.. image:: /pictures/H3.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mahe(sim, obs)
0.11743831388794855
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(np.abs(h))
def h3_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 root mean square error.
.. image:: /pictures/H3.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.sqrt(np.mean(h ** 2))
def h4_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mhe(sim, obs)
-0.0064637371129817
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(h)
def h4_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H4 mean absolute error.
.. image:: /pictures/H4.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mahe(sim, obs)
0.11781032209144082
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(np.abs(h))
def h4_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_rmshe(sim, obs)
0.13200901963465006
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.sqrt(np.mean(h ** 2))
def h5_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean error.
.. image:: /pictures/H5.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mhe(sim, obs)
-0.006606638791856322
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(h)
def h5_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean absolute error.
.. image:: /pictures/H5.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mahe(sim, obs)
0.11818409010335018
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(np.abs(h))
def h5_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 root mean square error.
.. image:: /pictures/H5.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_rmshe(sim, obs)
0.13254476469410933
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h6_mhe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H6 mean error.
.. image:: /pictures/H6.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mhe(sim, obs)
-0.006322019630356514
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(h)
def h6_mahe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""Compute the H6 mean absolute error.
.. image:: /pictures/H6.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mahe(sim, obs)
0.11743831388794852
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(np.abs(h))
def h6_rmshe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the H6 root mean square error.
.. image:: /pictures/H6.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h7_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean error.
.. image:: /pictures/H7.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mhe(sim, obs)
0.0026331898007430263
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(h)
def h7_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean absolute error.
.. image:: /pictures/H7.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mahe(sim, obs)
0.14549033265788583
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(np.abs(h))
def h7_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 root mean square error.
.. image:: /pictures/H7.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_rmshe(sim, obs)
0.16081964067090945
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
def h8_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H8 mean error.
.. image:: /pictures/H8.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mhe(sim, obs)
0.0018056158633666466
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(h)
def h8_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 mean absolute error.
.. image:: /pictures/H8.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mahe(sim, obs)
0.099764799536836
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(np.abs(h))
def h8_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 root mean square error.
.. image:: /pictures/H8.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_rmshe(sim, obs)
0.11027632503148076
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
# def h9(simulated_array, observed_array, h_type='mhe', k=1):
# h = (simulated_array / observed_array - 1) / \
# np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
# if h_type == 'mhe':
# return h.mean()
# elif h_type == 'ahe':
# return np.abs(h).mean()
# elif h_type == 'rmshe':
# return np.sqrt((h**2).mean())
# else:
# raise RuntimeError("The three types available are 'mhe', 'ahe', and 'rmshe'.")
def h10_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean error.
.. image:: /pictures/H10.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h10_mhe(sim, obs)
-0.0012578676058971154
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(h)
def h10_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean absolute error.
.. image:: /pictures/H10.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_mahe(sim, obs), 6)
0.094636
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(np.abs(h))
def h10_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 root mean square error.
.. image:: /pictures/H10.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_rmshe(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.sqrt(np.mean(h ** 2))
###################################################################################################
# Statistical Error Metrics for Distribution Testing #
###################################################################################################
def g_mean_diff(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the geometric mean difference.
.. image:: /pictures/GMD.png
**Range:**
**Notes:** For the difference of geometric means, the geometric mean is computed for each of
two samples then their difference is taken.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The geometric mean difference value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.g_mean_diff(sim, obs)
0.988855412098022
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.exp(gmean(sim_log) - gmean(obs_log))
def mean_var(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the mean variance.
.. image:: /pictures/MV.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean variance.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.mean_var(sim, obs), 6)
0.010641
References
----------
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.var(np.log1p(observed_array) - np.log1p(simulated_array))
####################################################################################################
# HELPER FUNCTIONS AND API INFORMATION #
####################################################################################################
metric_names = [
'Mean Error', 'Mean Absolute Error', 'Mean Squared Error', 'Mean Log Error',
'Mean Absolute Log Error', 'Mean Squared Log Error', 'Median Error', 'Median Absolute Error',
'Median Squared Error', 'Eclidean Distance', 'Normalized Eclidean Distance',
'Root Mean Square Error', 'Root Mean Squared Log Error',
'Normalized Root Mean Square Error - Range', 'Normalized Root Mean Square Error - Mean',
'Normalized Root Mean Square Error - IQR', 'Inertial Root Mean Square Error',
'Mean Absolute Scaled Error', 'Coefficient of Determination', 'Pearson Correlation Coefficient',
'Spearman Rank Correlation Coefficient', 'Anomaly Correlation Coefficient',
'Mean Absolute Percentage Error', 'Mean Absolute Percentage Deviation',
'Mean Arctangent Absolute Percentage Error', 'Symmetric Mean Absolute Percentage Error (1)',
'Symmetric Mean Absolute Percentage Error (2)', 'Index of Agreement (d)',
'Index of Agreement (d1)', 'Modified Index of Agreement', 'Relative Index of Agreement',
'Index of Agreement Refined (dr)', "Watterson's M", 'Mielke-Berry R',
'Nash-Sutcliffe Efficiency', 'Modified Nash-Sutcliffe Efficiency',
'Relative Nash-Sutcliffe Efficiency', 'Kling-Gupta Efficiency (2009)',
'Kling-Gupta Efficiency (2012)', 'Legate-McCabe Efficiency Index',
'Legate-McCabe Index of Agreement', 'Volumetric Efficiency', 'Spectral Angle',
'Spectral Correlation', 'Spectral Information Divergence', 'Spectral Gradient Angle',
'Mean H1 Error', 'Mean Absolute H1 Error', 'Root Mean Square H1 Error', 'Mean H2 Error',
'Mean Absolute H2 Error', 'Root Mean Square H2 Error', 'Mean H3 Error',
'Mean Absolute H3 Error', 'Root Mean Square H3 Error', 'Mean H4 Error',
'Mean Absolute H4 Error', 'Root Mean Square H4 Error', 'Mean H5 Error',
'Mean Absolute H5 Error', 'Root Mean Square H5 Error', 'Mean H6 Error',
'Mean Absolute H6 Error', 'Root Mean Square H6 Error', 'Mean H7 Error',
'Mean Absolute H7 Error', 'Root Mean Square H7 Error', 'Mean H8 Error',
'Mean Absolute H8 Error', 'Root Mean Square H8 Error', 'Mean H10 Error',
'Mean Absolute H10 Error', 'Root Mean Square H10 Error', 'Geometric Mean Difference',
'Mean Variance'
]
metric_abbr = [
'ME', 'MAE', 'MSE', 'MLE', 'MALE', 'MSLE', 'MdE', 'MdAE', 'MdSE', 'ED', 'NED', 'RMSE', 'RMSLE',
'NRMSE (Range)', 'NRMSE (Mean)', 'NRMSE (IQR)', 'IRMSE', 'MASE', 'r2', 'R (Pearson)',
'R (Spearman)', 'ACC', 'MAPE', 'MAPD', 'MAAPE', 'SMAPE1', 'SMAPE2', 'd', 'd1', 'd (Mod.)',
'd (Rel.)', 'dr', 'M', '(MB) R', 'NSE', 'NSE (Mod.)', 'NSE (Rel.)', 'KGE (2009)', 'KGE (2012)',
"E1'", "D1'", 'VE', 'SA', 'SC', 'SID', 'SGA', 'H1 (MHE)', 'H1 (MAHE)', 'H1 (RMSHE)', 'H2 (MHE)',
'H2 (MAHE)', 'H2 (RMSHE)', 'H3 (MHE)', 'H3 (MAHE)', 'H3 (RMSHE)', 'H4 (MHE)', 'H4 (MAHE)',
'H4 (RMSHE)', 'H5 (MHE)', 'H5 (MAHE)', 'H5 (RMSHE)', 'H6 (MHE)', 'H6 (MAHE)', 'H6 (RMSHE)',
'H7 (MHE)', 'H7 (MAHE)', 'H7 (RMSHE)', 'H8 (MHE)', 'H8 (MAHE)', 'H8 (RMSHE)', 'H10 (MHE)',
'H10 (MAHE)', 'H10 (RMSHE)', 'GMD', 'MV'
]
function_list = [
me, mae, mse, mle, male, msle, mde, mdae, mdse, ed, ned, rmse, rmsle, nrmse_range, nrmse_mean,
nrmse_iqr, irmse, mase, r_squared, pearson_r, spearman_r, acc, mape, mapd, maape, smape1,
smape2, d, d1, dmod, drel, dr, watt_m, mb_r, nse, nse_mod, nse_rel, kge_2009, kge_2012,
lm_index, d1_p, ve, sa, sc, sid, sga, h1_mhe, h1_mahe, h1_rmshe, h2_mhe, h2_mahe, h2_rmshe,
h3_mhe, h3_mahe, h3_rmshe, h4_mhe, h4_mahe, h4_rmshe, h5_mhe, h5_mahe, h5_rmshe, h6_mhe,
h6_mahe, h6_rmshe, h7_mhe, h7_mahe, h7_rmshe, h8_mhe, h8_mahe, h8_rmshe, h10_mhe, h10_mahe,
h10_rmshe, g_mean_diff, mean_var,
]
# Assign some properties to each function for ease of use for users
for i in range(len(function_list)):
function_list[i].name = metric_names[i]
function_list[i].abbr = metric_abbr[i]
def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Removes the nan, negative, and inf values in two numpy arrays"""
sim_copy = np.copy(simulated_array)
obs_copy = np.copy(observed_array)
# Checking to see if the vectors are the same length
assert sim_copy.ndim == 1, "The simulated array is not one dimensional."
assert obs_copy.ndim == 1, "The observed array is not one dimensional."
if sim_copy.size != obs_copy.size:
raise RuntimeError("The two ndarrays are not the same size.")
# Treat missing data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain nan values
all_treatment_array = np.ones(obs_copy.size, dtype=bool)
if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_nan = np.isnan(sim_copy)
obs_nan = np.isnan(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_nan] = replace_nan
obs_copy[obs_nan] = replace_nan
warnings.warn("Elements(s) {} contained NaN values in the simulated array and "
"elements(s) {} contained NaN values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_nan)[0],
np.where(obs_nan)[0]),
UserWarning)
else:
# Getting the indices of the nan values, combining them, and informing user.
nan_indices_fcst = ~np.isnan(sim_copy)
nan_indices_obs = ~np.isnan(obs_copy)
all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)
warnings.warn("Row(s) {} contained NaN values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_nan_indices)[0]),
UserWarning)
if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_inf = np.isinf(sim_copy)
obs_inf = np.isinf(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_inf] = replace_inf
obs_copy[obs_inf] = replace_inf
warnings.warn("Elements(s) {} contained Inf values in the simulated array and "
"elements(s) {} contained Inf values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_inf)[0],
np.where(obs_inf)[0]),
UserWarning)
else:
inf_indices_fcst = ~(np.isinf(sim_copy))
inf_indices_obs = ~np.isinf(obs_copy)
all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)
warnings.warn(
"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows "
"are zero indexed).".format(np.where(~all_inf_indices)[0]),
UserWarning
)
# Treat zero data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain zero values
if remove_zero:
if (obs_copy == 0).any() or (sim_copy == 0).any():
zero_indices_fcst = ~(sim_copy == 0)
zero_indices_obs = ~(obs_copy == 0)
all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)
warnings.warn(
"Row(s) {} contained zero values and the row(s) have been removed (Rows are "
"zero indexed).".format(np.where(~all_zero_indices)[0]),
UserWarning
)
# Treat negative data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain negative values
# Ignore runtime warnings from comparing
if remove_neg:
with np.errstate(invalid='ignore'):
obs_copy_bool = obs_copy < 0
sim_copy_bool = sim_copy < 0
if obs_copy_bool.any() or sim_copy_bool.any():
neg_indices_fcst = ~sim_copy_bool
neg_indices_obs = ~obs_copy_bool
all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)
warnings.warn("Row(s) {} contained negative values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_neg_indices)[0]),
UserWarning)
obs_copy = obs_copy[all_treatment_array]
sim_copy = sim_copy[all_treatment_array]
return sim_copy, obs_copy
if __name__ == "__main__":
pass
|
BYU-Hydroinformatics/HydroErr | HydroErr/HydroErr.py | maape | python | def maape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
return np.mean(np.arctan(b)) | Compute the the Mean Arctangent Absolute Percentage Error (MAAPE).
.. image:: /pictures/MAAPE.png
**Range:** 0 ≤ MAAPE < π/2, does not indicate bias, smaller is better.
**Notes:** Represents the mean absolute error as a percentage of the observed values. Handles
0s in the observed data. This metric is not as biased as MAPE by under-over predictions.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean arctangent absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
- Kim, S., Kim, H., 2016. A new metric of absolute percentage error for intermittent demand
forecasts. International Journal of Forecasting 32(3) 669-679. | train | https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L1937-L2010 | [
"def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,\n remove_neg=False, remove_zero=False):\n \"\"\"Removes the nan, negative, and inf values in two numpy arrays\"\"\"\n sim_copy = np.copy(simulated_array)\n obs_copy = np.copy(observed_array)\n\n # Checking to see if the vectors are the same length\n assert sim_copy.ndim == 1, \"The simulated array is not one dimensional.\"\n assert obs_copy.ndim == 1, \"The observed array is not one dimensional.\"\n\n if sim_copy.size != obs_copy.size:\n raise RuntimeError(\"The two ndarrays are not the same size.\")\n\n # Treat missing data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain nan values\n all_treatment_array = np.ones(obs_copy.size, dtype=bool)\n\n if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_nan = np.isnan(sim_copy)\n obs_nan = np.isnan(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_nan] = replace_nan\n obs_copy[obs_nan] = replace_nan\n\n warnings.warn(\"Elements(s) {} contained NaN values in the simulated array and \"\n \"elements(s) {} contained NaN values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_nan)[0],\n np.where(obs_nan)[0]),\n UserWarning)\n else:\n # Getting the indices of the nan values, combining them, and informing user.\n nan_indices_fcst = ~np.isnan(sim_copy)\n nan_indices_obs = ~np.isnan(obs_copy)\n all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)\n\n warnings.warn(\"Row(s) {} contained NaN values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_nan_indices)[0]),\n UserWarning)\n\n if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_inf = np.isinf(sim_copy)\n obs_inf = np.isinf(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_inf] = replace_inf\n obs_copy[obs_inf] = replace_inf\n\n warnings.warn(\"Elements(s) {} contained Inf values in the simulated array and \"\n \"elements(s) {} contained Inf values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_inf)[0],\n np.where(obs_inf)[0]),\n UserWarning)\n else:\n inf_indices_fcst = ~(np.isinf(sim_copy))\n inf_indices_obs = ~np.isinf(obs_copy)\n all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)\n\n warnings.warn(\n \"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows \"\n \"are zero indexed).\".format(np.where(~all_inf_indices)[0]),\n UserWarning\n )\n\n # Treat zero data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain zero values\n if remove_zero:\n if (obs_copy == 0).any() or (sim_copy == 0).any():\n zero_indices_fcst = ~(sim_copy == 0)\n zero_indices_obs = ~(obs_copy == 0)\n all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)\n\n warnings.warn(\n \"Row(s) {} contained zero values and the row(s) have been removed (Rows are \"\n \"zero indexed).\".format(np.where(~all_zero_indices)[0]),\n UserWarning\n )\n\n # Treat negative data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain negative values\n\n # Ignore runtime warnings from comparing\n if remove_neg:\n with np.errstate(invalid='ignore'):\n obs_copy_bool = obs_copy < 0\n sim_copy_bool = sim_copy < 0\n\n if obs_copy_bool.any() or sim_copy_bool.any():\n neg_indices_fcst = ~sim_copy_bool\n neg_indices_obs = ~obs_copy_bool\n all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)\n\n warnings.warn(\"Row(s) {} contained negative values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_neg_indices)[0]),\n UserWarning)\n\n obs_copy = obs_copy[all_treatment_array]\n sim_copy = sim_copy[all_treatment_array]\n\n return sim_copy, obs_copy\n"
] | # -*- coding: utf-8 -*-
"""
HydroErr contains a library of goodness of fit metrics that measure hydrologic skill.
Each metric is contained in function, and every function has the parameters to treat missing values as
well as remove zero and negative values from the timeseries data.
Each function contains two properties, name and abbr. These can be used in the Hydrostats package when creating tables
and adding metrics to the plots. Link to the hydrostats package: https://github.com/BYU-Hydroinformatics/Hydrostats.
An example of this functionality is shown below.
>>> import HydroErr as he
>>>
>>> he.acc.name
'Anomaly Correlation Coefficient'
>>> he.acc.abbr
'ACC'
"""
from __future__ import division
import numpy as np
from scipy.stats import gmean, rankdata
import warnings
__all__ = ['me', 'mae', 'mse', 'mle', 'male', 'msle', 'mde', 'mdae', 'mdse', 'ed', 'ned', 'rmse',
'rmsle', 'nrmse_range', 'nrmse_mean', 'nrmse_iqr', 'irmse', 'mase', 'r_squared',
'pearson_r', 'spearman_r', 'acc', 'mape', 'mapd', 'maape', 'smape1', 'smape2', 'd', 'd1',
'dmod', 'drel', 'dr', 'watt_m', 'mb_r', 'nse', 'nse_mod', 'nse_rel', 'kge_2009',
'kge_2012', 'lm_index', 'd1_p', 've', 'sa', 'sc', 'sid', 'sga', 'h1_mhe', 'h1_mahe',
'h1_rmshe', 'h2_mhe', 'h2_mahe', 'h2_rmshe', 'h3_mhe', 'h3_mahe', 'h3_rmshe', 'h4_mhe',
'h4_mahe', 'h4_rmshe', 'h5_mhe', 'h5_mahe', 'h5_rmshe', 'h6_mhe', 'h6_mahe', 'h6_rmshe',
'h7_mhe', 'h7_mahe', 'h7_rmshe', 'h8_mhe', 'h8_mahe', 'h8_rmshe', 'h10_mhe', 'h10_mahe',
'h10_rmshe', 'g_mean_diff', 'mean_var']
####################################################################################################
# General and Hydrological Error Metrics #
####################################################################################################
def me(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean error of the simulated and observed data.
.. image:: /pictures/ME.png
**Range:** -inf < MAE < inf, data units, closer to zero is better, indicates bias.
**Notes:** The mean error (ME) measures the difference between the simulated data and the
observed data. For the mean error, a smaller number indicates a better fit to the original
data. Note that if the error is in the form of random noise, the mean error will be very small,
which can skew the accuracy of this metric. ME is cumulative and will be small even if there
are large positive and negative errors that balance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean error value.
Examples
--------
Note that in this example the random noise cancels, leaving a very small ME.
>>> import HydroErr as he
>>> import numpy as np
>>> # Seed for reproducibility
>>> np.random.seed(54839)
>>> x = np.arange(100) / 20
>>> sim = np.sin(x) + 2
>>> obs = sim * (((np.random.rand(100) - 0.5) / 10) + 1)
>>> he.me(sim, obs)
-0.006832220968967168
References
----------
- Fisher, R.A., 1920. A Mathematical Examination of the Methods of Determining the Accuracy of
an Observation by the Mean Error, and by the Mean Square Error. Monthly Notices of the Royal
Astronomical Society 80 758 - 770.
"""
# Treating missing values
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero)
return np.mean(simulated_array - observed_array)
def mae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute error of the simulated and observed data.
.. image:: /pictures/MAE.png
**Range:** 0 ≤ MAE < inf, data units, smaller is better.
**Notes:** The ME measures the absolute difference between the simulated data and the observed
data. For the mean abolute error, a smaller number indicates a better fit to the original data.
Also note that random errors do not cancel. Also referred to as an L1-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute error value.
References
----------
- Willmott, Cort J., and Kenji Matsuura. “Advantages of the Mean Absolute Error (MAE) over the
Root Mean Square Error (RMSE) in Assessing Average Model Performance.” Climate Research 30,
no. 1 (2005): 79–82.
- Willmott, Cort J., and Kenji Matsuura. “On the Use of Dimensioned Measures of Error to
Evaluate the Performance of Spatial Interpolators.” International Journal of Geographical
Information Science 20, no. 1 (2006): 89–102.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mae(sim, obs)
0.5666666666666665
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean(np.absolute(simulated_array - observed_array))
def mse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared error of the simulated and observed data.
.. image:: /pictures/MSE.png
**Range:** 0 ≤ MSE < inf, data units squared, smaller is better.
**Notes:** Random errors do not cancel, highlights larger errors, also referred to as a
squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mse(sim, obs)
0.4333333333333333
References
----------
- Wang, Zhou, and Alan C. Bovik. “Mean Squared Error: Love It or Leave It? A New Look at Signal
Fidelity Measures.” IEEE Signal Processing Magazine 26, no. 1 (2009): 98–117.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean((simulated_array - observed_array) ** 2)
def mle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean log error of the simulated and observed data.
.. image:: /pictures/MLE.png
**Range:** -inf < MLE < inf, data units, closer to zero is better.
**Notes** Same as the mean erro (ME) only use log ratios as the error term. Limits the impact of outliers, more
evenly weights high and low data values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mle(sim, obs)
0.002961767058151136
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(sim_log - obs_log)
def male(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean absolute log error of the simulated and observed data.
.. image:: /pictures/MALE.png
**Range:** 0 ≤ MALE < inf, data units squared, smaller is better.
**Notes** Same as MAE only use log ratios as the error term. Limits the impact of outliers,
more evenly weights high and low flows.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.male(sim, obs), 6)
0.090417
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(np.abs(sim_log - obs_log))
def msle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared log error of the simulated and observed data.
.. image:: /pictures/MSLE.png
**Range:** 0 ≤ MSLE < inf, data units squared, smaller is better.
**Notes** Same as the mean squared error (MSE) only use log ratios as the error term. Limits
the impact of outliers, more evenly weights high and low values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.msle(sim, obs), 6)
0.010426
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean((sim_log - obs_log) ** 2)
def mde(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median error (MdE) between the simulated and observed data.
.. image:: /pictures/MdE.png
**Range** -inf < MdE < inf, closer to zero is better.
**Notes** This metric indicates bias. It is similar to the mean error (ME), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mde(sim, obs)
-0.10000000000000009
Returns
-------
float
The median error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(simulated_array - observed_array)
def mdae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median absolute error (MdAE) between the simulated and observed data.
.. image:: /pictures/MdAE.png
**Range** 0 ≤ MdAE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean absolute error (MAE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdae(sim, obs)
0.75
Returns
-------
float
The median absolute error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(np.abs(simulated_array - observed_array))
def mdse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median squared error (MdSE) between the simulated and observed data.
.. image:: /pictures/MdSE.png
**Range** 0 ≤ MdSE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean squared error (MSE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdse(sim, obs)
0.625
Returns
-------
float
The median squared error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median((simulated_array - observed_array) ** 2)
def ed(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Euclidean distance between predicted and observed values in vector space.
.. image:: /pictures/ED.png
**Range** 0 ≤ ED < inf, smaller is better.
**Notes** Also sometimes referred to as the L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ed(sim, obs)
1.63707055437449
Returns
-------
float
The euclidean distance error value.
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.linalg.norm(observed_array - simulated_array)
def ned(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the normalized Euclidian distance between the simulated and observed data in vector
space.
.. image:: /pictures/NED.png
**Range** 0 ≤ NED < inf, smaller is better.
**Notes** Also sometimes referred to as the squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The normalized euclidean distance value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ned(sim, obs)
0.2872053604165771
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array / np.mean(observed_array)
b = simulated_array / np.mean(simulated_array)
return np.linalg.norm(a - b)
def rmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square error between the simulated and observed data.
.. image:: /pictures/RMSE.png
**Range** 0 ≤ RMSE < inf, smaller is better.
**Notes:** The standard deviation of the residuals. A lower spread indicates that the points
are better concentrated around the line of best fit (linear). Random errors do not cancel.
This metric will highlights larger errors.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.rmse(sim, obs)
0.668331255192114
References
----------
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.sqrt(np.mean((simulated_array - observed_array) ** 2))
def rmsle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square log error between the simulated and observed data.
.. image:: /pictures/RMSLE.png
**Range:** 0 ≤ RMSLE < inf. Smaller is better, and it does not indicate bias.
**Notes:** Random errors do not cancel while using this metric. This metric limits the
impact of outliers by more evenly weighting high and low values. To calculate the log values,
each value in the observed and simulated array is increased by one unit in order to avoid
run-time errors and nan values (function np.log1p).
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square log error value.
Examples
--------
Notice that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.rmsle(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
"""
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf, remove_neg=remove_neg,
remove_zero=remove_zero)
return np.sqrt(np.mean(np.power(np.log1p(simulated_array) - np.log1p(observed_array), 2)))
def nrmse_range(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the range normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Range.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the range of the observed time series (x).
Normalizing allows comparison between data sets with different scales. The NRMSErange is the
most sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The range normalized root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_range(sim, obs)
0.0891108340256152
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_max = np.max(observed_array)
obs_min = np.min(observed_array)
return rmse_value / (obs_max - obs_min)
def nrmse_mean(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Mean.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the mean of the observed time series (x).
Normalizing allows comparison between data sets with different scales.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_mean(sim, obs)
0.11725109740212526
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_mean = np.mean(observed_array)
return rmse_value / obs_mean
def nrmse_iqr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the IQR normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_IQR.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the interquartile range of the observed time
series (x). Normalizing allows comparison between data sets with different scales.
The NRMSEquartile is the least sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The IQR normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_iqr(sim, obs)
0.2595461185212093
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
q1 = np.percentile(observed_array, 25)
q3 = np.percentile(observed_array, 75)
iqr = q3 - q1
return rmse_value / iqr
def irmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the inertial root mean square error (IRMSE) between the simulated and observed data.
.. image:: /pictures/IRMSE.png
**Range:** 0 ≤ IRMSE < inf, lower is better.
**Notes:** This metric is the RMSE devided by by the standard deviation of the gradient of the
observed timeseries data. This metric is meant to be help understand the ability of the model
to predict changes in observation.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The inertial root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.irmse(sim, obs)
0.14572738134831856
References
----------
- Daga, M., Deo, M.C., 2009. Alternative data-driven methods to estimate wind from waves by
inverse modeling. Natural Hazards 49(2) 293-310.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Getting the gradient of the observed data
obs_len = observed_array.size
obs_grad = observed_array[1:obs_len] - observed_array[0:obs_len - 1]
# Standard deviation of the gradient
obs_grad_std = np.std(obs_grad, ddof=1)
# Divide RMSE by the standard deviation of the gradient of the observed data
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
return rmse_value / obs_grad_std
def mase(simulated_array, observed_array, m=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute scaled error between the simulated and observed data.
.. image:: /pictures/MASE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
m: int
If given, indicates the seasonal period m. If not given, the default is 1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute scaled error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mase(sim, obs)
0.17341040462427745
References
----------
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
start = m
end = simulated_array.size - m
a = np.mean(np.abs(simulated_array - observed_array))
b = np.abs(observed_array[start:observed_array.size] - observed_array[:end])
return a / (np.sum(b) / end)
def pearson_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the pearson correlation coefficient.
.. image:: /pictures/R_pearson.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The pearson r coefficient measures linear correlation. It is sensitive to outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Pearson correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.pearson_r(sim, obs)
0.9610793632835262
References
----------
- Pearson, K. (1895). Note on regression and inheritance in the case of two parents.
Proceedings of the Royal Society of London, 58, 240-242.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
top = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1 = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2 = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
return top / (bot1 * bot2)
def spearman_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the spearman rank correlation coefficient.
.. image:: /pictures/R_spearman.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The spearman r coefficient measures the monotonic relation between simulated and
observed data. Because it uses a nonparametric measure of rank correlation, it is less sensitive
to outliers compared to the Pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spearman rank correlation coefficient.
Examples
----------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.spearman_r(sim, obs)
0.942857142857143
References
----------
- Spearman C (1904). "The proof and measurement of association between two things". American
Journal of Psychology. 15: 72–101. doi:10.2307/1412159
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rank_sim = rankdata(simulated_array)
rank_obs = rankdata(observed_array)
mean_rank_sim = np.mean(rank_sim)
mean_rank_obs = np.mean(rank_obs)
top = np.mean((rank_obs - mean_rank_obs) * (rank_sim - mean_rank_sim))
bot = np.sqrt(
np.mean((rank_obs - mean_rank_obs) ** 2) * np.mean((rank_sim - mean_rank_sim) ** 2))
return top / bot
def r_squared(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Coefficient of Determination (r2).
.. image:: /pictures/r2.png
**Range:** 0 ≤ r2 ≤ 1. 1 indicates perfect correlation, 0 indicates complete randomness.
**Notes:** The Coefficient of Determination measures the linear relation between simulated and
observed data. Because it is the pearson correlation coefficient squared, it is more heavily
affected by outliers than the pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The coefficient of determination (R^2).
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.r_squared(sim, obs)
0.9236735425294681
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array - np.mean(observed_array)
b = simulated_array - np.mean(simulated_array)
return (np.sum(a * b)) ** 2 / (np.sum(a ** 2) * np.sum(b ** 2))
def acc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the anomaly correlation coefficient (ACC).
.. image:: /pictures/ACC.png
**Range:** -1 ≤ ACC ≤ 1. -1 indicates perfect negative correlation of the variation
pattern of the anomalies, 0 indicates complete randomness of the variation patterns of the
anomalies, 1 indicates perfect correlation of the variation pattern of the anomalies.
**Notes:** Common measure in the verification of spatial fields. Measures the correlation
between the variation pattern of the simulated data compared to the observed data.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The anomaly correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.acc(sim, obs)
0.8008994694029383
References
----------
- Langland, Rolf H., and Ryan N. Maue. “Recent Northern Hemisphere Mid-Latitude Medium-Range
Deterministic Forecast Skill.” Tellus A: Dynamic Meteorology and Oceanography 64,
no. 1 (2012): 17531.
- Miyakoda, K., G. D. Hembree, R. F. Strickler, and I. Shulman. “Cumulative Results of Extended
Forecast Experiments I. Model Performance for Winter Cases.” Monthly Weather Review 100, no.
12(1972): 836–55.
- Murphy, Allan H., and Edward S. Epstein. “Skill Scores and Correlation Coefficients in Model
Verification.” Monthly Weather Review 117, no. 3 (1989): 572–82.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - np.mean(simulated_array)
b = observed_array - np.mean(observed_array)
c = np.std(observed_array, ddof=1) * np.std(simulated_array, ddof=1) * simulated_array.size
return np.dot(a, b / c)
def mape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the mean absolute percentage error (MAPE).
.. image:: /pictures/MAPE.png
**Range:** 0% ≤ MAPE ≤ inf. 0% indicates perfect correlation, a larger error indicates a
larger percent error in the data.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
c = 100 / simulated_array.size
return c * np.sum(b)
def mapd(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the mean absolute percentage deviation (MAPD).
.. image:: /pictures/MAPD.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage deviation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mapd(sim, obs)
0.10526315789473682
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(np.abs(observed_array))
return a / b
def smape1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (1) (SMAPE1).
.. image:: /pictures/SMAPE1.png
**Range:** 0 ≤ SMAPE1 < 100%, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (1).
Examples
--------
Note that if we switch the simulated and observed arrays the result is the same
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape1(sim, obs)
5.871915694397428
>>> he.smape1(obs, sim)
5.871915694397428
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 100 / simulated_array.size
b = np.abs(simulated_array - observed_array)
c = np.abs(simulated_array) + np.abs(observed_array)
return a * np.sum(b / c)
def smape2(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (2) (SMAPE2).
.. image:: /pictures/SMAPE2.png
**Range:** 0 ≤ SMAPE1 < 200%, does not indicate bias, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE with only positive metric values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (2).
Examples
--------
Note that switching the simulated and observed arrays yields the same results
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape2(sim, obs)
11.743831388794856
>>> he.smape2(obs, sim)
11.743831388794856
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = (simulated_array + observed_array) / 2
c = 100 / simulated_array.size
return c * np.sum(np.abs(a / b))
def d(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d).
.. image:: /pictures/d.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d(sim, obs)
0.978477353035657
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (observed_array - simulated_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
return 1 - (np.sum(a) / np.sum((b + c) ** 2))
def d1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d1).
.. image:: /pictures/d1.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric. Compared
to the other index of agreement (d) it has a reduced impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (d1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1(sim, obs)
0.8434782608695652
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
obs_mean = np.mean(observed_array)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.abs(simulated_array - obs_mean)
c = np.abs(observed_array - obs_mean)
return 1 - np.sum(a) / np.sum(b + c)
def dr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the refined index of agreement (dr).
.. image:: /pictures/dr.png
**Range:** -1 ≤ dr < 1, does not indicate bias, larger is better.
**Notes:** Reformulation of Willmott’s index of agreement. This metric was created to address
issues in the index of agreement and the Nash-Sutcliffe efficiency metric. Meant to be a
flexible metric for use in climatology.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The refined index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dr(sim, obs)
0.847457627118644
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = 2 * np.sum(np.abs(observed_array - observed_array.mean()))
if a <= b:
return 1 - (a / b)
else:
return (b / a) - 1
def drel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the relative index of agreement (drel).
.. image:: /pictures/drel.png
**Range:** 0 ≤ drel < 1, does not indicate bias, larger is better.
**Notes:** Instead of absolute differences, this metric uses relative differences.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.drel(sim, obs)
0.9740868625579597
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = ((simulated_array - observed_array) / observed_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = ((b + c) / np.mean(observed_array)) ** 2
return 1 - (np.sum(a) / np.sum(e))
def dmod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the modified index of agreement (dmod).
.. image:: /pictures/dmod.png
**Range:** 0 ≤ dmod < 1, does not indicate bias, larger is better.
**Notes:** When j=1, this metric is the same as d1. As j becomes larger, outliers have a larger
impact on the value.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
Optional input indicating the j values desired. A higher j places more emphasis on
outliers. j is 1 by default.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified index of agreement.
Examples
--------
Note that using the default is the same as calculating the d1 metric. Changing the value of j
modification of the metric.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dmod(sim, obs) # Same as d1
0.8434782608695652
>>> he.dmod(sim, obs, j=1.5)
0.9413310986805733
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = (b + c) ** j
return 1 - (np.sum(a) / np.sum(e))
def watt_m(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute Watterson's M (M).
.. image:: /pictures/M.png
**Range:** -1 ≤ M < 1, does not indicate bias, larger is better.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
Watterson's M value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.watt_m(sim, obs)
0.8307913876595929
References
----------
- Watterson, I.G., 1996. Non‐dimensional measures of climate model performance. International
Journal of Climatology 16(4) 379-391.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 2 / np.pi
b = np.mean((simulated_array - observed_array) ** 2) # MSE
c = np.std(observed_array, ddof=1) ** 2 + np.std(simulated_array, ddof=1) ** 2
e = (np.mean(simulated_array) - np.mean(observed_array)) ** 2
f = c + e
return a * np.arcsin(1 - (b / f))
def mb_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute Mielke-Berry R value (MB R).
.. image:: /pictures/MB_R.png
**Range:** 0 ≤ MB R < 1, does not indicate bias, larger is better.
**Notes:** Compares prediction to probability it arose by chance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Mielke-Berry R value.
Notes
-----
If a more optimized version is desired, the `numba package <http://numba.pydata.org/doc.html>`_ can be implemented
for a much more optimized performance when computing this metric. An example is given below.
>>> from numba import njit, prange
>>> @njit(parallel=True, fastmath=True)
>>> def mb_par_fastmath(pred, obs): # uses LLVM compiler
>>> assert pred.size == obs.size
>>> n = pred.size
>>> tot = 0.0
>>> mae = 0.0
>>> for i in range(n):
>>> for j in prange(n):
>>> tot += abs(pred[i] - obs[j])
>>> mae += abs(pred[i] - obs[i])
>>> mae = mae / n
>>> mb = 1 - ((n ** 2) * mae / tot)
>>>
>>> return mb
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mb_r(sim, obs)
0.7726315789473684
References
----------
- Berry, K.J., Mielke, P.W., 1988. A Generalization of Cohen's Kappa Agreement Measure to
Interval Measurement and Multiple Raters. Educational and Psychological Measurement 48(4)
921-933.
- Mielke, P.W., Berry, K.J., 2007. Permutation methods: a distance function approach.
Springer Science & Business Media.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Calculate metric
n = simulated_array.size
tot = 0.0
for i in range(n):
tot = tot + np.sum(np.abs(simulated_array - observed_array[i]))
mae_val = np.sum(np.abs(simulated_array - observed_array)) / n
mb = 1 - ((n ** 2) * mae_val / tot)
return mb
def nse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Nash-Sutcliffe Efficiency.
.. image:: /pictures/NSE.png
**Range:** -inf < NSE < 1, does not indicate bias, larger is better.
**Notes:** The Nash-Sutcliffe efficiency metric compares prediction values to naive predictions
(i.e. average value). One major flaw of this metric is that it punishes a higher variance in
the observed values (denominator). This metric is analogous to the mean absolute error skill
score (MAESS) using the mean flow as a benchmark.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Nash-Sutcliffe Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse(sim, obs)
0.922093023255814
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
- McCuen, R.H., Knight, Z., Cutter, A.G., 2006. Evaluation of the Nash-Sutcliffe Efficiency
Index. Journal of Hydraulic Engineering.
- Nash, J.E., Sutcliffe, J.V., 1970. River flow forecasting through conceptual models part
I — A discussion of principles. Journal of Hydrology 282-290.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** 2
b = (np.abs(observed_array - np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def nse_mod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the modified Nash-Sutcliffe efficiency (NSE mod).
.. image:: /pictures/NSEmod.png
**Range:** -inf < NSE (mod) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
If given, sets the value of j to the input. j is 1 by default. A higher j gives more
emphasis to outliers
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_mod(sim, obs)
0.6949152542372882
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = (np.abs(observed_array - np.mean(observed_array))) ** j
return 1 - (np.sum(a) / np.sum(b))
def nse_rel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the relative Nash-Sutcliffe efficiency (NSE rel).
.. image:: /pictures/NSErel.png
**Range:** -inf < NSE (rel) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_rel(sim, obs)
0.9062004687708474
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs((simulated_array - observed_array) / observed_array)) ** 2
b = (np.abs((observed_array - np.mean(observed_array)) / np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def kge_2009(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""Compute the Kling-Gupta efficiency (2009).
.. image:: /pictures/KGE_2009.png
**Range:** -inf < KGE (2009) < 1, larger is better.
**Notes:** Gupta et al. (2009) created this metric to demonstrate the relative importance of
the three components of the NSE, which are correlation, bias and variability. This was done
with hydrologic modeling as the context. This metric is meant to address issues with the NSE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), Alpha, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, alpha, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2009) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2009(sim, obs)
0.912223072345668
>>> he.kge_2009(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.927910707932087, 1.0058823529411764, 0.9181073779138655)
References
----------
- Gupta, H. V., Kling, H., Yilmaz, K. K., & Martinez, G. F. (2009). Decomposition of the mean
squared error and NSE performance criteria: Implications for improving hydrological modelling.
Journal of Hydrology, 377(1-2), 80-91.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array, ddof=1)
obs_sigma = np.std(observed_array, ddof=1)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
if obs_mean != 0:
beta = sim_mean / obs_mean
else:
beta = np.nan
# Relative variability between simulated and observed values
if obs_sigma != 0:
alpha = sim_sigma / obs_sigma
else:
alpha = np.nan
if not np.isnan(beta) and not np.isnan(alpha):
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (alpha - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Alpha is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, alpha, beta, kge
else:
return kge
def kge_2012(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""
Compute the Kling-Gupta efficiency (2012).
.. image:: /pictures/KGE_2012.png
**Range:** -inf < KGE (2012) < 1, does not indicate bias, larger is better.
**Notes:** The modified version of the KGE (2009). Kling proposed this version to avoid
cross-correlation between bias and variability ratios.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), gamma, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, gamma, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2012) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2012(sim, obs)
0.9122230723456678
>>> he.kge_2012(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.9224843295231272, 1.0058823529411764, 0.9132923608280753)
References
----------
- Kling, H., Fuchs, M., & Paulin, M. (2012). Runoff conditions in the upper Danube basin under
an ensemble of climate change scenarios. Journal of Hydrology, 424, 264-277.
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array)
obs_sigma = np.std(observed_array)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
beta = sim_mean / obs_mean
# CV is the coefficient of variation (standard deviation / mean)
sim_cv = sim_sigma / sim_mean
obs_cv = obs_sigma / obs_mean
# Variability Ratio, or the ratio of simulated CV to observed CV
gam = sim_cv / obs_cv
if obs_mean != 0 and obs_sigma != 0 and sim_mean != 0:
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (gam - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
if sim_mean == 0:
warnings.warn(
'Warning: The simulated data mean is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, gam, beta, kge
else:
return kge
def lm_index(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""
Compute the Legate-McCabe Efficiency Index.
.. image:: /pictures/E1p.png
**Range:** 0 ≤ E1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.lm_index(sim, obs)
0.6949152542372882
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
mean_obs = np.mean(observed_array)
if obs_bar_p is not None:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def d1_p(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""Compute the Legate-McCabe Index of Agreement.
.. image:: /pictures/D1p.png
**Range:** 0 ≤ d1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1_p(sim, obs)
0.8434782608695652
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
if obs_bar_p is not None:
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - obs_bar_p) + np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
mean_obs = np.mean(observed_array)
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - mean_obs) + np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def ve(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Volumetric Efficiency (VE).
.. image:: /pictures/VE.png
**Range:** 0 ≤ VE < 1 smaller is better, does not indicate bias.
**Notes:** Represents the error as a percentage of flow.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Volumetric Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ve(sim, obs)
0.8947368421052632
References
----------
- Criss, R.E., Winston, W.E., 2008. Do Nash values have value? Discussion and alternate
proposals. Hydrological Processes 22(14) 2723.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(observed_array)
return 1 - (a / b)
def sa(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Angle (SA).
.. image:: /pictures/SA.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral angle metric measures the angle between the two vectors in hyperspace.
It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Angle value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sa(sim, obs)
0.10816831366492945
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(simulated_array, observed_array)
b = np.linalg.norm(simulated_array) * np.linalg.norm(observed_array)
return np.arccos(a / b)
def sc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Correlation (SC).
.. image:: /pictures/SC.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral correlation metric measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Correlation value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sc(sim, obs)
0.27991341383646606
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(observed_array - np.mean(observed_array), simulated_array - np.mean(simulated_array))
b = np.linalg.norm(observed_array - np.mean(observed_array))
c = np.linalg.norm(simulated_array - np.mean(simulated_array))
e = b * c
return np.arccos(a / e)
def sid(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Information Divergence (SID).
.. image:: /pictures/SID.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral information divergence measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral information divergence value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sid(sim, obs)
0.03517616895318012
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
first = (observed_array / np.mean(observed_array)) - (
simulated_array / np.mean(simulated_array))
second1 = np.log10(observed_array) - np.log10(np.mean(observed_array))
second2 = np.log10(simulated_array) - np.log10(np.mean(simulated_array))
return np.dot(first, second1 - second2)
def sga(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Gradient Angle (SGA).
.. image:: /pictures/SGA.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral gradient angle measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
SG is the gradient of the simulated or observed time series.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Gradient Angle.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sga(sim, obs)
0.26764286472739834
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sgx = observed_array[1:] - observed_array[:observed_array.size - 1]
sgy = simulated_array[1:] - simulated_array[:simulated_array.size - 1]
a = np.dot(sgx, sgy)
b = np.linalg.norm(sgx) * np.linalg.norm(sgy)
return np.arccos(a / b)
####################################################################################################
# H Metrics: Methods from Tornqvist L, Vartia P, and Vartia YO. (1985) #
####################################################################################################
def h1_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the H1 mean error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mhe(sim, obs)
0.002106551840594386
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(h)
def h1_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H1 absolute error.
.. image:: /pictures/H1.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The H1 absolute error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mahe(sim, obs)
0.11639226612630865
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(np.abs(h))
def h1_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H1 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean squared H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_rmshe(sim, obs)
0.12865571253672756
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.sqrt(np.mean(h ** 2))
def h2_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean error.
.. image:: /pictures/H2.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mhe(sim, obs)
-0.015319829424307036
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(h)
def h2_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean absolute error.
.. image:: /pictures/H2.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mahe(sim, obs)
0.11997591408039167
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(np.abs(h))
def h2_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_rmshe(sim, obs)
0.1373586680669673
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.sqrt(np.mean(h ** 2))
def h3_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 mean error.
.. image:: /pictures/H3.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mhe(sim, obs)
-0.006322019630356533
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(h)
def h3_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H3 mean absolute error.
.. image:: /pictures/H3.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mahe(sim, obs)
0.11743831388794855
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(np.abs(h))
def h3_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 root mean square error.
.. image:: /pictures/H3.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.sqrt(np.mean(h ** 2))
def h4_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mhe(sim, obs)
-0.0064637371129817
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(h)
def h4_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H4 mean absolute error.
.. image:: /pictures/H4.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mahe(sim, obs)
0.11781032209144082
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(np.abs(h))
def h4_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_rmshe(sim, obs)
0.13200901963465006
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.sqrt(np.mean(h ** 2))
def h5_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean error.
.. image:: /pictures/H5.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mhe(sim, obs)
-0.006606638791856322
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(h)
def h5_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean absolute error.
.. image:: /pictures/H5.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mahe(sim, obs)
0.11818409010335018
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(np.abs(h))
def h5_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 root mean square error.
.. image:: /pictures/H5.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_rmshe(sim, obs)
0.13254476469410933
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h6_mhe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H6 mean error.
.. image:: /pictures/H6.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mhe(sim, obs)
-0.006322019630356514
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(h)
def h6_mahe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""Compute the H6 mean absolute error.
.. image:: /pictures/H6.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mahe(sim, obs)
0.11743831388794852
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(np.abs(h))
def h6_rmshe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the H6 root mean square error.
.. image:: /pictures/H6.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h7_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean error.
.. image:: /pictures/H7.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mhe(sim, obs)
0.0026331898007430263
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(h)
def h7_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean absolute error.
.. image:: /pictures/H7.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mahe(sim, obs)
0.14549033265788583
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(np.abs(h))
def h7_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 root mean square error.
.. image:: /pictures/H7.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_rmshe(sim, obs)
0.16081964067090945
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
def h8_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H8 mean error.
.. image:: /pictures/H8.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mhe(sim, obs)
0.0018056158633666466
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(h)
def h8_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 mean absolute error.
.. image:: /pictures/H8.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mahe(sim, obs)
0.099764799536836
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(np.abs(h))
def h8_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 root mean square error.
.. image:: /pictures/H8.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_rmshe(sim, obs)
0.11027632503148076
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
# def h9(simulated_array, observed_array, h_type='mhe', k=1):
# h = (simulated_array / observed_array - 1) / \
# np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
# if h_type == 'mhe':
# return h.mean()
# elif h_type == 'ahe':
# return np.abs(h).mean()
# elif h_type == 'rmshe':
# return np.sqrt((h**2).mean())
# else:
# raise RuntimeError("The three types available are 'mhe', 'ahe', and 'rmshe'.")
def h10_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean error.
.. image:: /pictures/H10.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h10_mhe(sim, obs)
-0.0012578676058971154
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(h)
def h10_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean absolute error.
.. image:: /pictures/H10.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_mahe(sim, obs), 6)
0.094636
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(np.abs(h))
def h10_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 root mean square error.
.. image:: /pictures/H10.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_rmshe(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.sqrt(np.mean(h ** 2))
###################################################################################################
# Statistical Error Metrics for Distribution Testing #
###################################################################################################
def g_mean_diff(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the geometric mean difference.
.. image:: /pictures/GMD.png
**Range:**
**Notes:** For the difference of geometric means, the geometric mean is computed for each of
two samples then their difference is taken.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The geometric mean difference value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.g_mean_diff(sim, obs)
0.988855412098022
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.exp(gmean(sim_log) - gmean(obs_log))
def mean_var(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the mean variance.
.. image:: /pictures/MV.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean variance.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.mean_var(sim, obs), 6)
0.010641
References
----------
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.var(np.log1p(observed_array) - np.log1p(simulated_array))
####################################################################################################
# HELPER FUNCTIONS AND API INFORMATION #
####################################################################################################
metric_names = [
'Mean Error', 'Mean Absolute Error', 'Mean Squared Error', 'Mean Log Error',
'Mean Absolute Log Error', 'Mean Squared Log Error', 'Median Error', 'Median Absolute Error',
'Median Squared Error', 'Eclidean Distance', 'Normalized Eclidean Distance',
'Root Mean Square Error', 'Root Mean Squared Log Error',
'Normalized Root Mean Square Error - Range', 'Normalized Root Mean Square Error - Mean',
'Normalized Root Mean Square Error - IQR', 'Inertial Root Mean Square Error',
'Mean Absolute Scaled Error', 'Coefficient of Determination', 'Pearson Correlation Coefficient',
'Spearman Rank Correlation Coefficient', 'Anomaly Correlation Coefficient',
'Mean Absolute Percentage Error', 'Mean Absolute Percentage Deviation',
'Mean Arctangent Absolute Percentage Error', 'Symmetric Mean Absolute Percentage Error (1)',
'Symmetric Mean Absolute Percentage Error (2)', 'Index of Agreement (d)',
'Index of Agreement (d1)', 'Modified Index of Agreement', 'Relative Index of Agreement',
'Index of Agreement Refined (dr)', "Watterson's M", 'Mielke-Berry R',
'Nash-Sutcliffe Efficiency', 'Modified Nash-Sutcliffe Efficiency',
'Relative Nash-Sutcliffe Efficiency', 'Kling-Gupta Efficiency (2009)',
'Kling-Gupta Efficiency (2012)', 'Legate-McCabe Efficiency Index',
'Legate-McCabe Index of Agreement', 'Volumetric Efficiency', 'Spectral Angle',
'Spectral Correlation', 'Spectral Information Divergence', 'Spectral Gradient Angle',
'Mean H1 Error', 'Mean Absolute H1 Error', 'Root Mean Square H1 Error', 'Mean H2 Error',
'Mean Absolute H2 Error', 'Root Mean Square H2 Error', 'Mean H3 Error',
'Mean Absolute H3 Error', 'Root Mean Square H3 Error', 'Mean H4 Error',
'Mean Absolute H4 Error', 'Root Mean Square H4 Error', 'Mean H5 Error',
'Mean Absolute H5 Error', 'Root Mean Square H5 Error', 'Mean H6 Error',
'Mean Absolute H6 Error', 'Root Mean Square H6 Error', 'Mean H7 Error',
'Mean Absolute H7 Error', 'Root Mean Square H7 Error', 'Mean H8 Error',
'Mean Absolute H8 Error', 'Root Mean Square H8 Error', 'Mean H10 Error',
'Mean Absolute H10 Error', 'Root Mean Square H10 Error', 'Geometric Mean Difference',
'Mean Variance'
]
metric_abbr = [
'ME', 'MAE', 'MSE', 'MLE', 'MALE', 'MSLE', 'MdE', 'MdAE', 'MdSE', 'ED', 'NED', 'RMSE', 'RMSLE',
'NRMSE (Range)', 'NRMSE (Mean)', 'NRMSE (IQR)', 'IRMSE', 'MASE', 'r2', 'R (Pearson)',
'R (Spearman)', 'ACC', 'MAPE', 'MAPD', 'MAAPE', 'SMAPE1', 'SMAPE2', 'd', 'd1', 'd (Mod.)',
'd (Rel.)', 'dr', 'M', '(MB) R', 'NSE', 'NSE (Mod.)', 'NSE (Rel.)', 'KGE (2009)', 'KGE (2012)',
"E1'", "D1'", 'VE', 'SA', 'SC', 'SID', 'SGA', 'H1 (MHE)', 'H1 (MAHE)', 'H1 (RMSHE)', 'H2 (MHE)',
'H2 (MAHE)', 'H2 (RMSHE)', 'H3 (MHE)', 'H3 (MAHE)', 'H3 (RMSHE)', 'H4 (MHE)', 'H4 (MAHE)',
'H4 (RMSHE)', 'H5 (MHE)', 'H5 (MAHE)', 'H5 (RMSHE)', 'H6 (MHE)', 'H6 (MAHE)', 'H6 (RMSHE)',
'H7 (MHE)', 'H7 (MAHE)', 'H7 (RMSHE)', 'H8 (MHE)', 'H8 (MAHE)', 'H8 (RMSHE)', 'H10 (MHE)',
'H10 (MAHE)', 'H10 (RMSHE)', 'GMD', 'MV'
]
function_list = [
me, mae, mse, mle, male, msle, mde, mdae, mdse, ed, ned, rmse, rmsle, nrmse_range, nrmse_mean,
nrmse_iqr, irmse, mase, r_squared, pearson_r, spearman_r, acc, mape, mapd, maape, smape1,
smape2, d, d1, dmod, drel, dr, watt_m, mb_r, nse, nse_mod, nse_rel, kge_2009, kge_2012,
lm_index, d1_p, ve, sa, sc, sid, sga, h1_mhe, h1_mahe, h1_rmshe, h2_mhe, h2_mahe, h2_rmshe,
h3_mhe, h3_mahe, h3_rmshe, h4_mhe, h4_mahe, h4_rmshe, h5_mhe, h5_mahe, h5_rmshe, h6_mhe,
h6_mahe, h6_rmshe, h7_mhe, h7_mahe, h7_rmshe, h8_mhe, h8_mahe, h8_rmshe, h10_mhe, h10_mahe,
h10_rmshe, g_mean_diff, mean_var,
]
# Assign some properties to each function for ease of use for users
for i in range(len(function_list)):
function_list[i].name = metric_names[i]
function_list[i].abbr = metric_abbr[i]
def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Removes the nan, negative, and inf values in two numpy arrays"""
sim_copy = np.copy(simulated_array)
obs_copy = np.copy(observed_array)
# Checking to see if the vectors are the same length
assert sim_copy.ndim == 1, "The simulated array is not one dimensional."
assert obs_copy.ndim == 1, "The observed array is not one dimensional."
if sim_copy.size != obs_copy.size:
raise RuntimeError("The two ndarrays are not the same size.")
# Treat missing data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain nan values
all_treatment_array = np.ones(obs_copy.size, dtype=bool)
if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_nan = np.isnan(sim_copy)
obs_nan = np.isnan(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_nan] = replace_nan
obs_copy[obs_nan] = replace_nan
warnings.warn("Elements(s) {} contained NaN values in the simulated array and "
"elements(s) {} contained NaN values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_nan)[0],
np.where(obs_nan)[0]),
UserWarning)
else:
# Getting the indices of the nan values, combining them, and informing user.
nan_indices_fcst = ~np.isnan(sim_copy)
nan_indices_obs = ~np.isnan(obs_copy)
all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)
warnings.warn("Row(s) {} contained NaN values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_nan_indices)[0]),
UserWarning)
if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_inf = np.isinf(sim_copy)
obs_inf = np.isinf(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_inf] = replace_inf
obs_copy[obs_inf] = replace_inf
warnings.warn("Elements(s) {} contained Inf values in the simulated array and "
"elements(s) {} contained Inf values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_inf)[0],
np.where(obs_inf)[0]),
UserWarning)
else:
inf_indices_fcst = ~(np.isinf(sim_copy))
inf_indices_obs = ~np.isinf(obs_copy)
all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)
warnings.warn(
"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows "
"are zero indexed).".format(np.where(~all_inf_indices)[0]),
UserWarning
)
# Treat zero data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain zero values
if remove_zero:
if (obs_copy == 0).any() or (sim_copy == 0).any():
zero_indices_fcst = ~(sim_copy == 0)
zero_indices_obs = ~(obs_copy == 0)
all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)
warnings.warn(
"Row(s) {} contained zero values and the row(s) have been removed (Rows are "
"zero indexed).".format(np.where(~all_zero_indices)[0]),
UserWarning
)
# Treat negative data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain negative values
# Ignore runtime warnings from comparing
if remove_neg:
with np.errstate(invalid='ignore'):
obs_copy_bool = obs_copy < 0
sim_copy_bool = sim_copy < 0
if obs_copy_bool.any() or sim_copy_bool.any():
neg_indices_fcst = ~sim_copy_bool
neg_indices_obs = ~obs_copy_bool
all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)
warnings.warn("Row(s) {} contained negative values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_neg_indices)[0]),
UserWarning)
obs_copy = obs_copy[all_treatment_array]
sim_copy = sim_copy[all_treatment_array]
return sim_copy, obs_copy
if __name__ == "__main__":
pass
|
BYU-Hydroinformatics/HydroErr | HydroErr/HydroErr.py | drel | python | def drel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = ((simulated_array - observed_array) / observed_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = ((b + c) / np.mean(observed_array)) ** 2
return 1 - (np.sum(a) / np.sum(e)) | Compute the the relative index of agreement (drel).
.. image:: /pictures/drel.png
**Range:** 0 ≤ drel < 1, does not indicate bias, larger is better.
**Notes:** Instead of absolute differences, this metric uses relative differences.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.drel(sim, obs)
0.9740868625579597
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97. | train | https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L2425-L2499 | [
"def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,\n remove_neg=False, remove_zero=False):\n \"\"\"Removes the nan, negative, and inf values in two numpy arrays\"\"\"\n sim_copy = np.copy(simulated_array)\n obs_copy = np.copy(observed_array)\n\n # Checking to see if the vectors are the same length\n assert sim_copy.ndim == 1, \"The simulated array is not one dimensional.\"\n assert obs_copy.ndim == 1, \"The observed array is not one dimensional.\"\n\n if sim_copy.size != obs_copy.size:\n raise RuntimeError(\"The two ndarrays are not the same size.\")\n\n # Treat missing data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain nan values\n all_treatment_array = np.ones(obs_copy.size, dtype=bool)\n\n if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_nan = np.isnan(sim_copy)\n obs_nan = np.isnan(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_nan] = replace_nan\n obs_copy[obs_nan] = replace_nan\n\n warnings.warn(\"Elements(s) {} contained NaN values in the simulated array and \"\n \"elements(s) {} contained NaN values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_nan)[0],\n np.where(obs_nan)[0]),\n UserWarning)\n else:\n # Getting the indices of the nan values, combining them, and informing user.\n nan_indices_fcst = ~np.isnan(sim_copy)\n nan_indices_obs = ~np.isnan(obs_copy)\n all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)\n\n warnings.warn(\"Row(s) {} contained NaN values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_nan_indices)[0]),\n UserWarning)\n\n if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_inf = np.isinf(sim_copy)\n obs_inf = np.isinf(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_inf] = replace_inf\n obs_copy[obs_inf] = replace_inf\n\n warnings.warn(\"Elements(s) {} contained Inf values in the simulated array and \"\n \"elements(s) {} contained Inf values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_inf)[0],\n np.where(obs_inf)[0]),\n UserWarning)\n else:\n inf_indices_fcst = ~(np.isinf(sim_copy))\n inf_indices_obs = ~np.isinf(obs_copy)\n all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)\n\n warnings.warn(\n \"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows \"\n \"are zero indexed).\".format(np.where(~all_inf_indices)[0]),\n UserWarning\n )\n\n # Treat zero data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain zero values\n if remove_zero:\n if (obs_copy == 0).any() or (sim_copy == 0).any():\n zero_indices_fcst = ~(sim_copy == 0)\n zero_indices_obs = ~(obs_copy == 0)\n all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)\n\n warnings.warn(\n \"Row(s) {} contained zero values and the row(s) have been removed (Rows are \"\n \"zero indexed).\".format(np.where(~all_zero_indices)[0]),\n UserWarning\n )\n\n # Treat negative data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain negative values\n\n # Ignore runtime warnings from comparing\n if remove_neg:\n with np.errstate(invalid='ignore'):\n obs_copy_bool = obs_copy < 0\n sim_copy_bool = sim_copy < 0\n\n if obs_copy_bool.any() or sim_copy_bool.any():\n neg_indices_fcst = ~sim_copy_bool\n neg_indices_obs = ~obs_copy_bool\n all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)\n\n warnings.warn(\"Row(s) {} contained negative values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_neg_indices)[0]),\n UserWarning)\n\n obs_copy = obs_copy[all_treatment_array]\n sim_copy = sim_copy[all_treatment_array]\n\n return sim_copy, obs_copy\n"
] | # -*- coding: utf-8 -*-
"""
HydroErr contains a library of goodness of fit metrics that measure hydrologic skill.
Each metric is contained in function, and every function has the parameters to treat missing values as
well as remove zero and negative values from the timeseries data.
Each function contains two properties, name and abbr. These can be used in the Hydrostats package when creating tables
and adding metrics to the plots. Link to the hydrostats package: https://github.com/BYU-Hydroinformatics/Hydrostats.
An example of this functionality is shown below.
>>> import HydroErr as he
>>>
>>> he.acc.name
'Anomaly Correlation Coefficient'
>>> he.acc.abbr
'ACC'
"""
from __future__ import division
import numpy as np
from scipy.stats import gmean, rankdata
import warnings
__all__ = ['me', 'mae', 'mse', 'mle', 'male', 'msle', 'mde', 'mdae', 'mdse', 'ed', 'ned', 'rmse',
'rmsle', 'nrmse_range', 'nrmse_mean', 'nrmse_iqr', 'irmse', 'mase', 'r_squared',
'pearson_r', 'spearman_r', 'acc', 'mape', 'mapd', 'maape', 'smape1', 'smape2', 'd', 'd1',
'dmod', 'drel', 'dr', 'watt_m', 'mb_r', 'nse', 'nse_mod', 'nse_rel', 'kge_2009',
'kge_2012', 'lm_index', 'd1_p', 've', 'sa', 'sc', 'sid', 'sga', 'h1_mhe', 'h1_mahe',
'h1_rmshe', 'h2_mhe', 'h2_mahe', 'h2_rmshe', 'h3_mhe', 'h3_mahe', 'h3_rmshe', 'h4_mhe',
'h4_mahe', 'h4_rmshe', 'h5_mhe', 'h5_mahe', 'h5_rmshe', 'h6_mhe', 'h6_mahe', 'h6_rmshe',
'h7_mhe', 'h7_mahe', 'h7_rmshe', 'h8_mhe', 'h8_mahe', 'h8_rmshe', 'h10_mhe', 'h10_mahe',
'h10_rmshe', 'g_mean_diff', 'mean_var']
####################################################################################################
# General and Hydrological Error Metrics #
####################################################################################################
def me(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean error of the simulated and observed data.
.. image:: /pictures/ME.png
**Range:** -inf < MAE < inf, data units, closer to zero is better, indicates bias.
**Notes:** The mean error (ME) measures the difference between the simulated data and the
observed data. For the mean error, a smaller number indicates a better fit to the original
data. Note that if the error is in the form of random noise, the mean error will be very small,
which can skew the accuracy of this metric. ME is cumulative and will be small even if there
are large positive and negative errors that balance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean error value.
Examples
--------
Note that in this example the random noise cancels, leaving a very small ME.
>>> import HydroErr as he
>>> import numpy as np
>>> # Seed for reproducibility
>>> np.random.seed(54839)
>>> x = np.arange(100) / 20
>>> sim = np.sin(x) + 2
>>> obs = sim * (((np.random.rand(100) - 0.5) / 10) + 1)
>>> he.me(sim, obs)
-0.006832220968967168
References
----------
- Fisher, R.A., 1920. A Mathematical Examination of the Methods of Determining the Accuracy of
an Observation by the Mean Error, and by the Mean Square Error. Monthly Notices of the Royal
Astronomical Society 80 758 - 770.
"""
# Treating missing values
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero)
return np.mean(simulated_array - observed_array)
def mae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute error of the simulated and observed data.
.. image:: /pictures/MAE.png
**Range:** 0 ≤ MAE < inf, data units, smaller is better.
**Notes:** The ME measures the absolute difference between the simulated data and the observed
data. For the mean abolute error, a smaller number indicates a better fit to the original data.
Also note that random errors do not cancel. Also referred to as an L1-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute error value.
References
----------
- Willmott, Cort J., and Kenji Matsuura. “Advantages of the Mean Absolute Error (MAE) over the
Root Mean Square Error (RMSE) in Assessing Average Model Performance.” Climate Research 30,
no. 1 (2005): 79–82.
- Willmott, Cort J., and Kenji Matsuura. “On the Use of Dimensioned Measures of Error to
Evaluate the Performance of Spatial Interpolators.” International Journal of Geographical
Information Science 20, no. 1 (2006): 89–102.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mae(sim, obs)
0.5666666666666665
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean(np.absolute(simulated_array - observed_array))
def mse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared error of the simulated and observed data.
.. image:: /pictures/MSE.png
**Range:** 0 ≤ MSE < inf, data units squared, smaller is better.
**Notes:** Random errors do not cancel, highlights larger errors, also referred to as a
squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mse(sim, obs)
0.4333333333333333
References
----------
- Wang, Zhou, and Alan C. Bovik. “Mean Squared Error: Love It or Leave It? A New Look at Signal
Fidelity Measures.” IEEE Signal Processing Magazine 26, no. 1 (2009): 98–117.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean((simulated_array - observed_array) ** 2)
def mle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean log error of the simulated and observed data.
.. image:: /pictures/MLE.png
**Range:** -inf < MLE < inf, data units, closer to zero is better.
**Notes** Same as the mean erro (ME) only use log ratios as the error term. Limits the impact of outliers, more
evenly weights high and low data values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mle(sim, obs)
0.002961767058151136
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(sim_log - obs_log)
def male(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean absolute log error of the simulated and observed data.
.. image:: /pictures/MALE.png
**Range:** 0 ≤ MALE < inf, data units squared, smaller is better.
**Notes** Same as MAE only use log ratios as the error term. Limits the impact of outliers,
more evenly weights high and low flows.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.male(sim, obs), 6)
0.090417
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(np.abs(sim_log - obs_log))
def msle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared log error of the simulated and observed data.
.. image:: /pictures/MSLE.png
**Range:** 0 ≤ MSLE < inf, data units squared, smaller is better.
**Notes** Same as the mean squared error (MSE) only use log ratios as the error term. Limits
the impact of outliers, more evenly weights high and low values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.msle(sim, obs), 6)
0.010426
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean((sim_log - obs_log) ** 2)
def mde(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median error (MdE) between the simulated and observed data.
.. image:: /pictures/MdE.png
**Range** -inf < MdE < inf, closer to zero is better.
**Notes** This metric indicates bias. It is similar to the mean error (ME), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mde(sim, obs)
-0.10000000000000009
Returns
-------
float
The median error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(simulated_array - observed_array)
def mdae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median absolute error (MdAE) between the simulated and observed data.
.. image:: /pictures/MdAE.png
**Range** 0 ≤ MdAE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean absolute error (MAE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdae(sim, obs)
0.75
Returns
-------
float
The median absolute error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(np.abs(simulated_array - observed_array))
def mdse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median squared error (MdSE) between the simulated and observed data.
.. image:: /pictures/MdSE.png
**Range** 0 ≤ MdSE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean squared error (MSE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdse(sim, obs)
0.625
Returns
-------
float
The median squared error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median((simulated_array - observed_array) ** 2)
def ed(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Euclidean distance between predicted and observed values in vector space.
.. image:: /pictures/ED.png
**Range** 0 ≤ ED < inf, smaller is better.
**Notes** Also sometimes referred to as the L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ed(sim, obs)
1.63707055437449
Returns
-------
float
The euclidean distance error value.
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.linalg.norm(observed_array - simulated_array)
def ned(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the normalized Euclidian distance between the simulated and observed data in vector
space.
.. image:: /pictures/NED.png
**Range** 0 ≤ NED < inf, smaller is better.
**Notes** Also sometimes referred to as the squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The normalized euclidean distance value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ned(sim, obs)
0.2872053604165771
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array / np.mean(observed_array)
b = simulated_array / np.mean(simulated_array)
return np.linalg.norm(a - b)
def rmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square error between the simulated and observed data.
.. image:: /pictures/RMSE.png
**Range** 0 ≤ RMSE < inf, smaller is better.
**Notes:** The standard deviation of the residuals. A lower spread indicates that the points
are better concentrated around the line of best fit (linear). Random errors do not cancel.
This metric will highlights larger errors.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.rmse(sim, obs)
0.668331255192114
References
----------
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.sqrt(np.mean((simulated_array - observed_array) ** 2))
def rmsle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square log error between the simulated and observed data.
.. image:: /pictures/RMSLE.png
**Range:** 0 ≤ RMSLE < inf. Smaller is better, and it does not indicate bias.
**Notes:** Random errors do not cancel while using this metric. This metric limits the
impact of outliers by more evenly weighting high and low values. To calculate the log values,
each value in the observed and simulated array is increased by one unit in order to avoid
run-time errors and nan values (function np.log1p).
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square log error value.
Examples
--------
Notice that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.rmsle(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
"""
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf, remove_neg=remove_neg,
remove_zero=remove_zero)
return np.sqrt(np.mean(np.power(np.log1p(simulated_array) - np.log1p(observed_array), 2)))
def nrmse_range(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the range normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Range.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the range of the observed time series (x).
Normalizing allows comparison between data sets with different scales. The NRMSErange is the
most sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The range normalized root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_range(sim, obs)
0.0891108340256152
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_max = np.max(observed_array)
obs_min = np.min(observed_array)
return rmse_value / (obs_max - obs_min)
def nrmse_mean(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Mean.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the mean of the observed time series (x).
Normalizing allows comparison between data sets with different scales.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_mean(sim, obs)
0.11725109740212526
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_mean = np.mean(observed_array)
return rmse_value / obs_mean
def nrmse_iqr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the IQR normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_IQR.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the interquartile range of the observed time
series (x). Normalizing allows comparison between data sets with different scales.
The NRMSEquartile is the least sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The IQR normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_iqr(sim, obs)
0.2595461185212093
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
q1 = np.percentile(observed_array, 25)
q3 = np.percentile(observed_array, 75)
iqr = q3 - q1
return rmse_value / iqr
def irmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the inertial root mean square error (IRMSE) between the simulated and observed data.
.. image:: /pictures/IRMSE.png
**Range:** 0 ≤ IRMSE < inf, lower is better.
**Notes:** This metric is the RMSE devided by by the standard deviation of the gradient of the
observed timeseries data. This metric is meant to be help understand the ability of the model
to predict changes in observation.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The inertial root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.irmse(sim, obs)
0.14572738134831856
References
----------
- Daga, M., Deo, M.C., 2009. Alternative data-driven methods to estimate wind from waves by
inverse modeling. Natural Hazards 49(2) 293-310.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Getting the gradient of the observed data
obs_len = observed_array.size
obs_grad = observed_array[1:obs_len] - observed_array[0:obs_len - 1]
# Standard deviation of the gradient
obs_grad_std = np.std(obs_grad, ddof=1)
# Divide RMSE by the standard deviation of the gradient of the observed data
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
return rmse_value / obs_grad_std
def mase(simulated_array, observed_array, m=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute scaled error between the simulated and observed data.
.. image:: /pictures/MASE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
m: int
If given, indicates the seasonal period m. If not given, the default is 1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute scaled error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mase(sim, obs)
0.17341040462427745
References
----------
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
start = m
end = simulated_array.size - m
a = np.mean(np.abs(simulated_array - observed_array))
b = np.abs(observed_array[start:observed_array.size] - observed_array[:end])
return a / (np.sum(b) / end)
def pearson_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the pearson correlation coefficient.
.. image:: /pictures/R_pearson.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The pearson r coefficient measures linear correlation. It is sensitive to outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Pearson correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.pearson_r(sim, obs)
0.9610793632835262
References
----------
- Pearson, K. (1895). Note on regression and inheritance in the case of two parents.
Proceedings of the Royal Society of London, 58, 240-242.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
top = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1 = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2 = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
return top / (bot1 * bot2)
def spearman_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the spearman rank correlation coefficient.
.. image:: /pictures/R_spearman.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The spearman r coefficient measures the monotonic relation between simulated and
observed data. Because it uses a nonparametric measure of rank correlation, it is less sensitive
to outliers compared to the Pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spearman rank correlation coefficient.
Examples
----------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.spearman_r(sim, obs)
0.942857142857143
References
----------
- Spearman C (1904). "The proof and measurement of association between two things". American
Journal of Psychology. 15: 72–101. doi:10.2307/1412159
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rank_sim = rankdata(simulated_array)
rank_obs = rankdata(observed_array)
mean_rank_sim = np.mean(rank_sim)
mean_rank_obs = np.mean(rank_obs)
top = np.mean((rank_obs - mean_rank_obs) * (rank_sim - mean_rank_sim))
bot = np.sqrt(
np.mean((rank_obs - mean_rank_obs) ** 2) * np.mean((rank_sim - mean_rank_sim) ** 2))
return top / bot
def r_squared(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Coefficient of Determination (r2).
.. image:: /pictures/r2.png
**Range:** 0 ≤ r2 ≤ 1. 1 indicates perfect correlation, 0 indicates complete randomness.
**Notes:** The Coefficient of Determination measures the linear relation between simulated and
observed data. Because it is the pearson correlation coefficient squared, it is more heavily
affected by outliers than the pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The coefficient of determination (R^2).
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.r_squared(sim, obs)
0.9236735425294681
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array - np.mean(observed_array)
b = simulated_array - np.mean(simulated_array)
return (np.sum(a * b)) ** 2 / (np.sum(a ** 2) * np.sum(b ** 2))
def acc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the anomaly correlation coefficient (ACC).
.. image:: /pictures/ACC.png
**Range:** -1 ≤ ACC ≤ 1. -1 indicates perfect negative correlation of the variation
pattern of the anomalies, 0 indicates complete randomness of the variation patterns of the
anomalies, 1 indicates perfect correlation of the variation pattern of the anomalies.
**Notes:** Common measure in the verification of spatial fields. Measures the correlation
between the variation pattern of the simulated data compared to the observed data.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The anomaly correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.acc(sim, obs)
0.8008994694029383
References
----------
- Langland, Rolf H., and Ryan N. Maue. “Recent Northern Hemisphere Mid-Latitude Medium-Range
Deterministic Forecast Skill.” Tellus A: Dynamic Meteorology and Oceanography 64,
no. 1 (2012): 17531.
- Miyakoda, K., G. D. Hembree, R. F. Strickler, and I. Shulman. “Cumulative Results of Extended
Forecast Experiments I. Model Performance for Winter Cases.” Monthly Weather Review 100, no.
12(1972): 836–55.
- Murphy, Allan H., and Edward S. Epstein. “Skill Scores and Correlation Coefficients in Model
Verification.” Monthly Weather Review 117, no. 3 (1989): 572–82.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - np.mean(simulated_array)
b = observed_array - np.mean(observed_array)
c = np.std(observed_array, ddof=1) * np.std(simulated_array, ddof=1) * simulated_array.size
return np.dot(a, b / c)
def mape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the mean absolute percentage error (MAPE).
.. image:: /pictures/MAPE.png
**Range:** 0% ≤ MAPE ≤ inf. 0% indicates perfect correlation, a larger error indicates a
larger percent error in the data.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
c = 100 / simulated_array.size
return c * np.sum(b)
def mapd(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the mean absolute percentage deviation (MAPD).
.. image:: /pictures/MAPD.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage deviation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mapd(sim, obs)
0.10526315789473682
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(np.abs(observed_array))
return a / b
def maape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the Mean Arctangent Absolute Percentage Error (MAAPE).
.. image:: /pictures/MAAPE.png
**Range:** 0 ≤ MAAPE < π/2, does not indicate bias, smaller is better.
**Notes:** Represents the mean absolute error as a percentage of the observed values. Handles
0s in the observed data. This metric is not as biased as MAPE by under-over predictions.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean arctangent absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
- Kim, S., Kim, H., 2016. A new metric of absolute percentage error for intermittent demand
forecasts. International Journal of Forecasting 32(3) 669-679.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
return np.mean(np.arctan(b))
def smape1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (1) (SMAPE1).
.. image:: /pictures/SMAPE1.png
**Range:** 0 ≤ SMAPE1 < 100%, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (1).
Examples
--------
Note that if we switch the simulated and observed arrays the result is the same
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape1(sim, obs)
5.871915694397428
>>> he.smape1(obs, sim)
5.871915694397428
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 100 / simulated_array.size
b = np.abs(simulated_array - observed_array)
c = np.abs(simulated_array) + np.abs(observed_array)
return a * np.sum(b / c)
def smape2(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (2) (SMAPE2).
.. image:: /pictures/SMAPE2.png
**Range:** 0 ≤ SMAPE1 < 200%, does not indicate bias, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE with only positive metric values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (2).
Examples
--------
Note that switching the simulated and observed arrays yields the same results
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape2(sim, obs)
11.743831388794856
>>> he.smape2(obs, sim)
11.743831388794856
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = (simulated_array + observed_array) / 2
c = 100 / simulated_array.size
return c * np.sum(np.abs(a / b))
def d(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d).
.. image:: /pictures/d.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d(sim, obs)
0.978477353035657
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (observed_array - simulated_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
return 1 - (np.sum(a) / np.sum((b + c) ** 2))
def d1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d1).
.. image:: /pictures/d1.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric. Compared
to the other index of agreement (d) it has a reduced impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (d1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1(sim, obs)
0.8434782608695652
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
obs_mean = np.mean(observed_array)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.abs(simulated_array - obs_mean)
c = np.abs(observed_array - obs_mean)
return 1 - np.sum(a) / np.sum(b + c)
def dr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the refined index of agreement (dr).
.. image:: /pictures/dr.png
**Range:** -1 ≤ dr < 1, does not indicate bias, larger is better.
**Notes:** Reformulation of Willmott’s index of agreement. This metric was created to address
issues in the index of agreement and the Nash-Sutcliffe efficiency metric. Meant to be a
flexible metric for use in climatology.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The refined index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dr(sim, obs)
0.847457627118644
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = 2 * np.sum(np.abs(observed_array - observed_array.mean()))
if a <= b:
return 1 - (a / b)
else:
return (b / a) - 1
def dmod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the modified index of agreement (dmod).
.. image:: /pictures/dmod.png
**Range:** 0 ≤ dmod < 1, does not indicate bias, larger is better.
**Notes:** When j=1, this metric is the same as d1. As j becomes larger, outliers have a larger
impact on the value.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
Optional input indicating the j values desired. A higher j places more emphasis on
outliers. j is 1 by default.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified index of agreement.
Examples
--------
Note that using the default is the same as calculating the d1 metric. Changing the value of j
modification of the metric.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dmod(sim, obs) # Same as d1
0.8434782608695652
>>> he.dmod(sim, obs, j=1.5)
0.9413310986805733
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = (b + c) ** j
return 1 - (np.sum(a) / np.sum(e))
def watt_m(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute Watterson's M (M).
.. image:: /pictures/M.png
**Range:** -1 ≤ M < 1, does not indicate bias, larger is better.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
Watterson's M value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.watt_m(sim, obs)
0.8307913876595929
References
----------
- Watterson, I.G., 1996. Non‐dimensional measures of climate model performance. International
Journal of Climatology 16(4) 379-391.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 2 / np.pi
b = np.mean((simulated_array - observed_array) ** 2) # MSE
c = np.std(observed_array, ddof=1) ** 2 + np.std(simulated_array, ddof=1) ** 2
e = (np.mean(simulated_array) - np.mean(observed_array)) ** 2
f = c + e
return a * np.arcsin(1 - (b / f))
def mb_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute Mielke-Berry R value (MB R).
.. image:: /pictures/MB_R.png
**Range:** 0 ≤ MB R < 1, does not indicate bias, larger is better.
**Notes:** Compares prediction to probability it arose by chance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Mielke-Berry R value.
Notes
-----
If a more optimized version is desired, the `numba package <http://numba.pydata.org/doc.html>`_ can be implemented
for a much more optimized performance when computing this metric. An example is given below.
>>> from numba import njit, prange
>>> @njit(parallel=True, fastmath=True)
>>> def mb_par_fastmath(pred, obs): # uses LLVM compiler
>>> assert pred.size == obs.size
>>> n = pred.size
>>> tot = 0.0
>>> mae = 0.0
>>> for i in range(n):
>>> for j in prange(n):
>>> tot += abs(pred[i] - obs[j])
>>> mae += abs(pred[i] - obs[i])
>>> mae = mae / n
>>> mb = 1 - ((n ** 2) * mae / tot)
>>>
>>> return mb
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mb_r(sim, obs)
0.7726315789473684
References
----------
- Berry, K.J., Mielke, P.W., 1988. A Generalization of Cohen's Kappa Agreement Measure to
Interval Measurement and Multiple Raters. Educational and Psychological Measurement 48(4)
921-933.
- Mielke, P.W., Berry, K.J., 2007. Permutation methods: a distance function approach.
Springer Science & Business Media.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Calculate metric
n = simulated_array.size
tot = 0.0
for i in range(n):
tot = tot + np.sum(np.abs(simulated_array - observed_array[i]))
mae_val = np.sum(np.abs(simulated_array - observed_array)) / n
mb = 1 - ((n ** 2) * mae_val / tot)
return mb
def nse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Nash-Sutcliffe Efficiency.
.. image:: /pictures/NSE.png
**Range:** -inf < NSE < 1, does not indicate bias, larger is better.
**Notes:** The Nash-Sutcliffe efficiency metric compares prediction values to naive predictions
(i.e. average value). One major flaw of this metric is that it punishes a higher variance in
the observed values (denominator). This metric is analogous to the mean absolute error skill
score (MAESS) using the mean flow as a benchmark.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Nash-Sutcliffe Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse(sim, obs)
0.922093023255814
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
- McCuen, R.H., Knight, Z., Cutter, A.G., 2006. Evaluation of the Nash-Sutcliffe Efficiency
Index. Journal of Hydraulic Engineering.
- Nash, J.E., Sutcliffe, J.V., 1970. River flow forecasting through conceptual models part
I — A discussion of principles. Journal of Hydrology 282-290.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** 2
b = (np.abs(observed_array - np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def nse_mod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the modified Nash-Sutcliffe efficiency (NSE mod).
.. image:: /pictures/NSEmod.png
**Range:** -inf < NSE (mod) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
If given, sets the value of j to the input. j is 1 by default. A higher j gives more
emphasis to outliers
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_mod(sim, obs)
0.6949152542372882
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = (np.abs(observed_array - np.mean(observed_array))) ** j
return 1 - (np.sum(a) / np.sum(b))
def nse_rel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the relative Nash-Sutcliffe efficiency (NSE rel).
.. image:: /pictures/NSErel.png
**Range:** -inf < NSE (rel) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_rel(sim, obs)
0.9062004687708474
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs((simulated_array - observed_array) / observed_array)) ** 2
b = (np.abs((observed_array - np.mean(observed_array)) / np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def kge_2009(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""Compute the Kling-Gupta efficiency (2009).
.. image:: /pictures/KGE_2009.png
**Range:** -inf < KGE (2009) < 1, larger is better.
**Notes:** Gupta et al. (2009) created this metric to demonstrate the relative importance of
the three components of the NSE, which are correlation, bias and variability. This was done
with hydrologic modeling as the context. This metric is meant to address issues with the NSE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), Alpha, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, alpha, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2009) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2009(sim, obs)
0.912223072345668
>>> he.kge_2009(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.927910707932087, 1.0058823529411764, 0.9181073779138655)
References
----------
- Gupta, H. V., Kling, H., Yilmaz, K. K., & Martinez, G. F. (2009). Decomposition of the mean
squared error and NSE performance criteria: Implications for improving hydrological modelling.
Journal of Hydrology, 377(1-2), 80-91.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array, ddof=1)
obs_sigma = np.std(observed_array, ddof=1)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
if obs_mean != 0:
beta = sim_mean / obs_mean
else:
beta = np.nan
# Relative variability between simulated and observed values
if obs_sigma != 0:
alpha = sim_sigma / obs_sigma
else:
alpha = np.nan
if not np.isnan(beta) and not np.isnan(alpha):
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (alpha - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Alpha is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, alpha, beta, kge
else:
return kge
def kge_2012(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""
Compute the Kling-Gupta efficiency (2012).
.. image:: /pictures/KGE_2012.png
**Range:** -inf < KGE (2012) < 1, does not indicate bias, larger is better.
**Notes:** The modified version of the KGE (2009). Kling proposed this version to avoid
cross-correlation between bias and variability ratios.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), gamma, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, gamma, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2012) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2012(sim, obs)
0.9122230723456678
>>> he.kge_2012(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.9224843295231272, 1.0058823529411764, 0.9132923608280753)
References
----------
- Kling, H., Fuchs, M., & Paulin, M. (2012). Runoff conditions in the upper Danube basin under
an ensemble of climate change scenarios. Journal of Hydrology, 424, 264-277.
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array)
obs_sigma = np.std(observed_array)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
beta = sim_mean / obs_mean
# CV is the coefficient of variation (standard deviation / mean)
sim_cv = sim_sigma / sim_mean
obs_cv = obs_sigma / obs_mean
# Variability Ratio, or the ratio of simulated CV to observed CV
gam = sim_cv / obs_cv
if obs_mean != 0 and obs_sigma != 0 and sim_mean != 0:
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (gam - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
if sim_mean == 0:
warnings.warn(
'Warning: The simulated data mean is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, gam, beta, kge
else:
return kge
def lm_index(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""
Compute the Legate-McCabe Efficiency Index.
.. image:: /pictures/E1p.png
**Range:** 0 ≤ E1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.lm_index(sim, obs)
0.6949152542372882
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
mean_obs = np.mean(observed_array)
if obs_bar_p is not None:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def d1_p(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""Compute the Legate-McCabe Index of Agreement.
.. image:: /pictures/D1p.png
**Range:** 0 ≤ d1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1_p(sim, obs)
0.8434782608695652
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
if obs_bar_p is not None:
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - obs_bar_p) + np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
mean_obs = np.mean(observed_array)
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - mean_obs) + np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def ve(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Volumetric Efficiency (VE).
.. image:: /pictures/VE.png
**Range:** 0 ≤ VE < 1 smaller is better, does not indicate bias.
**Notes:** Represents the error as a percentage of flow.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Volumetric Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ve(sim, obs)
0.8947368421052632
References
----------
- Criss, R.E., Winston, W.E., 2008. Do Nash values have value? Discussion and alternate
proposals. Hydrological Processes 22(14) 2723.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(observed_array)
return 1 - (a / b)
def sa(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Angle (SA).
.. image:: /pictures/SA.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral angle metric measures the angle between the two vectors in hyperspace.
It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Angle value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sa(sim, obs)
0.10816831366492945
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(simulated_array, observed_array)
b = np.linalg.norm(simulated_array) * np.linalg.norm(observed_array)
return np.arccos(a / b)
def sc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Correlation (SC).
.. image:: /pictures/SC.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral correlation metric measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Correlation value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sc(sim, obs)
0.27991341383646606
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(observed_array - np.mean(observed_array), simulated_array - np.mean(simulated_array))
b = np.linalg.norm(observed_array - np.mean(observed_array))
c = np.linalg.norm(simulated_array - np.mean(simulated_array))
e = b * c
return np.arccos(a / e)
def sid(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Information Divergence (SID).
.. image:: /pictures/SID.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral information divergence measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral information divergence value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sid(sim, obs)
0.03517616895318012
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
first = (observed_array / np.mean(observed_array)) - (
simulated_array / np.mean(simulated_array))
second1 = np.log10(observed_array) - np.log10(np.mean(observed_array))
second2 = np.log10(simulated_array) - np.log10(np.mean(simulated_array))
return np.dot(first, second1 - second2)
def sga(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Gradient Angle (SGA).
.. image:: /pictures/SGA.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral gradient angle measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
SG is the gradient of the simulated or observed time series.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Gradient Angle.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sga(sim, obs)
0.26764286472739834
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sgx = observed_array[1:] - observed_array[:observed_array.size - 1]
sgy = simulated_array[1:] - simulated_array[:simulated_array.size - 1]
a = np.dot(sgx, sgy)
b = np.linalg.norm(sgx) * np.linalg.norm(sgy)
return np.arccos(a / b)
####################################################################################################
# H Metrics: Methods from Tornqvist L, Vartia P, and Vartia YO. (1985) #
####################################################################################################
def h1_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the H1 mean error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mhe(sim, obs)
0.002106551840594386
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(h)
def h1_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H1 absolute error.
.. image:: /pictures/H1.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The H1 absolute error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mahe(sim, obs)
0.11639226612630865
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(np.abs(h))
def h1_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H1 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean squared H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_rmshe(sim, obs)
0.12865571253672756
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.sqrt(np.mean(h ** 2))
def h2_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean error.
.. image:: /pictures/H2.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mhe(sim, obs)
-0.015319829424307036
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(h)
def h2_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean absolute error.
.. image:: /pictures/H2.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mahe(sim, obs)
0.11997591408039167
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(np.abs(h))
def h2_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_rmshe(sim, obs)
0.1373586680669673
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.sqrt(np.mean(h ** 2))
def h3_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 mean error.
.. image:: /pictures/H3.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mhe(sim, obs)
-0.006322019630356533
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(h)
def h3_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H3 mean absolute error.
.. image:: /pictures/H3.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mahe(sim, obs)
0.11743831388794855
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(np.abs(h))
def h3_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 root mean square error.
.. image:: /pictures/H3.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.sqrt(np.mean(h ** 2))
def h4_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mhe(sim, obs)
-0.0064637371129817
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(h)
def h4_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H4 mean absolute error.
.. image:: /pictures/H4.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mahe(sim, obs)
0.11781032209144082
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(np.abs(h))
def h4_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_rmshe(sim, obs)
0.13200901963465006
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.sqrt(np.mean(h ** 2))
def h5_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean error.
.. image:: /pictures/H5.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mhe(sim, obs)
-0.006606638791856322
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(h)
def h5_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean absolute error.
.. image:: /pictures/H5.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mahe(sim, obs)
0.11818409010335018
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(np.abs(h))
def h5_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 root mean square error.
.. image:: /pictures/H5.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_rmshe(sim, obs)
0.13254476469410933
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h6_mhe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H6 mean error.
.. image:: /pictures/H6.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mhe(sim, obs)
-0.006322019630356514
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(h)
def h6_mahe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""Compute the H6 mean absolute error.
.. image:: /pictures/H6.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mahe(sim, obs)
0.11743831388794852
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(np.abs(h))
def h6_rmshe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the H6 root mean square error.
.. image:: /pictures/H6.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h7_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean error.
.. image:: /pictures/H7.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mhe(sim, obs)
0.0026331898007430263
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(h)
def h7_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean absolute error.
.. image:: /pictures/H7.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mahe(sim, obs)
0.14549033265788583
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(np.abs(h))
def h7_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 root mean square error.
.. image:: /pictures/H7.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_rmshe(sim, obs)
0.16081964067090945
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
def h8_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H8 mean error.
.. image:: /pictures/H8.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mhe(sim, obs)
0.0018056158633666466
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(h)
def h8_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 mean absolute error.
.. image:: /pictures/H8.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mahe(sim, obs)
0.099764799536836
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(np.abs(h))
def h8_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 root mean square error.
.. image:: /pictures/H8.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_rmshe(sim, obs)
0.11027632503148076
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
# def h9(simulated_array, observed_array, h_type='mhe', k=1):
# h = (simulated_array / observed_array - 1) / \
# np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
# if h_type == 'mhe':
# return h.mean()
# elif h_type == 'ahe':
# return np.abs(h).mean()
# elif h_type == 'rmshe':
# return np.sqrt((h**2).mean())
# else:
# raise RuntimeError("The three types available are 'mhe', 'ahe', and 'rmshe'.")
def h10_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean error.
.. image:: /pictures/H10.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h10_mhe(sim, obs)
-0.0012578676058971154
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(h)
def h10_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean absolute error.
.. image:: /pictures/H10.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_mahe(sim, obs), 6)
0.094636
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(np.abs(h))
def h10_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 root mean square error.
.. image:: /pictures/H10.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_rmshe(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.sqrt(np.mean(h ** 2))
###################################################################################################
# Statistical Error Metrics for Distribution Testing #
###################################################################################################
def g_mean_diff(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the geometric mean difference.
.. image:: /pictures/GMD.png
**Range:**
**Notes:** For the difference of geometric means, the geometric mean is computed for each of
two samples then their difference is taken.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The geometric mean difference value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.g_mean_diff(sim, obs)
0.988855412098022
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.exp(gmean(sim_log) - gmean(obs_log))
def mean_var(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the mean variance.
.. image:: /pictures/MV.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean variance.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.mean_var(sim, obs), 6)
0.010641
References
----------
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.var(np.log1p(observed_array) - np.log1p(simulated_array))
####################################################################################################
# HELPER FUNCTIONS AND API INFORMATION #
####################################################################################################
metric_names = [
'Mean Error', 'Mean Absolute Error', 'Mean Squared Error', 'Mean Log Error',
'Mean Absolute Log Error', 'Mean Squared Log Error', 'Median Error', 'Median Absolute Error',
'Median Squared Error', 'Eclidean Distance', 'Normalized Eclidean Distance',
'Root Mean Square Error', 'Root Mean Squared Log Error',
'Normalized Root Mean Square Error - Range', 'Normalized Root Mean Square Error - Mean',
'Normalized Root Mean Square Error - IQR', 'Inertial Root Mean Square Error',
'Mean Absolute Scaled Error', 'Coefficient of Determination', 'Pearson Correlation Coefficient',
'Spearman Rank Correlation Coefficient', 'Anomaly Correlation Coefficient',
'Mean Absolute Percentage Error', 'Mean Absolute Percentage Deviation',
'Mean Arctangent Absolute Percentage Error', 'Symmetric Mean Absolute Percentage Error (1)',
'Symmetric Mean Absolute Percentage Error (2)', 'Index of Agreement (d)',
'Index of Agreement (d1)', 'Modified Index of Agreement', 'Relative Index of Agreement',
'Index of Agreement Refined (dr)', "Watterson's M", 'Mielke-Berry R',
'Nash-Sutcliffe Efficiency', 'Modified Nash-Sutcliffe Efficiency',
'Relative Nash-Sutcliffe Efficiency', 'Kling-Gupta Efficiency (2009)',
'Kling-Gupta Efficiency (2012)', 'Legate-McCabe Efficiency Index',
'Legate-McCabe Index of Agreement', 'Volumetric Efficiency', 'Spectral Angle',
'Spectral Correlation', 'Spectral Information Divergence', 'Spectral Gradient Angle',
'Mean H1 Error', 'Mean Absolute H1 Error', 'Root Mean Square H1 Error', 'Mean H2 Error',
'Mean Absolute H2 Error', 'Root Mean Square H2 Error', 'Mean H3 Error',
'Mean Absolute H3 Error', 'Root Mean Square H3 Error', 'Mean H4 Error',
'Mean Absolute H4 Error', 'Root Mean Square H4 Error', 'Mean H5 Error',
'Mean Absolute H5 Error', 'Root Mean Square H5 Error', 'Mean H6 Error',
'Mean Absolute H6 Error', 'Root Mean Square H6 Error', 'Mean H7 Error',
'Mean Absolute H7 Error', 'Root Mean Square H7 Error', 'Mean H8 Error',
'Mean Absolute H8 Error', 'Root Mean Square H8 Error', 'Mean H10 Error',
'Mean Absolute H10 Error', 'Root Mean Square H10 Error', 'Geometric Mean Difference',
'Mean Variance'
]
metric_abbr = [
'ME', 'MAE', 'MSE', 'MLE', 'MALE', 'MSLE', 'MdE', 'MdAE', 'MdSE', 'ED', 'NED', 'RMSE', 'RMSLE',
'NRMSE (Range)', 'NRMSE (Mean)', 'NRMSE (IQR)', 'IRMSE', 'MASE', 'r2', 'R (Pearson)',
'R (Spearman)', 'ACC', 'MAPE', 'MAPD', 'MAAPE', 'SMAPE1', 'SMAPE2', 'd', 'd1', 'd (Mod.)',
'd (Rel.)', 'dr', 'M', '(MB) R', 'NSE', 'NSE (Mod.)', 'NSE (Rel.)', 'KGE (2009)', 'KGE (2012)',
"E1'", "D1'", 'VE', 'SA', 'SC', 'SID', 'SGA', 'H1 (MHE)', 'H1 (MAHE)', 'H1 (RMSHE)', 'H2 (MHE)',
'H2 (MAHE)', 'H2 (RMSHE)', 'H3 (MHE)', 'H3 (MAHE)', 'H3 (RMSHE)', 'H4 (MHE)', 'H4 (MAHE)',
'H4 (RMSHE)', 'H5 (MHE)', 'H5 (MAHE)', 'H5 (RMSHE)', 'H6 (MHE)', 'H6 (MAHE)', 'H6 (RMSHE)',
'H7 (MHE)', 'H7 (MAHE)', 'H7 (RMSHE)', 'H8 (MHE)', 'H8 (MAHE)', 'H8 (RMSHE)', 'H10 (MHE)',
'H10 (MAHE)', 'H10 (RMSHE)', 'GMD', 'MV'
]
function_list = [
me, mae, mse, mle, male, msle, mde, mdae, mdse, ed, ned, rmse, rmsle, nrmse_range, nrmse_mean,
nrmse_iqr, irmse, mase, r_squared, pearson_r, spearman_r, acc, mape, mapd, maape, smape1,
smape2, d, d1, dmod, drel, dr, watt_m, mb_r, nse, nse_mod, nse_rel, kge_2009, kge_2012,
lm_index, d1_p, ve, sa, sc, sid, sga, h1_mhe, h1_mahe, h1_rmshe, h2_mhe, h2_mahe, h2_rmshe,
h3_mhe, h3_mahe, h3_rmshe, h4_mhe, h4_mahe, h4_rmshe, h5_mhe, h5_mahe, h5_rmshe, h6_mhe,
h6_mahe, h6_rmshe, h7_mhe, h7_mahe, h7_rmshe, h8_mhe, h8_mahe, h8_rmshe, h10_mhe, h10_mahe,
h10_rmshe, g_mean_diff, mean_var,
]
# Assign some properties to each function for ease of use for users
for i in range(len(function_list)):
function_list[i].name = metric_names[i]
function_list[i].abbr = metric_abbr[i]
def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Removes the nan, negative, and inf values in two numpy arrays"""
sim_copy = np.copy(simulated_array)
obs_copy = np.copy(observed_array)
# Checking to see if the vectors are the same length
assert sim_copy.ndim == 1, "The simulated array is not one dimensional."
assert obs_copy.ndim == 1, "The observed array is not one dimensional."
if sim_copy.size != obs_copy.size:
raise RuntimeError("The two ndarrays are not the same size.")
# Treat missing data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain nan values
all_treatment_array = np.ones(obs_copy.size, dtype=bool)
if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_nan = np.isnan(sim_copy)
obs_nan = np.isnan(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_nan] = replace_nan
obs_copy[obs_nan] = replace_nan
warnings.warn("Elements(s) {} contained NaN values in the simulated array and "
"elements(s) {} contained NaN values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_nan)[0],
np.where(obs_nan)[0]),
UserWarning)
else:
# Getting the indices of the nan values, combining them, and informing user.
nan_indices_fcst = ~np.isnan(sim_copy)
nan_indices_obs = ~np.isnan(obs_copy)
all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)
warnings.warn("Row(s) {} contained NaN values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_nan_indices)[0]),
UserWarning)
if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_inf = np.isinf(sim_copy)
obs_inf = np.isinf(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_inf] = replace_inf
obs_copy[obs_inf] = replace_inf
warnings.warn("Elements(s) {} contained Inf values in the simulated array and "
"elements(s) {} contained Inf values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_inf)[0],
np.where(obs_inf)[0]),
UserWarning)
else:
inf_indices_fcst = ~(np.isinf(sim_copy))
inf_indices_obs = ~np.isinf(obs_copy)
all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)
warnings.warn(
"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows "
"are zero indexed).".format(np.where(~all_inf_indices)[0]),
UserWarning
)
# Treat zero data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain zero values
if remove_zero:
if (obs_copy == 0).any() or (sim_copy == 0).any():
zero_indices_fcst = ~(sim_copy == 0)
zero_indices_obs = ~(obs_copy == 0)
all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)
warnings.warn(
"Row(s) {} contained zero values and the row(s) have been removed (Rows are "
"zero indexed).".format(np.where(~all_zero_indices)[0]),
UserWarning
)
# Treat negative data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain negative values
# Ignore runtime warnings from comparing
if remove_neg:
with np.errstate(invalid='ignore'):
obs_copy_bool = obs_copy < 0
sim_copy_bool = sim_copy < 0
if obs_copy_bool.any() or sim_copy_bool.any():
neg_indices_fcst = ~sim_copy_bool
neg_indices_obs = ~obs_copy_bool
all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)
warnings.warn("Row(s) {} contained negative values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_neg_indices)[0]),
UserWarning)
obs_copy = obs_copy[all_treatment_array]
sim_copy = sim_copy[all_treatment_array]
return sim_copy, obs_copy
if __name__ == "__main__":
pass
|
BYU-Hydroinformatics/HydroErr | HydroErr/HydroErr.py | watt_m | python | def watt_m(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 2 / np.pi
b = np.mean((simulated_array - observed_array) ** 2) # MSE
c = np.std(observed_array, ddof=1) ** 2 + np.std(simulated_array, ddof=1) ** 2
e = (np.mean(simulated_array) - np.mean(observed_array)) ** 2
f = c + e
return a * np.arcsin(1 - (b / f)) | Compute Watterson's M (M).
.. image:: /pictures/M.png
**Range:** -1 ≤ M < 1, does not indicate bias, larger is better.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
Watterson's M value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.watt_m(sim, obs)
0.8307913876595929
References
----------
- Watterson, I.G., 1996. Non‐dimensional measures of climate model performance. International
Journal of Climatology 16(4) 379-391. | train | https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L2593-L2668 | [
"def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,\n remove_neg=False, remove_zero=False):\n \"\"\"Removes the nan, negative, and inf values in two numpy arrays\"\"\"\n sim_copy = np.copy(simulated_array)\n obs_copy = np.copy(observed_array)\n\n # Checking to see if the vectors are the same length\n assert sim_copy.ndim == 1, \"The simulated array is not one dimensional.\"\n assert obs_copy.ndim == 1, \"The observed array is not one dimensional.\"\n\n if sim_copy.size != obs_copy.size:\n raise RuntimeError(\"The two ndarrays are not the same size.\")\n\n # Treat missing data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain nan values\n all_treatment_array = np.ones(obs_copy.size, dtype=bool)\n\n if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_nan = np.isnan(sim_copy)\n obs_nan = np.isnan(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_nan] = replace_nan\n obs_copy[obs_nan] = replace_nan\n\n warnings.warn(\"Elements(s) {} contained NaN values in the simulated array and \"\n \"elements(s) {} contained NaN values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_nan)[0],\n np.where(obs_nan)[0]),\n UserWarning)\n else:\n # Getting the indices of the nan values, combining them, and informing user.\n nan_indices_fcst = ~np.isnan(sim_copy)\n nan_indices_obs = ~np.isnan(obs_copy)\n all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)\n\n warnings.warn(\"Row(s) {} contained NaN values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_nan_indices)[0]),\n UserWarning)\n\n if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_inf = np.isinf(sim_copy)\n obs_inf = np.isinf(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_inf] = replace_inf\n obs_copy[obs_inf] = replace_inf\n\n warnings.warn(\"Elements(s) {} contained Inf values in the simulated array and \"\n \"elements(s) {} contained Inf values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_inf)[0],\n np.where(obs_inf)[0]),\n UserWarning)\n else:\n inf_indices_fcst = ~(np.isinf(sim_copy))\n inf_indices_obs = ~np.isinf(obs_copy)\n all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)\n\n warnings.warn(\n \"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows \"\n \"are zero indexed).\".format(np.where(~all_inf_indices)[0]),\n UserWarning\n )\n\n # Treat zero data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain zero values\n if remove_zero:\n if (obs_copy == 0).any() or (sim_copy == 0).any():\n zero_indices_fcst = ~(sim_copy == 0)\n zero_indices_obs = ~(obs_copy == 0)\n all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)\n\n warnings.warn(\n \"Row(s) {} contained zero values and the row(s) have been removed (Rows are \"\n \"zero indexed).\".format(np.where(~all_zero_indices)[0]),\n UserWarning\n )\n\n # Treat negative data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain negative values\n\n # Ignore runtime warnings from comparing\n if remove_neg:\n with np.errstate(invalid='ignore'):\n obs_copy_bool = obs_copy < 0\n sim_copy_bool = sim_copy < 0\n\n if obs_copy_bool.any() or sim_copy_bool.any():\n neg_indices_fcst = ~sim_copy_bool\n neg_indices_obs = ~obs_copy_bool\n all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)\n\n warnings.warn(\"Row(s) {} contained negative values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_neg_indices)[0]),\n UserWarning)\n\n obs_copy = obs_copy[all_treatment_array]\n sim_copy = sim_copy[all_treatment_array]\n\n return sim_copy, obs_copy\n"
] | # -*- coding: utf-8 -*-
"""
HydroErr contains a library of goodness of fit metrics that measure hydrologic skill.
Each metric is contained in function, and every function has the parameters to treat missing values as
well as remove zero and negative values from the timeseries data.
Each function contains two properties, name and abbr. These can be used in the Hydrostats package when creating tables
and adding metrics to the plots. Link to the hydrostats package: https://github.com/BYU-Hydroinformatics/Hydrostats.
An example of this functionality is shown below.
>>> import HydroErr as he
>>>
>>> he.acc.name
'Anomaly Correlation Coefficient'
>>> he.acc.abbr
'ACC'
"""
from __future__ import division
import numpy as np
from scipy.stats import gmean, rankdata
import warnings
__all__ = ['me', 'mae', 'mse', 'mle', 'male', 'msle', 'mde', 'mdae', 'mdse', 'ed', 'ned', 'rmse',
'rmsle', 'nrmse_range', 'nrmse_mean', 'nrmse_iqr', 'irmse', 'mase', 'r_squared',
'pearson_r', 'spearman_r', 'acc', 'mape', 'mapd', 'maape', 'smape1', 'smape2', 'd', 'd1',
'dmod', 'drel', 'dr', 'watt_m', 'mb_r', 'nse', 'nse_mod', 'nse_rel', 'kge_2009',
'kge_2012', 'lm_index', 'd1_p', 've', 'sa', 'sc', 'sid', 'sga', 'h1_mhe', 'h1_mahe',
'h1_rmshe', 'h2_mhe', 'h2_mahe', 'h2_rmshe', 'h3_mhe', 'h3_mahe', 'h3_rmshe', 'h4_mhe',
'h4_mahe', 'h4_rmshe', 'h5_mhe', 'h5_mahe', 'h5_rmshe', 'h6_mhe', 'h6_mahe', 'h6_rmshe',
'h7_mhe', 'h7_mahe', 'h7_rmshe', 'h8_mhe', 'h8_mahe', 'h8_rmshe', 'h10_mhe', 'h10_mahe',
'h10_rmshe', 'g_mean_diff', 'mean_var']
####################################################################################################
# General and Hydrological Error Metrics #
####################################################################################################
def me(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean error of the simulated and observed data.
.. image:: /pictures/ME.png
**Range:** -inf < MAE < inf, data units, closer to zero is better, indicates bias.
**Notes:** The mean error (ME) measures the difference between the simulated data and the
observed data. For the mean error, a smaller number indicates a better fit to the original
data. Note that if the error is in the form of random noise, the mean error will be very small,
which can skew the accuracy of this metric. ME is cumulative and will be small even if there
are large positive and negative errors that balance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean error value.
Examples
--------
Note that in this example the random noise cancels, leaving a very small ME.
>>> import HydroErr as he
>>> import numpy as np
>>> # Seed for reproducibility
>>> np.random.seed(54839)
>>> x = np.arange(100) / 20
>>> sim = np.sin(x) + 2
>>> obs = sim * (((np.random.rand(100) - 0.5) / 10) + 1)
>>> he.me(sim, obs)
-0.006832220968967168
References
----------
- Fisher, R.A., 1920. A Mathematical Examination of the Methods of Determining the Accuracy of
an Observation by the Mean Error, and by the Mean Square Error. Monthly Notices of the Royal
Astronomical Society 80 758 - 770.
"""
# Treating missing values
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero)
return np.mean(simulated_array - observed_array)
def mae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute error of the simulated and observed data.
.. image:: /pictures/MAE.png
**Range:** 0 ≤ MAE < inf, data units, smaller is better.
**Notes:** The ME measures the absolute difference between the simulated data and the observed
data. For the mean abolute error, a smaller number indicates a better fit to the original data.
Also note that random errors do not cancel. Also referred to as an L1-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute error value.
References
----------
- Willmott, Cort J., and Kenji Matsuura. “Advantages of the Mean Absolute Error (MAE) over the
Root Mean Square Error (RMSE) in Assessing Average Model Performance.” Climate Research 30,
no. 1 (2005): 79–82.
- Willmott, Cort J., and Kenji Matsuura. “On the Use of Dimensioned Measures of Error to
Evaluate the Performance of Spatial Interpolators.” International Journal of Geographical
Information Science 20, no. 1 (2006): 89–102.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mae(sim, obs)
0.5666666666666665
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean(np.absolute(simulated_array - observed_array))
def mse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared error of the simulated and observed data.
.. image:: /pictures/MSE.png
**Range:** 0 ≤ MSE < inf, data units squared, smaller is better.
**Notes:** Random errors do not cancel, highlights larger errors, also referred to as a
squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mse(sim, obs)
0.4333333333333333
References
----------
- Wang, Zhou, and Alan C. Bovik. “Mean Squared Error: Love It or Leave It? A New Look at Signal
Fidelity Measures.” IEEE Signal Processing Magazine 26, no. 1 (2009): 98–117.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean((simulated_array - observed_array) ** 2)
def mle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean log error of the simulated and observed data.
.. image:: /pictures/MLE.png
**Range:** -inf < MLE < inf, data units, closer to zero is better.
**Notes** Same as the mean erro (ME) only use log ratios as the error term. Limits the impact of outliers, more
evenly weights high and low data values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mle(sim, obs)
0.002961767058151136
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(sim_log - obs_log)
def male(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean absolute log error of the simulated and observed data.
.. image:: /pictures/MALE.png
**Range:** 0 ≤ MALE < inf, data units squared, smaller is better.
**Notes** Same as MAE only use log ratios as the error term. Limits the impact of outliers,
more evenly weights high and low flows.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.male(sim, obs), 6)
0.090417
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(np.abs(sim_log - obs_log))
def msle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared log error of the simulated and observed data.
.. image:: /pictures/MSLE.png
**Range:** 0 ≤ MSLE < inf, data units squared, smaller is better.
**Notes** Same as the mean squared error (MSE) only use log ratios as the error term. Limits
the impact of outliers, more evenly weights high and low values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.msle(sim, obs), 6)
0.010426
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean((sim_log - obs_log) ** 2)
def mde(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median error (MdE) between the simulated and observed data.
.. image:: /pictures/MdE.png
**Range** -inf < MdE < inf, closer to zero is better.
**Notes** This metric indicates bias. It is similar to the mean error (ME), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mde(sim, obs)
-0.10000000000000009
Returns
-------
float
The median error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(simulated_array - observed_array)
def mdae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median absolute error (MdAE) between the simulated and observed data.
.. image:: /pictures/MdAE.png
**Range** 0 ≤ MdAE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean absolute error (MAE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdae(sim, obs)
0.75
Returns
-------
float
The median absolute error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(np.abs(simulated_array - observed_array))
def mdse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median squared error (MdSE) between the simulated and observed data.
.. image:: /pictures/MdSE.png
**Range** 0 ≤ MdSE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean squared error (MSE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdse(sim, obs)
0.625
Returns
-------
float
The median squared error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median((simulated_array - observed_array) ** 2)
def ed(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Euclidean distance between predicted and observed values in vector space.
.. image:: /pictures/ED.png
**Range** 0 ≤ ED < inf, smaller is better.
**Notes** Also sometimes referred to as the L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ed(sim, obs)
1.63707055437449
Returns
-------
float
The euclidean distance error value.
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.linalg.norm(observed_array - simulated_array)
def ned(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the normalized Euclidian distance between the simulated and observed data in vector
space.
.. image:: /pictures/NED.png
**Range** 0 ≤ NED < inf, smaller is better.
**Notes** Also sometimes referred to as the squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The normalized euclidean distance value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ned(sim, obs)
0.2872053604165771
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array / np.mean(observed_array)
b = simulated_array / np.mean(simulated_array)
return np.linalg.norm(a - b)
def rmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square error between the simulated and observed data.
.. image:: /pictures/RMSE.png
**Range** 0 ≤ RMSE < inf, smaller is better.
**Notes:** The standard deviation of the residuals. A lower spread indicates that the points
are better concentrated around the line of best fit (linear). Random errors do not cancel.
This metric will highlights larger errors.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.rmse(sim, obs)
0.668331255192114
References
----------
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.sqrt(np.mean((simulated_array - observed_array) ** 2))
def rmsle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square log error between the simulated and observed data.
.. image:: /pictures/RMSLE.png
**Range:** 0 ≤ RMSLE < inf. Smaller is better, and it does not indicate bias.
**Notes:** Random errors do not cancel while using this metric. This metric limits the
impact of outliers by more evenly weighting high and low values. To calculate the log values,
each value in the observed and simulated array is increased by one unit in order to avoid
run-time errors and nan values (function np.log1p).
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square log error value.
Examples
--------
Notice that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.rmsle(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
"""
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf, remove_neg=remove_neg,
remove_zero=remove_zero)
return np.sqrt(np.mean(np.power(np.log1p(simulated_array) - np.log1p(observed_array), 2)))
def nrmse_range(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the range normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Range.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the range of the observed time series (x).
Normalizing allows comparison between data sets with different scales. The NRMSErange is the
most sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The range normalized root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_range(sim, obs)
0.0891108340256152
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_max = np.max(observed_array)
obs_min = np.min(observed_array)
return rmse_value / (obs_max - obs_min)
def nrmse_mean(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Mean.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the mean of the observed time series (x).
Normalizing allows comparison between data sets with different scales.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_mean(sim, obs)
0.11725109740212526
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_mean = np.mean(observed_array)
return rmse_value / obs_mean
def nrmse_iqr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the IQR normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_IQR.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the interquartile range of the observed time
series (x). Normalizing allows comparison between data sets with different scales.
The NRMSEquartile is the least sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The IQR normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_iqr(sim, obs)
0.2595461185212093
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
q1 = np.percentile(observed_array, 25)
q3 = np.percentile(observed_array, 75)
iqr = q3 - q1
return rmse_value / iqr
def irmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the inertial root mean square error (IRMSE) between the simulated and observed data.
.. image:: /pictures/IRMSE.png
**Range:** 0 ≤ IRMSE < inf, lower is better.
**Notes:** This metric is the RMSE devided by by the standard deviation of the gradient of the
observed timeseries data. This metric is meant to be help understand the ability of the model
to predict changes in observation.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The inertial root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.irmse(sim, obs)
0.14572738134831856
References
----------
- Daga, M., Deo, M.C., 2009. Alternative data-driven methods to estimate wind from waves by
inverse modeling. Natural Hazards 49(2) 293-310.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Getting the gradient of the observed data
obs_len = observed_array.size
obs_grad = observed_array[1:obs_len] - observed_array[0:obs_len - 1]
# Standard deviation of the gradient
obs_grad_std = np.std(obs_grad, ddof=1)
# Divide RMSE by the standard deviation of the gradient of the observed data
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
return rmse_value / obs_grad_std
def mase(simulated_array, observed_array, m=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute scaled error between the simulated and observed data.
.. image:: /pictures/MASE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
m: int
If given, indicates the seasonal period m. If not given, the default is 1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute scaled error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mase(sim, obs)
0.17341040462427745
References
----------
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
start = m
end = simulated_array.size - m
a = np.mean(np.abs(simulated_array - observed_array))
b = np.abs(observed_array[start:observed_array.size] - observed_array[:end])
return a / (np.sum(b) / end)
def pearson_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the pearson correlation coefficient.
.. image:: /pictures/R_pearson.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The pearson r coefficient measures linear correlation. It is sensitive to outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Pearson correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.pearson_r(sim, obs)
0.9610793632835262
References
----------
- Pearson, K. (1895). Note on regression and inheritance in the case of two parents.
Proceedings of the Royal Society of London, 58, 240-242.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
top = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1 = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2 = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
return top / (bot1 * bot2)
def spearman_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the spearman rank correlation coefficient.
.. image:: /pictures/R_spearman.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The spearman r coefficient measures the monotonic relation between simulated and
observed data. Because it uses a nonparametric measure of rank correlation, it is less sensitive
to outliers compared to the Pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spearman rank correlation coefficient.
Examples
----------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.spearman_r(sim, obs)
0.942857142857143
References
----------
- Spearman C (1904). "The proof and measurement of association between two things". American
Journal of Psychology. 15: 72–101. doi:10.2307/1412159
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rank_sim = rankdata(simulated_array)
rank_obs = rankdata(observed_array)
mean_rank_sim = np.mean(rank_sim)
mean_rank_obs = np.mean(rank_obs)
top = np.mean((rank_obs - mean_rank_obs) * (rank_sim - mean_rank_sim))
bot = np.sqrt(
np.mean((rank_obs - mean_rank_obs) ** 2) * np.mean((rank_sim - mean_rank_sim) ** 2))
return top / bot
def r_squared(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Coefficient of Determination (r2).
.. image:: /pictures/r2.png
**Range:** 0 ≤ r2 ≤ 1. 1 indicates perfect correlation, 0 indicates complete randomness.
**Notes:** The Coefficient of Determination measures the linear relation between simulated and
observed data. Because it is the pearson correlation coefficient squared, it is more heavily
affected by outliers than the pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The coefficient of determination (R^2).
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.r_squared(sim, obs)
0.9236735425294681
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array - np.mean(observed_array)
b = simulated_array - np.mean(simulated_array)
return (np.sum(a * b)) ** 2 / (np.sum(a ** 2) * np.sum(b ** 2))
def acc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the anomaly correlation coefficient (ACC).
.. image:: /pictures/ACC.png
**Range:** -1 ≤ ACC ≤ 1. -1 indicates perfect negative correlation of the variation
pattern of the anomalies, 0 indicates complete randomness of the variation patterns of the
anomalies, 1 indicates perfect correlation of the variation pattern of the anomalies.
**Notes:** Common measure in the verification of spatial fields. Measures the correlation
between the variation pattern of the simulated data compared to the observed data.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The anomaly correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.acc(sim, obs)
0.8008994694029383
References
----------
- Langland, Rolf H., and Ryan N. Maue. “Recent Northern Hemisphere Mid-Latitude Medium-Range
Deterministic Forecast Skill.” Tellus A: Dynamic Meteorology and Oceanography 64,
no. 1 (2012): 17531.
- Miyakoda, K., G. D. Hembree, R. F. Strickler, and I. Shulman. “Cumulative Results of Extended
Forecast Experiments I. Model Performance for Winter Cases.” Monthly Weather Review 100, no.
12(1972): 836–55.
- Murphy, Allan H., and Edward S. Epstein. “Skill Scores and Correlation Coefficients in Model
Verification.” Monthly Weather Review 117, no. 3 (1989): 572–82.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - np.mean(simulated_array)
b = observed_array - np.mean(observed_array)
c = np.std(observed_array, ddof=1) * np.std(simulated_array, ddof=1) * simulated_array.size
return np.dot(a, b / c)
def mape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the mean absolute percentage error (MAPE).
.. image:: /pictures/MAPE.png
**Range:** 0% ≤ MAPE ≤ inf. 0% indicates perfect correlation, a larger error indicates a
larger percent error in the data.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
c = 100 / simulated_array.size
return c * np.sum(b)
def mapd(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the mean absolute percentage deviation (MAPD).
.. image:: /pictures/MAPD.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage deviation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mapd(sim, obs)
0.10526315789473682
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(np.abs(observed_array))
return a / b
def maape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the Mean Arctangent Absolute Percentage Error (MAAPE).
.. image:: /pictures/MAAPE.png
**Range:** 0 ≤ MAAPE < π/2, does not indicate bias, smaller is better.
**Notes:** Represents the mean absolute error as a percentage of the observed values. Handles
0s in the observed data. This metric is not as biased as MAPE by under-over predictions.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean arctangent absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
- Kim, S., Kim, H., 2016. A new metric of absolute percentage error for intermittent demand
forecasts. International Journal of Forecasting 32(3) 669-679.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
return np.mean(np.arctan(b))
def smape1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (1) (SMAPE1).
.. image:: /pictures/SMAPE1.png
**Range:** 0 ≤ SMAPE1 < 100%, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (1).
Examples
--------
Note that if we switch the simulated and observed arrays the result is the same
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape1(sim, obs)
5.871915694397428
>>> he.smape1(obs, sim)
5.871915694397428
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 100 / simulated_array.size
b = np.abs(simulated_array - observed_array)
c = np.abs(simulated_array) + np.abs(observed_array)
return a * np.sum(b / c)
def smape2(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (2) (SMAPE2).
.. image:: /pictures/SMAPE2.png
**Range:** 0 ≤ SMAPE1 < 200%, does not indicate bias, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE with only positive metric values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (2).
Examples
--------
Note that switching the simulated and observed arrays yields the same results
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape2(sim, obs)
11.743831388794856
>>> he.smape2(obs, sim)
11.743831388794856
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = (simulated_array + observed_array) / 2
c = 100 / simulated_array.size
return c * np.sum(np.abs(a / b))
def d(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d).
.. image:: /pictures/d.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d(sim, obs)
0.978477353035657
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (observed_array - simulated_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
return 1 - (np.sum(a) / np.sum((b + c) ** 2))
def d1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d1).
.. image:: /pictures/d1.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric. Compared
to the other index of agreement (d) it has a reduced impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (d1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1(sim, obs)
0.8434782608695652
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
obs_mean = np.mean(observed_array)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.abs(simulated_array - obs_mean)
c = np.abs(observed_array - obs_mean)
return 1 - np.sum(a) / np.sum(b + c)
def dr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the refined index of agreement (dr).
.. image:: /pictures/dr.png
**Range:** -1 ≤ dr < 1, does not indicate bias, larger is better.
**Notes:** Reformulation of Willmott’s index of agreement. This metric was created to address
issues in the index of agreement and the Nash-Sutcliffe efficiency metric. Meant to be a
flexible metric for use in climatology.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The refined index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dr(sim, obs)
0.847457627118644
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = 2 * np.sum(np.abs(observed_array - observed_array.mean()))
if a <= b:
return 1 - (a / b)
else:
return (b / a) - 1
def drel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the relative index of agreement (drel).
.. image:: /pictures/drel.png
**Range:** 0 ≤ drel < 1, does not indicate bias, larger is better.
**Notes:** Instead of absolute differences, this metric uses relative differences.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.drel(sim, obs)
0.9740868625579597
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = ((simulated_array - observed_array) / observed_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = ((b + c) / np.mean(observed_array)) ** 2
return 1 - (np.sum(a) / np.sum(e))
def dmod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the modified index of agreement (dmod).
.. image:: /pictures/dmod.png
**Range:** 0 ≤ dmod < 1, does not indicate bias, larger is better.
**Notes:** When j=1, this metric is the same as d1. As j becomes larger, outliers have a larger
impact on the value.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
Optional input indicating the j values desired. A higher j places more emphasis on
outliers. j is 1 by default.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified index of agreement.
Examples
--------
Note that using the default is the same as calculating the d1 metric. Changing the value of j
modification of the metric.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dmod(sim, obs) # Same as d1
0.8434782608695652
>>> he.dmod(sim, obs, j=1.5)
0.9413310986805733
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = (b + c) ** j
return 1 - (np.sum(a) / np.sum(e))
def mb_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute Mielke-Berry R value (MB R).
.. image:: /pictures/MB_R.png
**Range:** 0 ≤ MB R < 1, does not indicate bias, larger is better.
**Notes:** Compares prediction to probability it arose by chance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Mielke-Berry R value.
Notes
-----
If a more optimized version is desired, the `numba package <http://numba.pydata.org/doc.html>`_ can be implemented
for a much more optimized performance when computing this metric. An example is given below.
>>> from numba import njit, prange
>>> @njit(parallel=True, fastmath=True)
>>> def mb_par_fastmath(pred, obs): # uses LLVM compiler
>>> assert pred.size == obs.size
>>> n = pred.size
>>> tot = 0.0
>>> mae = 0.0
>>> for i in range(n):
>>> for j in prange(n):
>>> tot += abs(pred[i] - obs[j])
>>> mae += abs(pred[i] - obs[i])
>>> mae = mae / n
>>> mb = 1 - ((n ** 2) * mae / tot)
>>>
>>> return mb
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mb_r(sim, obs)
0.7726315789473684
References
----------
- Berry, K.J., Mielke, P.W., 1988. A Generalization of Cohen's Kappa Agreement Measure to
Interval Measurement and Multiple Raters. Educational and Psychological Measurement 48(4)
921-933.
- Mielke, P.W., Berry, K.J., 2007. Permutation methods: a distance function approach.
Springer Science & Business Media.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Calculate metric
n = simulated_array.size
tot = 0.0
for i in range(n):
tot = tot + np.sum(np.abs(simulated_array - observed_array[i]))
mae_val = np.sum(np.abs(simulated_array - observed_array)) / n
mb = 1 - ((n ** 2) * mae_val / tot)
return mb
def nse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Nash-Sutcliffe Efficiency.
.. image:: /pictures/NSE.png
**Range:** -inf < NSE < 1, does not indicate bias, larger is better.
**Notes:** The Nash-Sutcliffe efficiency metric compares prediction values to naive predictions
(i.e. average value). One major flaw of this metric is that it punishes a higher variance in
the observed values (denominator). This metric is analogous to the mean absolute error skill
score (MAESS) using the mean flow as a benchmark.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Nash-Sutcliffe Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse(sim, obs)
0.922093023255814
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
- McCuen, R.H., Knight, Z., Cutter, A.G., 2006. Evaluation of the Nash-Sutcliffe Efficiency
Index. Journal of Hydraulic Engineering.
- Nash, J.E., Sutcliffe, J.V., 1970. River flow forecasting through conceptual models part
I — A discussion of principles. Journal of Hydrology 282-290.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** 2
b = (np.abs(observed_array - np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def nse_mod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the modified Nash-Sutcliffe efficiency (NSE mod).
.. image:: /pictures/NSEmod.png
**Range:** -inf < NSE (mod) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
If given, sets the value of j to the input. j is 1 by default. A higher j gives more
emphasis to outliers
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_mod(sim, obs)
0.6949152542372882
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = (np.abs(observed_array - np.mean(observed_array))) ** j
return 1 - (np.sum(a) / np.sum(b))
def nse_rel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the relative Nash-Sutcliffe efficiency (NSE rel).
.. image:: /pictures/NSErel.png
**Range:** -inf < NSE (rel) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_rel(sim, obs)
0.9062004687708474
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs((simulated_array - observed_array) / observed_array)) ** 2
b = (np.abs((observed_array - np.mean(observed_array)) / np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def kge_2009(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""Compute the Kling-Gupta efficiency (2009).
.. image:: /pictures/KGE_2009.png
**Range:** -inf < KGE (2009) < 1, larger is better.
**Notes:** Gupta et al. (2009) created this metric to demonstrate the relative importance of
the three components of the NSE, which are correlation, bias and variability. This was done
with hydrologic modeling as the context. This metric is meant to address issues with the NSE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), Alpha, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, alpha, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2009) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2009(sim, obs)
0.912223072345668
>>> he.kge_2009(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.927910707932087, 1.0058823529411764, 0.9181073779138655)
References
----------
- Gupta, H. V., Kling, H., Yilmaz, K. K., & Martinez, G. F. (2009). Decomposition of the mean
squared error and NSE performance criteria: Implications for improving hydrological modelling.
Journal of Hydrology, 377(1-2), 80-91.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array, ddof=1)
obs_sigma = np.std(observed_array, ddof=1)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
if obs_mean != 0:
beta = sim_mean / obs_mean
else:
beta = np.nan
# Relative variability between simulated and observed values
if obs_sigma != 0:
alpha = sim_sigma / obs_sigma
else:
alpha = np.nan
if not np.isnan(beta) and not np.isnan(alpha):
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (alpha - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Alpha is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, alpha, beta, kge
else:
return kge
def kge_2012(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""
Compute the Kling-Gupta efficiency (2012).
.. image:: /pictures/KGE_2012.png
**Range:** -inf < KGE (2012) < 1, does not indicate bias, larger is better.
**Notes:** The modified version of the KGE (2009). Kling proposed this version to avoid
cross-correlation between bias and variability ratios.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), gamma, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, gamma, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2012) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2012(sim, obs)
0.9122230723456678
>>> he.kge_2012(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.9224843295231272, 1.0058823529411764, 0.9132923608280753)
References
----------
- Kling, H., Fuchs, M., & Paulin, M. (2012). Runoff conditions in the upper Danube basin under
an ensemble of climate change scenarios. Journal of Hydrology, 424, 264-277.
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array)
obs_sigma = np.std(observed_array)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
beta = sim_mean / obs_mean
# CV is the coefficient of variation (standard deviation / mean)
sim_cv = sim_sigma / sim_mean
obs_cv = obs_sigma / obs_mean
# Variability Ratio, or the ratio of simulated CV to observed CV
gam = sim_cv / obs_cv
if obs_mean != 0 and obs_sigma != 0 and sim_mean != 0:
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (gam - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
if sim_mean == 0:
warnings.warn(
'Warning: The simulated data mean is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, gam, beta, kge
else:
return kge
def lm_index(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""
Compute the Legate-McCabe Efficiency Index.
.. image:: /pictures/E1p.png
**Range:** 0 ≤ E1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.lm_index(sim, obs)
0.6949152542372882
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
mean_obs = np.mean(observed_array)
if obs_bar_p is not None:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def d1_p(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""Compute the Legate-McCabe Index of Agreement.
.. image:: /pictures/D1p.png
**Range:** 0 ≤ d1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1_p(sim, obs)
0.8434782608695652
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
if obs_bar_p is not None:
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - obs_bar_p) + np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
mean_obs = np.mean(observed_array)
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - mean_obs) + np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def ve(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Volumetric Efficiency (VE).
.. image:: /pictures/VE.png
**Range:** 0 ≤ VE < 1 smaller is better, does not indicate bias.
**Notes:** Represents the error as a percentage of flow.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Volumetric Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ve(sim, obs)
0.8947368421052632
References
----------
- Criss, R.E., Winston, W.E., 2008. Do Nash values have value? Discussion and alternate
proposals. Hydrological Processes 22(14) 2723.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(observed_array)
return 1 - (a / b)
def sa(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Angle (SA).
.. image:: /pictures/SA.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral angle metric measures the angle between the two vectors in hyperspace.
It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Angle value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sa(sim, obs)
0.10816831366492945
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(simulated_array, observed_array)
b = np.linalg.norm(simulated_array) * np.linalg.norm(observed_array)
return np.arccos(a / b)
def sc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Correlation (SC).
.. image:: /pictures/SC.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral correlation metric measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Correlation value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sc(sim, obs)
0.27991341383646606
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(observed_array - np.mean(observed_array), simulated_array - np.mean(simulated_array))
b = np.linalg.norm(observed_array - np.mean(observed_array))
c = np.linalg.norm(simulated_array - np.mean(simulated_array))
e = b * c
return np.arccos(a / e)
def sid(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Information Divergence (SID).
.. image:: /pictures/SID.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral information divergence measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral information divergence value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sid(sim, obs)
0.03517616895318012
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
first = (observed_array / np.mean(observed_array)) - (
simulated_array / np.mean(simulated_array))
second1 = np.log10(observed_array) - np.log10(np.mean(observed_array))
second2 = np.log10(simulated_array) - np.log10(np.mean(simulated_array))
return np.dot(first, second1 - second2)
def sga(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Gradient Angle (SGA).
.. image:: /pictures/SGA.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral gradient angle measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
SG is the gradient of the simulated or observed time series.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Gradient Angle.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sga(sim, obs)
0.26764286472739834
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sgx = observed_array[1:] - observed_array[:observed_array.size - 1]
sgy = simulated_array[1:] - simulated_array[:simulated_array.size - 1]
a = np.dot(sgx, sgy)
b = np.linalg.norm(sgx) * np.linalg.norm(sgy)
return np.arccos(a / b)
####################################################################################################
# H Metrics: Methods from Tornqvist L, Vartia P, and Vartia YO. (1985) #
####################################################################################################
def h1_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the H1 mean error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mhe(sim, obs)
0.002106551840594386
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(h)
def h1_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H1 absolute error.
.. image:: /pictures/H1.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The H1 absolute error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mahe(sim, obs)
0.11639226612630865
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(np.abs(h))
def h1_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H1 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean squared H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_rmshe(sim, obs)
0.12865571253672756
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.sqrt(np.mean(h ** 2))
def h2_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean error.
.. image:: /pictures/H2.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mhe(sim, obs)
-0.015319829424307036
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(h)
def h2_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean absolute error.
.. image:: /pictures/H2.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mahe(sim, obs)
0.11997591408039167
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(np.abs(h))
def h2_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_rmshe(sim, obs)
0.1373586680669673
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.sqrt(np.mean(h ** 2))
def h3_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 mean error.
.. image:: /pictures/H3.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mhe(sim, obs)
-0.006322019630356533
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(h)
def h3_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H3 mean absolute error.
.. image:: /pictures/H3.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mahe(sim, obs)
0.11743831388794855
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(np.abs(h))
def h3_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 root mean square error.
.. image:: /pictures/H3.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.sqrt(np.mean(h ** 2))
def h4_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mhe(sim, obs)
-0.0064637371129817
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(h)
def h4_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H4 mean absolute error.
.. image:: /pictures/H4.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mahe(sim, obs)
0.11781032209144082
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(np.abs(h))
def h4_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_rmshe(sim, obs)
0.13200901963465006
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.sqrt(np.mean(h ** 2))
def h5_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean error.
.. image:: /pictures/H5.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mhe(sim, obs)
-0.006606638791856322
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(h)
def h5_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean absolute error.
.. image:: /pictures/H5.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mahe(sim, obs)
0.11818409010335018
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(np.abs(h))
def h5_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 root mean square error.
.. image:: /pictures/H5.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_rmshe(sim, obs)
0.13254476469410933
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h6_mhe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H6 mean error.
.. image:: /pictures/H6.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mhe(sim, obs)
-0.006322019630356514
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(h)
def h6_mahe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""Compute the H6 mean absolute error.
.. image:: /pictures/H6.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mahe(sim, obs)
0.11743831388794852
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(np.abs(h))
def h6_rmshe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the H6 root mean square error.
.. image:: /pictures/H6.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h7_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean error.
.. image:: /pictures/H7.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mhe(sim, obs)
0.0026331898007430263
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(h)
def h7_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean absolute error.
.. image:: /pictures/H7.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mahe(sim, obs)
0.14549033265788583
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(np.abs(h))
def h7_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 root mean square error.
.. image:: /pictures/H7.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_rmshe(sim, obs)
0.16081964067090945
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
def h8_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H8 mean error.
.. image:: /pictures/H8.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mhe(sim, obs)
0.0018056158633666466
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(h)
def h8_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 mean absolute error.
.. image:: /pictures/H8.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mahe(sim, obs)
0.099764799536836
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(np.abs(h))
def h8_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 root mean square error.
.. image:: /pictures/H8.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_rmshe(sim, obs)
0.11027632503148076
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
# def h9(simulated_array, observed_array, h_type='mhe', k=1):
# h = (simulated_array / observed_array - 1) / \
# np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
# if h_type == 'mhe':
# return h.mean()
# elif h_type == 'ahe':
# return np.abs(h).mean()
# elif h_type == 'rmshe':
# return np.sqrt((h**2).mean())
# else:
# raise RuntimeError("The three types available are 'mhe', 'ahe', and 'rmshe'.")
def h10_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean error.
.. image:: /pictures/H10.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h10_mhe(sim, obs)
-0.0012578676058971154
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(h)
def h10_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean absolute error.
.. image:: /pictures/H10.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_mahe(sim, obs), 6)
0.094636
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(np.abs(h))
def h10_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 root mean square error.
.. image:: /pictures/H10.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_rmshe(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.sqrt(np.mean(h ** 2))
###################################################################################################
# Statistical Error Metrics for Distribution Testing #
###################################################################################################
def g_mean_diff(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the geometric mean difference.
.. image:: /pictures/GMD.png
**Range:**
**Notes:** For the difference of geometric means, the geometric mean is computed for each of
two samples then their difference is taken.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The geometric mean difference value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.g_mean_diff(sim, obs)
0.988855412098022
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.exp(gmean(sim_log) - gmean(obs_log))
def mean_var(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the mean variance.
.. image:: /pictures/MV.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean variance.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.mean_var(sim, obs), 6)
0.010641
References
----------
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.var(np.log1p(observed_array) - np.log1p(simulated_array))
####################################################################################################
# HELPER FUNCTIONS AND API INFORMATION #
####################################################################################################
metric_names = [
'Mean Error', 'Mean Absolute Error', 'Mean Squared Error', 'Mean Log Error',
'Mean Absolute Log Error', 'Mean Squared Log Error', 'Median Error', 'Median Absolute Error',
'Median Squared Error', 'Eclidean Distance', 'Normalized Eclidean Distance',
'Root Mean Square Error', 'Root Mean Squared Log Error',
'Normalized Root Mean Square Error - Range', 'Normalized Root Mean Square Error - Mean',
'Normalized Root Mean Square Error - IQR', 'Inertial Root Mean Square Error',
'Mean Absolute Scaled Error', 'Coefficient of Determination', 'Pearson Correlation Coefficient',
'Spearman Rank Correlation Coefficient', 'Anomaly Correlation Coefficient',
'Mean Absolute Percentage Error', 'Mean Absolute Percentage Deviation',
'Mean Arctangent Absolute Percentage Error', 'Symmetric Mean Absolute Percentage Error (1)',
'Symmetric Mean Absolute Percentage Error (2)', 'Index of Agreement (d)',
'Index of Agreement (d1)', 'Modified Index of Agreement', 'Relative Index of Agreement',
'Index of Agreement Refined (dr)', "Watterson's M", 'Mielke-Berry R',
'Nash-Sutcliffe Efficiency', 'Modified Nash-Sutcliffe Efficiency',
'Relative Nash-Sutcliffe Efficiency', 'Kling-Gupta Efficiency (2009)',
'Kling-Gupta Efficiency (2012)', 'Legate-McCabe Efficiency Index',
'Legate-McCabe Index of Agreement', 'Volumetric Efficiency', 'Spectral Angle',
'Spectral Correlation', 'Spectral Information Divergence', 'Spectral Gradient Angle',
'Mean H1 Error', 'Mean Absolute H1 Error', 'Root Mean Square H1 Error', 'Mean H2 Error',
'Mean Absolute H2 Error', 'Root Mean Square H2 Error', 'Mean H3 Error',
'Mean Absolute H3 Error', 'Root Mean Square H3 Error', 'Mean H4 Error',
'Mean Absolute H4 Error', 'Root Mean Square H4 Error', 'Mean H5 Error',
'Mean Absolute H5 Error', 'Root Mean Square H5 Error', 'Mean H6 Error',
'Mean Absolute H6 Error', 'Root Mean Square H6 Error', 'Mean H7 Error',
'Mean Absolute H7 Error', 'Root Mean Square H7 Error', 'Mean H8 Error',
'Mean Absolute H8 Error', 'Root Mean Square H8 Error', 'Mean H10 Error',
'Mean Absolute H10 Error', 'Root Mean Square H10 Error', 'Geometric Mean Difference',
'Mean Variance'
]
metric_abbr = [
'ME', 'MAE', 'MSE', 'MLE', 'MALE', 'MSLE', 'MdE', 'MdAE', 'MdSE', 'ED', 'NED', 'RMSE', 'RMSLE',
'NRMSE (Range)', 'NRMSE (Mean)', 'NRMSE (IQR)', 'IRMSE', 'MASE', 'r2', 'R (Pearson)',
'R (Spearman)', 'ACC', 'MAPE', 'MAPD', 'MAAPE', 'SMAPE1', 'SMAPE2', 'd', 'd1', 'd (Mod.)',
'd (Rel.)', 'dr', 'M', '(MB) R', 'NSE', 'NSE (Mod.)', 'NSE (Rel.)', 'KGE (2009)', 'KGE (2012)',
"E1'", "D1'", 'VE', 'SA', 'SC', 'SID', 'SGA', 'H1 (MHE)', 'H1 (MAHE)', 'H1 (RMSHE)', 'H2 (MHE)',
'H2 (MAHE)', 'H2 (RMSHE)', 'H3 (MHE)', 'H3 (MAHE)', 'H3 (RMSHE)', 'H4 (MHE)', 'H4 (MAHE)',
'H4 (RMSHE)', 'H5 (MHE)', 'H5 (MAHE)', 'H5 (RMSHE)', 'H6 (MHE)', 'H6 (MAHE)', 'H6 (RMSHE)',
'H7 (MHE)', 'H7 (MAHE)', 'H7 (RMSHE)', 'H8 (MHE)', 'H8 (MAHE)', 'H8 (RMSHE)', 'H10 (MHE)',
'H10 (MAHE)', 'H10 (RMSHE)', 'GMD', 'MV'
]
function_list = [
me, mae, mse, mle, male, msle, mde, mdae, mdse, ed, ned, rmse, rmsle, nrmse_range, nrmse_mean,
nrmse_iqr, irmse, mase, r_squared, pearson_r, spearman_r, acc, mape, mapd, maape, smape1,
smape2, d, d1, dmod, drel, dr, watt_m, mb_r, nse, nse_mod, nse_rel, kge_2009, kge_2012,
lm_index, d1_p, ve, sa, sc, sid, sga, h1_mhe, h1_mahe, h1_rmshe, h2_mhe, h2_mahe, h2_rmshe,
h3_mhe, h3_mahe, h3_rmshe, h4_mhe, h4_mahe, h4_rmshe, h5_mhe, h5_mahe, h5_rmshe, h6_mhe,
h6_mahe, h6_rmshe, h7_mhe, h7_mahe, h7_rmshe, h8_mhe, h8_mahe, h8_rmshe, h10_mhe, h10_mahe,
h10_rmshe, g_mean_diff, mean_var,
]
# Assign some properties to each function for ease of use for users
for i in range(len(function_list)):
function_list[i].name = metric_names[i]
function_list[i].abbr = metric_abbr[i]
def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Removes the nan, negative, and inf values in two numpy arrays"""
sim_copy = np.copy(simulated_array)
obs_copy = np.copy(observed_array)
# Checking to see if the vectors are the same length
assert sim_copy.ndim == 1, "The simulated array is not one dimensional."
assert obs_copy.ndim == 1, "The observed array is not one dimensional."
if sim_copy.size != obs_copy.size:
raise RuntimeError("The two ndarrays are not the same size.")
# Treat missing data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain nan values
all_treatment_array = np.ones(obs_copy.size, dtype=bool)
if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_nan = np.isnan(sim_copy)
obs_nan = np.isnan(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_nan] = replace_nan
obs_copy[obs_nan] = replace_nan
warnings.warn("Elements(s) {} contained NaN values in the simulated array and "
"elements(s) {} contained NaN values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_nan)[0],
np.where(obs_nan)[0]),
UserWarning)
else:
# Getting the indices of the nan values, combining them, and informing user.
nan_indices_fcst = ~np.isnan(sim_copy)
nan_indices_obs = ~np.isnan(obs_copy)
all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)
warnings.warn("Row(s) {} contained NaN values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_nan_indices)[0]),
UserWarning)
if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_inf = np.isinf(sim_copy)
obs_inf = np.isinf(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_inf] = replace_inf
obs_copy[obs_inf] = replace_inf
warnings.warn("Elements(s) {} contained Inf values in the simulated array and "
"elements(s) {} contained Inf values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_inf)[0],
np.where(obs_inf)[0]),
UserWarning)
else:
inf_indices_fcst = ~(np.isinf(sim_copy))
inf_indices_obs = ~np.isinf(obs_copy)
all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)
warnings.warn(
"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows "
"are zero indexed).".format(np.where(~all_inf_indices)[0]),
UserWarning
)
# Treat zero data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain zero values
if remove_zero:
if (obs_copy == 0).any() or (sim_copy == 0).any():
zero_indices_fcst = ~(sim_copy == 0)
zero_indices_obs = ~(obs_copy == 0)
all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)
warnings.warn(
"Row(s) {} contained zero values and the row(s) have been removed (Rows are "
"zero indexed).".format(np.where(~all_zero_indices)[0]),
UserWarning
)
# Treat negative data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain negative values
# Ignore runtime warnings from comparing
if remove_neg:
with np.errstate(invalid='ignore'):
obs_copy_bool = obs_copy < 0
sim_copy_bool = sim_copy < 0
if obs_copy_bool.any() or sim_copy_bool.any():
neg_indices_fcst = ~sim_copy_bool
neg_indices_obs = ~obs_copy_bool
all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)
warnings.warn("Row(s) {} contained negative values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_neg_indices)[0]),
UserWarning)
obs_copy = obs_copy[all_treatment_array]
sim_copy = sim_copy[all_treatment_array]
return sim_copy, obs_copy
if __name__ == "__main__":
pass
|
BYU-Hydroinformatics/HydroErr | HydroErr/HydroErr.py | kge_2009 | python | def kge_2009(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array, ddof=1)
obs_sigma = np.std(observed_array, ddof=1)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
if obs_mean != 0:
beta = sim_mean / obs_mean
else:
beta = np.nan
# Relative variability between simulated and observed values
if obs_sigma != 0:
alpha = sim_sigma / obs_sigma
else:
alpha = np.nan
if not np.isnan(beta) and not np.isnan(alpha):
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (alpha - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Alpha is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, alpha, beta, kge
else:
return kge | Compute the Kling-Gupta efficiency (2009).
.. image:: /pictures/KGE_2009.png
**Range:** -inf < KGE (2009) < 1, larger is better.
**Notes:** Gupta et al. (2009) created this metric to demonstrate the relative importance of
the three components of the NSE, which are correlation, bias and variability. This was done
with hydrologic modeling as the context. This metric is meant to address issues with the NSE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), Alpha, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, alpha, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2009) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2009(sim, obs)
0.912223072345668
>>> he.kge_2009(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.927910707932087, 1.0058823529411764, 0.9181073779138655)
References
----------
- Gupta, H. V., Kling, H., Yilmaz, K. K., & Martinez, G. F. (2009). Decomposition of the mean
squared error and NSE performance criteria: Implications for improving hydrological modelling.
Journal of Hydrology, 377(1-2), 80-91. | train | https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L3023-L3151 | [
"def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,\n remove_neg=False, remove_zero=False):\n \"\"\"Removes the nan, negative, and inf values in two numpy arrays\"\"\"\n sim_copy = np.copy(simulated_array)\n obs_copy = np.copy(observed_array)\n\n # Checking to see if the vectors are the same length\n assert sim_copy.ndim == 1, \"The simulated array is not one dimensional.\"\n assert obs_copy.ndim == 1, \"The observed array is not one dimensional.\"\n\n if sim_copy.size != obs_copy.size:\n raise RuntimeError(\"The two ndarrays are not the same size.\")\n\n # Treat missing data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain nan values\n all_treatment_array = np.ones(obs_copy.size, dtype=bool)\n\n if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_nan = np.isnan(sim_copy)\n obs_nan = np.isnan(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_nan] = replace_nan\n obs_copy[obs_nan] = replace_nan\n\n warnings.warn(\"Elements(s) {} contained NaN values in the simulated array and \"\n \"elements(s) {} contained NaN values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_nan)[0],\n np.where(obs_nan)[0]),\n UserWarning)\n else:\n # Getting the indices of the nan values, combining them, and informing user.\n nan_indices_fcst = ~np.isnan(sim_copy)\n nan_indices_obs = ~np.isnan(obs_copy)\n all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)\n\n warnings.warn(\"Row(s) {} contained NaN values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_nan_indices)[0]),\n UserWarning)\n\n if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_inf = np.isinf(sim_copy)\n obs_inf = np.isinf(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_inf] = replace_inf\n obs_copy[obs_inf] = replace_inf\n\n warnings.warn(\"Elements(s) {} contained Inf values in the simulated array and \"\n \"elements(s) {} contained Inf values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_inf)[0],\n np.where(obs_inf)[0]),\n UserWarning)\n else:\n inf_indices_fcst = ~(np.isinf(sim_copy))\n inf_indices_obs = ~np.isinf(obs_copy)\n all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)\n\n warnings.warn(\n \"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows \"\n \"are zero indexed).\".format(np.where(~all_inf_indices)[0]),\n UserWarning\n )\n\n # Treat zero data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain zero values\n if remove_zero:\n if (obs_copy == 0).any() or (sim_copy == 0).any():\n zero_indices_fcst = ~(sim_copy == 0)\n zero_indices_obs = ~(obs_copy == 0)\n all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)\n\n warnings.warn(\n \"Row(s) {} contained zero values and the row(s) have been removed (Rows are \"\n \"zero indexed).\".format(np.where(~all_zero_indices)[0]),\n UserWarning\n )\n\n # Treat negative data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain negative values\n\n # Ignore runtime warnings from comparing\n if remove_neg:\n with np.errstate(invalid='ignore'):\n obs_copy_bool = obs_copy < 0\n sim_copy_bool = sim_copy < 0\n\n if obs_copy_bool.any() or sim_copy_bool.any():\n neg_indices_fcst = ~sim_copy_bool\n neg_indices_obs = ~obs_copy_bool\n all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)\n\n warnings.warn(\"Row(s) {} contained negative values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_neg_indices)[0]),\n UserWarning)\n\n obs_copy = obs_copy[all_treatment_array]\n sim_copy = sim_copy[all_treatment_array]\n\n return sim_copy, obs_copy\n"
] | # -*- coding: utf-8 -*-
"""
HydroErr contains a library of goodness of fit metrics that measure hydrologic skill.
Each metric is contained in function, and every function has the parameters to treat missing values as
well as remove zero and negative values from the timeseries data.
Each function contains two properties, name and abbr. These can be used in the Hydrostats package when creating tables
and adding metrics to the plots. Link to the hydrostats package: https://github.com/BYU-Hydroinformatics/Hydrostats.
An example of this functionality is shown below.
>>> import HydroErr as he
>>>
>>> he.acc.name
'Anomaly Correlation Coefficient'
>>> he.acc.abbr
'ACC'
"""
from __future__ import division
import numpy as np
from scipy.stats import gmean, rankdata
import warnings
__all__ = ['me', 'mae', 'mse', 'mle', 'male', 'msle', 'mde', 'mdae', 'mdse', 'ed', 'ned', 'rmse',
'rmsle', 'nrmse_range', 'nrmse_mean', 'nrmse_iqr', 'irmse', 'mase', 'r_squared',
'pearson_r', 'spearman_r', 'acc', 'mape', 'mapd', 'maape', 'smape1', 'smape2', 'd', 'd1',
'dmod', 'drel', 'dr', 'watt_m', 'mb_r', 'nse', 'nse_mod', 'nse_rel', 'kge_2009',
'kge_2012', 'lm_index', 'd1_p', 've', 'sa', 'sc', 'sid', 'sga', 'h1_mhe', 'h1_mahe',
'h1_rmshe', 'h2_mhe', 'h2_mahe', 'h2_rmshe', 'h3_mhe', 'h3_mahe', 'h3_rmshe', 'h4_mhe',
'h4_mahe', 'h4_rmshe', 'h5_mhe', 'h5_mahe', 'h5_rmshe', 'h6_mhe', 'h6_mahe', 'h6_rmshe',
'h7_mhe', 'h7_mahe', 'h7_rmshe', 'h8_mhe', 'h8_mahe', 'h8_rmshe', 'h10_mhe', 'h10_mahe',
'h10_rmshe', 'g_mean_diff', 'mean_var']
####################################################################################################
# General and Hydrological Error Metrics #
####################################################################################################
def me(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean error of the simulated and observed data.
.. image:: /pictures/ME.png
**Range:** -inf < MAE < inf, data units, closer to zero is better, indicates bias.
**Notes:** The mean error (ME) measures the difference between the simulated data and the
observed data. For the mean error, a smaller number indicates a better fit to the original
data. Note that if the error is in the form of random noise, the mean error will be very small,
which can skew the accuracy of this metric. ME is cumulative and will be small even if there
are large positive and negative errors that balance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean error value.
Examples
--------
Note that in this example the random noise cancels, leaving a very small ME.
>>> import HydroErr as he
>>> import numpy as np
>>> # Seed for reproducibility
>>> np.random.seed(54839)
>>> x = np.arange(100) / 20
>>> sim = np.sin(x) + 2
>>> obs = sim * (((np.random.rand(100) - 0.5) / 10) + 1)
>>> he.me(sim, obs)
-0.006832220968967168
References
----------
- Fisher, R.A., 1920. A Mathematical Examination of the Methods of Determining the Accuracy of
an Observation by the Mean Error, and by the Mean Square Error. Monthly Notices of the Royal
Astronomical Society 80 758 - 770.
"""
# Treating missing values
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero)
return np.mean(simulated_array - observed_array)
def mae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute error of the simulated and observed data.
.. image:: /pictures/MAE.png
**Range:** 0 ≤ MAE < inf, data units, smaller is better.
**Notes:** The ME measures the absolute difference between the simulated data and the observed
data. For the mean abolute error, a smaller number indicates a better fit to the original data.
Also note that random errors do not cancel. Also referred to as an L1-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute error value.
References
----------
- Willmott, Cort J., and Kenji Matsuura. “Advantages of the Mean Absolute Error (MAE) over the
Root Mean Square Error (RMSE) in Assessing Average Model Performance.” Climate Research 30,
no. 1 (2005): 79–82.
- Willmott, Cort J., and Kenji Matsuura. “On the Use of Dimensioned Measures of Error to
Evaluate the Performance of Spatial Interpolators.” International Journal of Geographical
Information Science 20, no. 1 (2006): 89–102.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mae(sim, obs)
0.5666666666666665
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean(np.absolute(simulated_array - observed_array))
def mse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared error of the simulated and observed data.
.. image:: /pictures/MSE.png
**Range:** 0 ≤ MSE < inf, data units squared, smaller is better.
**Notes:** Random errors do not cancel, highlights larger errors, also referred to as a
squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mse(sim, obs)
0.4333333333333333
References
----------
- Wang, Zhou, and Alan C. Bovik. “Mean Squared Error: Love It or Leave It? A New Look at Signal
Fidelity Measures.” IEEE Signal Processing Magazine 26, no. 1 (2009): 98–117.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean((simulated_array - observed_array) ** 2)
def mle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean log error of the simulated and observed data.
.. image:: /pictures/MLE.png
**Range:** -inf < MLE < inf, data units, closer to zero is better.
**Notes** Same as the mean erro (ME) only use log ratios as the error term. Limits the impact of outliers, more
evenly weights high and low data values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mle(sim, obs)
0.002961767058151136
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(sim_log - obs_log)
def male(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean absolute log error of the simulated and observed data.
.. image:: /pictures/MALE.png
**Range:** 0 ≤ MALE < inf, data units squared, smaller is better.
**Notes** Same as MAE only use log ratios as the error term. Limits the impact of outliers,
more evenly weights high and low flows.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.male(sim, obs), 6)
0.090417
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(np.abs(sim_log - obs_log))
def msle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared log error of the simulated and observed data.
.. image:: /pictures/MSLE.png
**Range:** 0 ≤ MSLE < inf, data units squared, smaller is better.
**Notes** Same as the mean squared error (MSE) only use log ratios as the error term. Limits
the impact of outliers, more evenly weights high and low values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.msle(sim, obs), 6)
0.010426
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean((sim_log - obs_log) ** 2)
def mde(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median error (MdE) between the simulated and observed data.
.. image:: /pictures/MdE.png
**Range** -inf < MdE < inf, closer to zero is better.
**Notes** This metric indicates bias. It is similar to the mean error (ME), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mde(sim, obs)
-0.10000000000000009
Returns
-------
float
The median error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(simulated_array - observed_array)
def mdae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median absolute error (MdAE) between the simulated and observed data.
.. image:: /pictures/MdAE.png
**Range** 0 ≤ MdAE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean absolute error (MAE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdae(sim, obs)
0.75
Returns
-------
float
The median absolute error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(np.abs(simulated_array - observed_array))
def mdse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median squared error (MdSE) between the simulated and observed data.
.. image:: /pictures/MdSE.png
**Range** 0 ≤ MdSE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean squared error (MSE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdse(sim, obs)
0.625
Returns
-------
float
The median squared error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median((simulated_array - observed_array) ** 2)
def ed(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Euclidean distance between predicted and observed values in vector space.
.. image:: /pictures/ED.png
**Range** 0 ≤ ED < inf, smaller is better.
**Notes** Also sometimes referred to as the L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ed(sim, obs)
1.63707055437449
Returns
-------
float
The euclidean distance error value.
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.linalg.norm(observed_array - simulated_array)
def ned(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the normalized Euclidian distance between the simulated and observed data in vector
space.
.. image:: /pictures/NED.png
**Range** 0 ≤ NED < inf, smaller is better.
**Notes** Also sometimes referred to as the squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The normalized euclidean distance value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ned(sim, obs)
0.2872053604165771
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array / np.mean(observed_array)
b = simulated_array / np.mean(simulated_array)
return np.linalg.norm(a - b)
def rmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square error between the simulated and observed data.
.. image:: /pictures/RMSE.png
**Range** 0 ≤ RMSE < inf, smaller is better.
**Notes:** The standard deviation of the residuals. A lower spread indicates that the points
are better concentrated around the line of best fit (linear). Random errors do not cancel.
This metric will highlights larger errors.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.rmse(sim, obs)
0.668331255192114
References
----------
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.sqrt(np.mean((simulated_array - observed_array) ** 2))
def rmsle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square log error between the simulated and observed data.
.. image:: /pictures/RMSLE.png
**Range:** 0 ≤ RMSLE < inf. Smaller is better, and it does not indicate bias.
**Notes:** Random errors do not cancel while using this metric. This metric limits the
impact of outliers by more evenly weighting high and low values. To calculate the log values,
each value in the observed and simulated array is increased by one unit in order to avoid
run-time errors and nan values (function np.log1p).
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square log error value.
Examples
--------
Notice that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.rmsle(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
"""
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf, remove_neg=remove_neg,
remove_zero=remove_zero)
return np.sqrt(np.mean(np.power(np.log1p(simulated_array) - np.log1p(observed_array), 2)))
def nrmse_range(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the range normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Range.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the range of the observed time series (x).
Normalizing allows comparison between data sets with different scales. The NRMSErange is the
most sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The range normalized root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_range(sim, obs)
0.0891108340256152
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_max = np.max(observed_array)
obs_min = np.min(observed_array)
return rmse_value / (obs_max - obs_min)
def nrmse_mean(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Mean.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the mean of the observed time series (x).
Normalizing allows comparison between data sets with different scales.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_mean(sim, obs)
0.11725109740212526
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_mean = np.mean(observed_array)
return rmse_value / obs_mean
def nrmse_iqr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the IQR normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_IQR.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the interquartile range of the observed time
series (x). Normalizing allows comparison between data sets with different scales.
The NRMSEquartile is the least sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The IQR normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_iqr(sim, obs)
0.2595461185212093
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
q1 = np.percentile(observed_array, 25)
q3 = np.percentile(observed_array, 75)
iqr = q3 - q1
return rmse_value / iqr
def irmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the inertial root mean square error (IRMSE) between the simulated and observed data.
.. image:: /pictures/IRMSE.png
**Range:** 0 ≤ IRMSE < inf, lower is better.
**Notes:** This metric is the RMSE devided by by the standard deviation of the gradient of the
observed timeseries data. This metric is meant to be help understand the ability of the model
to predict changes in observation.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The inertial root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.irmse(sim, obs)
0.14572738134831856
References
----------
- Daga, M., Deo, M.C., 2009. Alternative data-driven methods to estimate wind from waves by
inverse modeling. Natural Hazards 49(2) 293-310.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Getting the gradient of the observed data
obs_len = observed_array.size
obs_grad = observed_array[1:obs_len] - observed_array[0:obs_len - 1]
# Standard deviation of the gradient
obs_grad_std = np.std(obs_grad, ddof=1)
# Divide RMSE by the standard deviation of the gradient of the observed data
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
return rmse_value / obs_grad_std
def mase(simulated_array, observed_array, m=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute scaled error between the simulated and observed data.
.. image:: /pictures/MASE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
m: int
If given, indicates the seasonal period m. If not given, the default is 1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute scaled error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mase(sim, obs)
0.17341040462427745
References
----------
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
start = m
end = simulated_array.size - m
a = np.mean(np.abs(simulated_array - observed_array))
b = np.abs(observed_array[start:observed_array.size] - observed_array[:end])
return a / (np.sum(b) / end)
def pearson_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the pearson correlation coefficient.
.. image:: /pictures/R_pearson.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The pearson r coefficient measures linear correlation. It is sensitive to outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Pearson correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.pearson_r(sim, obs)
0.9610793632835262
References
----------
- Pearson, K. (1895). Note on regression and inheritance in the case of two parents.
Proceedings of the Royal Society of London, 58, 240-242.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
top = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1 = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2 = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
return top / (bot1 * bot2)
def spearman_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the spearman rank correlation coefficient.
.. image:: /pictures/R_spearman.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The spearman r coefficient measures the monotonic relation between simulated and
observed data. Because it uses a nonparametric measure of rank correlation, it is less sensitive
to outliers compared to the Pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spearman rank correlation coefficient.
Examples
----------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.spearman_r(sim, obs)
0.942857142857143
References
----------
- Spearman C (1904). "The proof and measurement of association between two things". American
Journal of Psychology. 15: 72–101. doi:10.2307/1412159
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rank_sim = rankdata(simulated_array)
rank_obs = rankdata(observed_array)
mean_rank_sim = np.mean(rank_sim)
mean_rank_obs = np.mean(rank_obs)
top = np.mean((rank_obs - mean_rank_obs) * (rank_sim - mean_rank_sim))
bot = np.sqrt(
np.mean((rank_obs - mean_rank_obs) ** 2) * np.mean((rank_sim - mean_rank_sim) ** 2))
return top / bot
def r_squared(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Coefficient of Determination (r2).
.. image:: /pictures/r2.png
**Range:** 0 ≤ r2 ≤ 1. 1 indicates perfect correlation, 0 indicates complete randomness.
**Notes:** The Coefficient of Determination measures the linear relation between simulated and
observed data. Because it is the pearson correlation coefficient squared, it is more heavily
affected by outliers than the pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The coefficient of determination (R^2).
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.r_squared(sim, obs)
0.9236735425294681
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array - np.mean(observed_array)
b = simulated_array - np.mean(simulated_array)
return (np.sum(a * b)) ** 2 / (np.sum(a ** 2) * np.sum(b ** 2))
def acc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the anomaly correlation coefficient (ACC).
.. image:: /pictures/ACC.png
**Range:** -1 ≤ ACC ≤ 1. -1 indicates perfect negative correlation of the variation
pattern of the anomalies, 0 indicates complete randomness of the variation patterns of the
anomalies, 1 indicates perfect correlation of the variation pattern of the anomalies.
**Notes:** Common measure in the verification of spatial fields. Measures the correlation
between the variation pattern of the simulated data compared to the observed data.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The anomaly correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.acc(sim, obs)
0.8008994694029383
References
----------
- Langland, Rolf H., and Ryan N. Maue. “Recent Northern Hemisphere Mid-Latitude Medium-Range
Deterministic Forecast Skill.” Tellus A: Dynamic Meteorology and Oceanography 64,
no. 1 (2012): 17531.
- Miyakoda, K., G. D. Hembree, R. F. Strickler, and I. Shulman. “Cumulative Results of Extended
Forecast Experiments I. Model Performance for Winter Cases.” Monthly Weather Review 100, no.
12(1972): 836–55.
- Murphy, Allan H., and Edward S. Epstein. “Skill Scores and Correlation Coefficients in Model
Verification.” Monthly Weather Review 117, no. 3 (1989): 572–82.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - np.mean(simulated_array)
b = observed_array - np.mean(observed_array)
c = np.std(observed_array, ddof=1) * np.std(simulated_array, ddof=1) * simulated_array.size
return np.dot(a, b / c)
def mape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the mean absolute percentage error (MAPE).
.. image:: /pictures/MAPE.png
**Range:** 0% ≤ MAPE ≤ inf. 0% indicates perfect correlation, a larger error indicates a
larger percent error in the data.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
c = 100 / simulated_array.size
return c * np.sum(b)
def mapd(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the mean absolute percentage deviation (MAPD).
.. image:: /pictures/MAPD.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage deviation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mapd(sim, obs)
0.10526315789473682
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(np.abs(observed_array))
return a / b
def maape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the Mean Arctangent Absolute Percentage Error (MAAPE).
.. image:: /pictures/MAAPE.png
**Range:** 0 ≤ MAAPE < π/2, does not indicate bias, smaller is better.
**Notes:** Represents the mean absolute error as a percentage of the observed values. Handles
0s in the observed data. This metric is not as biased as MAPE by under-over predictions.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean arctangent absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
- Kim, S., Kim, H., 2016. A new metric of absolute percentage error for intermittent demand
forecasts. International Journal of Forecasting 32(3) 669-679.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
return np.mean(np.arctan(b))
def smape1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (1) (SMAPE1).
.. image:: /pictures/SMAPE1.png
**Range:** 0 ≤ SMAPE1 < 100%, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (1).
Examples
--------
Note that if we switch the simulated and observed arrays the result is the same
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape1(sim, obs)
5.871915694397428
>>> he.smape1(obs, sim)
5.871915694397428
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 100 / simulated_array.size
b = np.abs(simulated_array - observed_array)
c = np.abs(simulated_array) + np.abs(observed_array)
return a * np.sum(b / c)
def smape2(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (2) (SMAPE2).
.. image:: /pictures/SMAPE2.png
**Range:** 0 ≤ SMAPE1 < 200%, does not indicate bias, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE with only positive metric values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (2).
Examples
--------
Note that switching the simulated and observed arrays yields the same results
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape2(sim, obs)
11.743831388794856
>>> he.smape2(obs, sim)
11.743831388794856
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = (simulated_array + observed_array) / 2
c = 100 / simulated_array.size
return c * np.sum(np.abs(a / b))
def d(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d).
.. image:: /pictures/d.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d(sim, obs)
0.978477353035657
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (observed_array - simulated_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
return 1 - (np.sum(a) / np.sum((b + c) ** 2))
def d1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d1).
.. image:: /pictures/d1.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric. Compared
to the other index of agreement (d) it has a reduced impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (d1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1(sim, obs)
0.8434782608695652
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
obs_mean = np.mean(observed_array)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.abs(simulated_array - obs_mean)
c = np.abs(observed_array - obs_mean)
return 1 - np.sum(a) / np.sum(b + c)
def dr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the refined index of agreement (dr).
.. image:: /pictures/dr.png
**Range:** -1 ≤ dr < 1, does not indicate bias, larger is better.
**Notes:** Reformulation of Willmott’s index of agreement. This metric was created to address
issues in the index of agreement and the Nash-Sutcliffe efficiency metric. Meant to be a
flexible metric for use in climatology.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The refined index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dr(sim, obs)
0.847457627118644
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = 2 * np.sum(np.abs(observed_array - observed_array.mean()))
if a <= b:
return 1 - (a / b)
else:
return (b / a) - 1
def drel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the relative index of agreement (drel).
.. image:: /pictures/drel.png
**Range:** 0 ≤ drel < 1, does not indicate bias, larger is better.
**Notes:** Instead of absolute differences, this metric uses relative differences.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.drel(sim, obs)
0.9740868625579597
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = ((simulated_array - observed_array) / observed_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = ((b + c) / np.mean(observed_array)) ** 2
return 1 - (np.sum(a) / np.sum(e))
def dmod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the modified index of agreement (dmod).
.. image:: /pictures/dmod.png
**Range:** 0 ≤ dmod < 1, does not indicate bias, larger is better.
**Notes:** When j=1, this metric is the same as d1. As j becomes larger, outliers have a larger
impact on the value.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
Optional input indicating the j values desired. A higher j places more emphasis on
outliers. j is 1 by default.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified index of agreement.
Examples
--------
Note that using the default is the same as calculating the d1 metric. Changing the value of j
modification of the metric.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dmod(sim, obs) # Same as d1
0.8434782608695652
>>> he.dmod(sim, obs, j=1.5)
0.9413310986805733
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = (b + c) ** j
return 1 - (np.sum(a) / np.sum(e))
def watt_m(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute Watterson's M (M).
.. image:: /pictures/M.png
**Range:** -1 ≤ M < 1, does not indicate bias, larger is better.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
Watterson's M value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.watt_m(sim, obs)
0.8307913876595929
References
----------
- Watterson, I.G., 1996. Non‐dimensional measures of climate model performance. International
Journal of Climatology 16(4) 379-391.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 2 / np.pi
b = np.mean((simulated_array - observed_array) ** 2) # MSE
c = np.std(observed_array, ddof=1) ** 2 + np.std(simulated_array, ddof=1) ** 2
e = (np.mean(simulated_array) - np.mean(observed_array)) ** 2
f = c + e
return a * np.arcsin(1 - (b / f))
def mb_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute Mielke-Berry R value (MB R).
.. image:: /pictures/MB_R.png
**Range:** 0 ≤ MB R < 1, does not indicate bias, larger is better.
**Notes:** Compares prediction to probability it arose by chance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Mielke-Berry R value.
Notes
-----
If a more optimized version is desired, the `numba package <http://numba.pydata.org/doc.html>`_ can be implemented
for a much more optimized performance when computing this metric. An example is given below.
>>> from numba import njit, prange
>>> @njit(parallel=True, fastmath=True)
>>> def mb_par_fastmath(pred, obs): # uses LLVM compiler
>>> assert pred.size == obs.size
>>> n = pred.size
>>> tot = 0.0
>>> mae = 0.0
>>> for i in range(n):
>>> for j in prange(n):
>>> tot += abs(pred[i] - obs[j])
>>> mae += abs(pred[i] - obs[i])
>>> mae = mae / n
>>> mb = 1 - ((n ** 2) * mae / tot)
>>>
>>> return mb
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mb_r(sim, obs)
0.7726315789473684
References
----------
- Berry, K.J., Mielke, P.W., 1988. A Generalization of Cohen's Kappa Agreement Measure to
Interval Measurement and Multiple Raters. Educational and Psychological Measurement 48(4)
921-933.
- Mielke, P.W., Berry, K.J., 2007. Permutation methods: a distance function approach.
Springer Science & Business Media.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Calculate metric
n = simulated_array.size
tot = 0.0
for i in range(n):
tot = tot + np.sum(np.abs(simulated_array - observed_array[i]))
mae_val = np.sum(np.abs(simulated_array - observed_array)) / n
mb = 1 - ((n ** 2) * mae_val / tot)
return mb
def nse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Nash-Sutcliffe Efficiency.
.. image:: /pictures/NSE.png
**Range:** -inf < NSE < 1, does not indicate bias, larger is better.
**Notes:** The Nash-Sutcliffe efficiency metric compares prediction values to naive predictions
(i.e. average value). One major flaw of this metric is that it punishes a higher variance in
the observed values (denominator). This metric is analogous to the mean absolute error skill
score (MAESS) using the mean flow as a benchmark.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Nash-Sutcliffe Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse(sim, obs)
0.922093023255814
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
- McCuen, R.H., Knight, Z., Cutter, A.G., 2006. Evaluation of the Nash-Sutcliffe Efficiency
Index. Journal of Hydraulic Engineering.
- Nash, J.E., Sutcliffe, J.V., 1970. River flow forecasting through conceptual models part
I — A discussion of principles. Journal of Hydrology 282-290.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** 2
b = (np.abs(observed_array - np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def nse_mod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the modified Nash-Sutcliffe efficiency (NSE mod).
.. image:: /pictures/NSEmod.png
**Range:** -inf < NSE (mod) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
If given, sets the value of j to the input. j is 1 by default. A higher j gives more
emphasis to outliers
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_mod(sim, obs)
0.6949152542372882
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = (np.abs(observed_array - np.mean(observed_array))) ** j
return 1 - (np.sum(a) / np.sum(b))
def nse_rel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the relative Nash-Sutcliffe efficiency (NSE rel).
.. image:: /pictures/NSErel.png
**Range:** -inf < NSE (rel) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_rel(sim, obs)
0.9062004687708474
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs((simulated_array - observed_array) / observed_array)) ** 2
b = (np.abs((observed_array - np.mean(observed_array)) / np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def kge_2012(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""
Compute the Kling-Gupta efficiency (2012).
.. image:: /pictures/KGE_2012.png
**Range:** -inf < KGE (2012) < 1, does not indicate bias, larger is better.
**Notes:** The modified version of the KGE (2009). Kling proposed this version to avoid
cross-correlation between bias and variability ratios.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), gamma, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, gamma, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2012) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2012(sim, obs)
0.9122230723456678
>>> he.kge_2012(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.9224843295231272, 1.0058823529411764, 0.9132923608280753)
References
----------
- Kling, H., Fuchs, M., & Paulin, M. (2012). Runoff conditions in the upper Danube basin under
an ensemble of climate change scenarios. Journal of Hydrology, 424, 264-277.
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array)
obs_sigma = np.std(observed_array)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
beta = sim_mean / obs_mean
# CV is the coefficient of variation (standard deviation / mean)
sim_cv = sim_sigma / sim_mean
obs_cv = obs_sigma / obs_mean
# Variability Ratio, or the ratio of simulated CV to observed CV
gam = sim_cv / obs_cv
if obs_mean != 0 and obs_sigma != 0 and sim_mean != 0:
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (gam - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
if sim_mean == 0:
warnings.warn(
'Warning: The simulated data mean is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, gam, beta, kge
else:
return kge
def lm_index(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""
Compute the Legate-McCabe Efficiency Index.
.. image:: /pictures/E1p.png
**Range:** 0 ≤ E1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.lm_index(sim, obs)
0.6949152542372882
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
mean_obs = np.mean(observed_array)
if obs_bar_p is not None:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def d1_p(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""Compute the Legate-McCabe Index of Agreement.
.. image:: /pictures/D1p.png
**Range:** 0 ≤ d1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1_p(sim, obs)
0.8434782608695652
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
if obs_bar_p is not None:
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - obs_bar_p) + np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
mean_obs = np.mean(observed_array)
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - mean_obs) + np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def ve(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Volumetric Efficiency (VE).
.. image:: /pictures/VE.png
**Range:** 0 ≤ VE < 1 smaller is better, does not indicate bias.
**Notes:** Represents the error as a percentage of flow.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Volumetric Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ve(sim, obs)
0.8947368421052632
References
----------
- Criss, R.E., Winston, W.E., 2008. Do Nash values have value? Discussion and alternate
proposals. Hydrological Processes 22(14) 2723.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(observed_array)
return 1 - (a / b)
def sa(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Angle (SA).
.. image:: /pictures/SA.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral angle metric measures the angle between the two vectors in hyperspace.
It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Angle value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sa(sim, obs)
0.10816831366492945
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(simulated_array, observed_array)
b = np.linalg.norm(simulated_array) * np.linalg.norm(observed_array)
return np.arccos(a / b)
def sc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Correlation (SC).
.. image:: /pictures/SC.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral correlation metric measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Correlation value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sc(sim, obs)
0.27991341383646606
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(observed_array - np.mean(observed_array), simulated_array - np.mean(simulated_array))
b = np.linalg.norm(observed_array - np.mean(observed_array))
c = np.linalg.norm(simulated_array - np.mean(simulated_array))
e = b * c
return np.arccos(a / e)
def sid(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Information Divergence (SID).
.. image:: /pictures/SID.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral information divergence measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral information divergence value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sid(sim, obs)
0.03517616895318012
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
first = (observed_array / np.mean(observed_array)) - (
simulated_array / np.mean(simulated_array))
second1 = np.log10(observed_array) - np.log10(np.mean(observed_array))
second2 = np.log10(simulated_array) - np.log10(np.mean(simulated_array))
return np.dot(first, second1 - second2)
def sga(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Gradient Angle (SGA).
.. image:: /pictures/SGA.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral gradient angle measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
SG is the gradient of the simulated or observed time series.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Gradient Angle.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sga(sim, obs)
0.26764286472739834
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sgx = observed_array[1:] - observed_array[:observed_array.size - 1]
sgy = simulated_array[1:] - simulated_array[:simulated_array.size - 1]
a = np.dot(sgx, sgy)
b = np.linalg.norm(sgx) * np.linalg.norm(sgy)
return np.arccos(a / b)
####################################################################################################
# H Metrics: Methods from Tornqvist L, Vartia P, and Vartia YO. (1985) #
####################################################################################################
def h1_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the H1 mean error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mhe(sim, obs)
0.002106551840594386
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(h)
def h1_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H1 absolute error.
.. image:: /pictures/H1.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The H1 absolute error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mahe(sim, obs)
0.11639226612630865
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(np.abs(h))
def h1_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H1 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean squared H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_rmshe(sim, obs)
0.12865571253672756
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.sqrt(np.mean(h ** 2))
def h2_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean error.
.. image:: /pictures/H2.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mhe(sim, obs)
-0.015319829424307036
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(h)
def h2_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean absolute error.
.. image:: /pictures/H2.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mahe(sim, obs)
0.11997591408039167
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(np.abs(h))
def h2_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_rmshe(sim, obs)
0.1373586680669673
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.sqrt(np.mean(h ** 2))
def h3_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 mean error.
.. image:: /pictures/H3.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mhe(sim, obs)
-0.006322019630356533
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(h)
def h3_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H3 mean absolute error.
.. image:: /pictures/H3.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mahe(sim, obs)
0.11743831388794855
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(np.abs(h))
def h3_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 root mean square error.
.. image:: /pictures/H3.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.sqrt(np.mean(h ** 2))
def h4_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mhe(sim, obs)
-0.0064637371129817
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(h)
def h4_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H4 mean absolute error.
.. image:: /pictures/H4.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mahe(sim, obs)
0.11781032209144082
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(np.abs(h))
def h4_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_rmshe(sim, obs)
0.13200901963465006
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.sqrt(np.mean(h ** 2))
def h5_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean error.
.. image:: /pictures/H5.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mhe(sim, obs)
-0.006606638791856322
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(h)
def h5_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean absolute error.
.. image:: /pictures/H5.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mahe(sim, obs)
0.11818409010335018
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(np.abs(h))
def h5_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 root mean square error.
.. image:: /pictures/H5.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_rmshe(sim, obs)
0.13254476469410933
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h6_mhe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H6 mean error.
.. image:: /pictures/H6.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mhe(sim, obs)
-0.006322019630356514
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(h)
def h6_mahe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""Compute the H6 mean absolute error.
.. image:: /pictures/H6.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mahe(sim, obs)
0.11743831388794852
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(np.abs(h))
def h6_rmshe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the H6 root mean square error.
.. image:: /pictures/H6.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h7_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean error.
.. image:: /pictures/H7.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mhe(sim, obs)
0.0026331898007430263
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(h)
def h7_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean absolute error.
.. image:: /pictures/H7.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mahe(sim, obs)
0.14549033265788583
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(np.abs(h))
def h7_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 root mean square error.
.. image:: /pictures/H7.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_rmshe(sim, obs)
0.16081964067090945
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
def h8_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H8 mean error.
.. image:: /pictures/H8.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mhe(sim, obs)
0.0018056158633666466
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(h)
def h8_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 mean absolute error.
.. image:: /pictures/H8.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mahe(sim, obs)
0.099764799536836
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(np.abs(h))
def h8_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 root mean square error.
.. image:: /pictures/H8.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_rmshe(sim, obs)
0.11027632503148076
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
# def h9(simulated_array, observed_array, h_type='mhe', k=1):
# h = (simulated_array / observed_array - 1) / \
# np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
# if h_type == 'mhe':
# return h.mean()
# elif h_type == 'ahe':
# return np.abs(h).mean()
# elif h_type == 'rmshe':
# return np.sqrt((h**2).mean())
# else:
# raise RuntimeError("The three types available are 'mhe', 'ahe', and 'rmshe'.")
def h10_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean error.
.. image:: /pictures/H10.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h10_mhe(sim, obs)
-0.0012578676058971154
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(h)
def h10_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean absolute error.
.. image:: /pictures/H10.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_mahe(sim, obs), 6)
0.094636
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(np.abs(h))
def h10_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 root mean square error.
.. image:: /pictures/H10.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_rmshe(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.sqrt(np.mean(h ** 2))
###################################################################################################
# Statistical Error Metrics for Distribution Testing #
###################################################################################################
def g_mean_diff(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the geometric mean difference.
.. image:: /pictures/GMD.png
**Range:**
**Notes:** For the difference of geometric means, the geometric mean is computed for each of
two samples then their difference is taken.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The geometric mean difference value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.g_mean_diff(sim, obs)
0.988855412098022
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.exp(gmean(sim_log) - gmean(obs_log))
def mean_var(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the mean variance.
.. image:: /pictures/MV.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean variance.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.mean_var(sim, obs), 6)
0.010641
References
----------
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.var(np.log1p(observed_array) - np.log1p(simulated_array))
####################################################################################################
# HELPER FUNCTIONS AND API INFORMATION #
####################################################################################################
metric_names = [
'Mean Error', 'Mean Absolute Error', 'Mean Squared Error', 'Mean Log Error',
'Mean Absolute Log Error', 'Mean Squared Log Error', 'Median Error', 'Median Absolute Error',
'Median Squared Error', 'Eclidean Distance', 'Normalized Eclidean Distance',
'Root Mean Square Error', 'Root Mean Squared Log Error',
'Normalized Root Mean Square Error - Range', 'Normalized Root Mean Square Error - Mean',
'Normalized Root Mean Square Error - IQR', 'Inertial Root Mean Square Error',
'Mean Absolute Scaled Error', 'Coefficient of Determination', 'Pearson Correlation Coefficient',
'Spearman Rank Correlation Coefficient', 'Anomaly Correlation Coefficient',
'Mean Absolute Percentage Error', 'Mean Absolute Percentage Deviation',
'Mean Arctangent Absolute Percentage Error', 'Symmetric Mean Absolute Percentage Error (1)',
'Symmetric Mean Absolute Percentage Error (2)', 'Index of Agreement (d)',
'Index of Agreement (d1)', 'Modified Index of Agreement', 'Relative Index of Agreement',
'Index of Agreement Refined (dr)', "Watterson's M", 'Mielke-Berry R',
'Nash-Sutcliffe Efficiency', 'Modified Nash-Sutcliffe Efficiency',
'Relative Nash-Sutcliffe Efficiency', 'Kling-Gupta Efficiency (2009)',
'Kling-Gupta Efficiency (2012)', 'Legate-McCabe Efficiency Index',
'Legate-McCabe Index of Agreement', 'Volumetric Efficiency', 'Spectral Angle',
'Spectral Correlation', 'Spectral Information Divergence', 'Spectral Gradient Angle',
'Mean H1 Error', 'Mean Absolute H1 Error', 'Root Mean Square H1 Error', 'Mean H2 Error',
'Mean Absolute H2 Error', 'Root Mean Square H2 Error', 'Mean H3 Error',
'Mean Absolute H3 Error', 'Root Mean Square H3 Error', 'Mean H4 Error',
'Mean Absolute H4 Error', 'Root Mean Square H4 Error', 'Mean H5 Error',
'Mean Absolute H5 Error', 'Root Mean Square H5 Error', 'Mean H6 Error',
'Mean Absolute H6 Error', 'Root Mean Square H6 Error', 'Mean H7 Error',
'Mean Absolute H7 Error', 'Root Mean Square H7 Error', 'Mean H8 Error',
'Mean Absolute H8 Error', 'Root Mean Square H8 Error', 'Mean H10 Error',
'Mean Absolute H10 Error', 'Root Mean Square H10 Error', 'Geometric Mean Difference',
'Mean Variance'
]
metric_abbr = [
'ME', 'MAE', 'MSE', 'MLE', 'MALE', 'MSLE', 'MdE', 'MdAE', 'MdSE', 'ED', 'NED', 'RMSE', 'RMSLE',
'NRMSE (Range)', 'NRMSE (Mean)', 'NRMSE (IQR)', 'IRMSE', 'MASE', 'r2', 'R (Pearson)',
'R (Spearman)', 'ACC', 'MAPE', 'MAPD', 'MAAPE', 'SMAPE1', 'SMAPE2', 'd', 'd1', 'd (Mod.)',
'd (Rel.)', 'dr', 'M', '(MB) R', 'NSE', 'NSE (Mod.)', 'NSE (Rel.)', 'KGE (2009)', 'KGE (2012)',
"E1'", "D1'", 'VE', 'SA', 'SC', 'SID', 'SGA', 'H1 (MHE)', 'H1 (MAHE)', 'H1 (RMSHE)', 'H2 (MHE)',
'H2 (MAHE)', 'H2 (RMSHE)', 'H3 (MHE)', 'H3 (MAHE)', 'H3 (RMSHE)', 'H4 (MHE)', 'H4 (MAHE)',
'H4 (RMSHE)', 'H5 (MHE)', 'H5 (MAHE)', 'H5 (RMSHE)', 'H6 (MHE)', 'H6 (MAHE)', 'H6 (RMSHE)',
'H7 (MHE)', 'H7 (MAHE)', 'H7 (RMSHE)', 'H8 (MHE)', 'H8 (MAHE)', 'H8 (RMSHE)', 'H10 (MHE)',
'H10 (MAHE)', 'H10 (RMSHE)', 'GMD', 'MV'
]
function_list = [
me, mae, mse, mle, male, msle, mde, mdae, mdse, ed, ned, rmse, rmsle, nrmse_range, nrmse_mean,
nrmse_iqr, irmse, mase, r_squared, pearson_r, spearman_r, acc, mape, mapd, maape, smape1,
smape2, d, d1, dmod, drel, dr, watt_m, mb_r, nse, nse_mod, nse_rel, kge_2009, kge_2012,
lm_index, d1_p, ve, sa, sc, sid, sga, h1_mhe, h1_mahe, h1_rmshe, h2_mhe, h2_mahe, h2_rmshe,
h3_mhe, h3_mahe, h3_rmshe, h4_mhe, h4_mahe, h4_rmshe, h5_mhe, h5_mahe, h5_rmshe, h6_mhe,
h6_mahe, h6_rmshe, h7_mhe, h7_mahe, h7_rmshe, h8_mhe, h8_mahe, h8_rmshe, h10_mhe, h10_mahe,
h10_rmshe, g_mean_diff, mean_var,
]
# Assign some properties to each function for ease of use for users
for i in range(len(function_list)):
function_list[i].name = metric_names[i]
function_list[i].abbr = metric_abbr[i]
def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Removes the nan, negative, and inf values in two numpy arrays"""
sim_copy = np.copy(simulated_array)
obs_copy = np.copy(observed_array)
# Checking to see if the vectors are the same length
assert sim_copy.ndim == 1, "The simulated array is not one dimensional."
assert obs_copy.ndim == 1, "The observed array is not one dimensional."
if sim_copy.size != obs_copy.size:
raise RuntimeError("The two ndarrays are not the same size.")
# Treat missing data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain nan values
all_treatment_array = np.ones(obs_copy.size, dtype=bool)
if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_nan = np.isnan(sim_copy)
obs_nan = np.isnan(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_nan] = replace_nan
obs_copy[obs_nan] = replace_nan
warnings.warn("Elements(s) {} contained NaN values in the simulated array and "
"elements(s) {} contained NaN values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_nan)[0],
np.where(obs_nan)[0]),
UserWarning)
else:
# Getting the indices of the nan values, combining them, and informing user.
nan_indices_fcst = ~np.isnan(sim_copy)
nan_indices_obs = ~np.isnan(obs_copy)
all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)
warnings.warn("Row(s) {} contained NaN values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_nan_indices)[0]),
UserWarning)
if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_inf = np.isinf(sim_copy)
obs_inf = np.isinf(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_inf] = replace_inf
obs_copy[obs_inf] = replace_inf
warnings.warn("Elements(s) {} contained Inf values in the simulated array and "
"elements(s) {} contained Inf values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_inf)[0],
np.where(obs_inf)[0]),
UserWarning)
else:
inf_indices_fcst = ~(np.isinf(sim_copy))
inf_indices_obs = ~np.isinf(obs_copy)
all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)
warnings.warn(
"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows "
"are zero indexed).".format(np.where(~all_inf_indices)[0]),
UserWarning
)
# Treat zero data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain zero values
if remove_zero:
if (obs_copy == 0).any() or (sim_copy == 0).any():
zero_indices_fcst = ~(sim_copy == 0)
zero_indices_obs = ~(obs_copy == 0)
all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)
warnings.warn(
"Row(s) {} contained zero values and the row(s) have been removed (Rows are "
"zero indexed).".format(np.where(~all_zero_indices)[0]),
UserWarning
)
# Treat negative data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain negative values
# Ignore runtime warnings from comparing
if remove_neg:
with np.errstate(invalid='ignore'):
obs_copy_bool = obs_copy < 0
sim_copy_bool = sim_copy < 0
if obs_copy_bool.any() or sim_copy_bool.any():
neg_indices_fcst = ~sim_copy_bool
neg_indices_obs = ~obs_copy_bool
all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)
warnings.warn("Row(s) {} contained negative values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_neg_indices)[0]),
UserWarning)
obs_copy = obs_copy[all_treatment_array]
sim_copy = sim_copy[all_treatment_array]
return sim_copy, obs_copy
if __name__ == "__main__":
pass
|
BYU-Hydroinformatics/HydroErr | HydroErr/HydroErr.py | sa | python | def sa(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(simulated_array, observed_array)
b = np.linalg.norm(simulated_array) * np.linalg.norm(observed_array)
return np.arccos(a / b) | Compute the Spectral Angle (SA).
.. image:: /pictures/SA.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral angle metric measures the angle between the two vectors in hyperspace.
It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Angle value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sa(sim, obs)
0.10816831366492945
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166. | train | https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L3538-L3612 | [
"def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,\n remove_neg=False, remove_zero=False):\n \"\"\"Removes the nan, negative, and inf values in two numpy arrays\"\"\"\n sim_copy = np.copy(simulated_array)\n obs_copy = np.copy(observed_array)\n\n # Checking to see if the vectors are the same length\n assert sim_copy.ndim == 1, \"The simulated array is not one dimensional.\"\n assert obs_copy.ndim == 1, \"The observed array is not one dimensional.\"\n\n if sim_copy.size != obs_copy.size:\n raise RuntimeError(\"The two ndarrays are not the same size.\")\n\n # Treat missing data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain nan values\n all_treatment_array = np.ones(obs_copy.size, dtype=bool)\n\n if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_nan = np.isnan(sim_copy)\n obs_nan = np.isnan(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_nan] = replace_nan\n obs_copy[obs_nan] = replace_nan\n\n warnings.warn(\"Elements(s) {} contained NaN values in the simulated array and \"\n \"elements(s) {} contained NaN values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_nan)[0],\n np.where(obs_nan)[0]),\n UserWarning)\n else:\n # Getting the indices of the nan values, combining them, and informing user.\n nan_indices_fcst = ~np.isnan(sim_copy)\n nan_indices_obs = ~np.isnan(obs_copy)\n all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)\n\n warnings.warn(\"Row(s) {} contained NaN values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_nan_indices)[0]),\n UserWarning)\n\n if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_inf = np.isinf(sim_copy)\n obs_inf = np.isinf(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_inf] = replace_inf\n obs_copy[obs_inf] = replace_inf\n\n warnings.warn(\"Elements(s) {} contained Inf values in the simulated array and \"\n \"elements(s) {} contained Inf values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_inf)[0],\n np.where(obs_inf)[0]),\n UserWarning)\n else:\n inf_indices_fcst = ~(np.isinf(sim_copy))\n inf_indices_obs = ~np.isinf(obs_copy)\n all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)\n\n warnings.warn(\n \"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows \"\n \"are zero indexed).\".format(np.where(~all_inf_indices)[0]),\n UserWarning\n )\n\n # Treat zero data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain zero values\n if remove_zero:\n if (obs_copy == 0).any() or (sim_copy == 0).any():\n zero_indices_fcst = ~(sim_copy == 0)\n zero_indices_obs = ~(obs_copy == 0)\n all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)\n\n warnings.warn(\n \"Row(s) {} contained zero values and the row(s) have been removed (Rows are \"\n \"zero indexed).\".format(np.where(~all_zero_indices)[0]),\n UserWarning\n )\n\n # Treat negative data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain negative values\n\n # Ignore runtime warnings from comparing\n if remove_neg:\n with np.errstate(invalid='ignore'):\n obs_copy_bool = obs_copy < 0\n sim_copy_bool = sim_copy < 0\n\n if obs_copy_bool.any() or sim_copy_bool.any():\n neg_indices_fcst = ~sim_copy_bool\n neg_indices_obs = ~obs_copy_bool\n all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)\n\n warnings.warn(\"Row(s) {} contained negative values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_neg_indices)[0]),\n UserWarning)\n\n obs_copy = obs_copy[all_treatment_array]\n sim_copy = sim_copy[all_treatment_array]\n\n return sim_copy, obs_copy\n"
] | # -*- coding: utf-8 -*-
"""
HydroErr contains a library of goodness of fit metrics that measure hydrologic skill.
Each metric is contained in function, and every function has the parameters to treat missing values as
well as remove zero and negative values from the timeseries data.
Each function contains two properties, name and abbr. These can be used in the Hydrostats package when creating tables
and adding metrics to the plots. Link to the hydrostats package: https://github.com/BYU-Hydroinformatics/Hydrostats.
An example of this functionality is shown below.
>>> import HydroErr as he
>>>
>>> he.acc.name
'Anomaly Correlation Coefficient'
>>> he.acc.abbr
'ACC'
"""
from __future__ import division
import numpy as np
from scipy.stats import gmean, rankdata
import warnings
__all__ = ['me', 'mae', 'mse', 'mle', 'male', 'msle', 'mde', 'mdae', 'mdse', 'ed', 'ned', 'rmse',
'rmsle', 'nrmse_range', 'nrmse_mean', 'nrmse_iqr', 'irmse', 'mase', 'r_squared',
'pearson_r', 'spearman_r', 'acc', 'mape', 'mapd', 'maape', 'smape1', 'smape2', 'd', 'd1',
'dmod', 'drel', 'dr', 'watt_m', 'mb_r', 'nse', 'nse_mod', 'nse_rel', 'kge_2009',
'kge_2012', 'lm_index', 'd1_p', 've', 'sa', 'sc', 'sid', 'sga', 'h1_mhe', 'h1_mahe',
'h1_rmshe', 'h2_mhe', 'h2_mahe', 'h2_rmshe', 'h3_mhe', 'h3_mahe', 'h3_rmshe', 'h4_mhe',
'h4_mahe', 'h4_rmshe', 'h5_mhe', 'h5_mahe', 'h5_rmshe', 'h6_mhe', 'h6_mahe', 'h6_rmshe',
'h7_mhe', 'h7_mahe', 'h7_rmshe', 'h8_mhe', 'h8_mahe', 'h8_rmshe', 'h10_mhe', 'h10_mahe',
'h10_rmshe', 'g_mean_diff', 'mean_var']
####################################################################################################
# General and Hydrological Error Metrics #
####################################################################################################
def me(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean error of the simulated and observed data.
.. image:: /pictures/ME.png
**Range:** -inf < MAE < inf, data units, closer to zero is better, indicates bias.
**Notes:** The mean error (ME) measures the difference between the simulated data and the
observed data. For the mean error, a smaller number indicates a better fit to the original
data. Note that if the error is in the form of random noise, the mean error will be very small,
which can skew the accuracy of this metric. ME is cumulative and will be small even if there
are large positive and negative errors that balance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean error value.
Examples
--------
Note that in this example the random noise cancels, leaving a very small ME.
>>> import HydroErr as he
>>> import numpy as np
>>> # Seed for reproducibility
>>> np.random.seed(54839)
>>> x = np.arange(100) / 20
>>> sim = np.sin(x) + 2
>>> obs = sim * (((np.random.rand(100) - 0.5) / 10) + 1)
>>> he.me(sim, obs)
-0.006832220968967168
References
----------
- Fisher, R.A., 1920. A Mathematical Examination of the Methods of Determining the Accuracy of
an Observation by the Mean Error, and by the Mean Square Error. Monthly Notices of the Royal
Astronomical Society 80 758 - 770.
"""
# Treating missing values
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero)
return np.mean(simulated_array - observed_array)
def mae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute error of the simulated and observed data.
.. image:: /pictures/MAE.png
**Range:** 0 ≤ MAE < inf, data units, smaller is better.
**Notes:** The ME measures the absolute difference between the simulated data and the observed
data. For the mean abolute error, a smaller number indicates a better fit to the original data.
Also note that random errors do not cancel. Also referred to as an L1-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute error value.
References
----------
- Willmott, Cort J., and Kenji Matsuura. “Advantages of the Mean Absolute Error (MAE) over the
Root Mean Square Error (RMSE) in Assessing Average Model Performance.” Climate Research 30,
no. 1 (2005): 79–82.
- Willmott, Cort J., and Kenji Matsuura. “On the Use of Dimensioned Measures of Error to
Evaluate the Performance of Spatial Interpolators.” International Journal of Geographical
Information Science 20, no. 1 (2006): 89–102.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mae(sim, obs)
0.5666666666666665
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean(np.absolute(simulated_array - observed_array))
def mse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared error of the simulated and observed data.
.. image:: /pictures/MSE.png
**Range:** 0 ≤ MSE < inf, data units squared, smaller is better.
**Notes:** Random errors do not cancel, highlights larger errors, also referred to as a
squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mse(sim, obs)
0.4333333333333333
References
----------
- Wang, Zhou, and Alan C. Bovik. “Mean Squared Error: Love It or Leave It? A New Look at Signal
Fidelity Measures.” IEEE Signal Processing Magazine 26, no. 1 (2009): 98–117.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean((simulated_array - observed_array) ** 2)
def mle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean log error of the simulated and observed data.
.. image:: /pictures/MLE.png
**Range:** -inf < MLE < inf, data units, closer to zero is better.
**Notes** Same as the mean erro (ME) only use log ratios as the error term. Limits the impact of outliers, more
evenly weights high and low data values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mle(sim, obs)
0.002961767058151136
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(sim_log - obs_log)
def male(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean absolute log error of the simulated and observed data.
.. image:: /pictures/MALE.png
**Range:** 0 ≤ MALE < inf, data units squared, smaller is better.
**Notes** Same as MAE only use log ratios as the error term. Limits the impact of outliers,
more evenly weights high and low flows.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.male(sim, obs), 6)
0.090417
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(np.abs(sim_log - obs_log))
def msle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared log error of the simulated and observed data.
.. image:: /pictures/MSLE.png
**Range:** 0 ≤ MSLE < inf, data units squared, smaller is better.
**Notes** Same as the mean squared error (MSE) only use log ratios as the error term. Limits
the impact of outliers, more evenly weights high and low values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.msle(sim, obs), 6)
0.010426
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean((sim_log - obs_log) ** 2)
def mde(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median error (MdE) between the simulated and observed data.
.. image:: /pictures/MdE.png
**Range** -inf < MdE < inf, closer to zero is better.
**Notes** This metric indicates bias. It is similar to the mean error (ME), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mde(sim, obs)
-0.10000000000000009
Returns
-------
float
The median error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(simulated_array - observed_array)
def mdae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median absolute error (MdAE) between the simulated and observed data.
.. image:: /pictures/MdAE.png
**Range** 0 ≤ MdAE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean absolute error (MAE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdae(sim, obs)
0.75
Returns
-------
float
The median absolute error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(np.abs(simulated_array - observed_array))
def mdse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median squared error (MdSE) between the simulated and observed data.
.. image:: /pictures/MdSE.png
**Range** 0 ≤ MdSE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean squared error (MSE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdse(sim, obs)
0.625
Returns
-------
float
The median squared error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median((simulated_array - observed_array) ** 2)
def ed(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Euclidean distance between predicted and observed values in vector space.
.. image:: /pictures/ED.png
**Range** 0 ≤ ED < inf, smaller is better.
**Notes** Also sometimes referred to as the L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ed(sim, obs)
1.63707055437449
Returns
-------
float
The euclidean distance error value.
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.linalg.norm(observed_array - simulated_array)
def ned(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the normalized Euclidian distance between the simulated and observed data in vector
space.
.. image:: /pictures/NED.png
**Range** 0 ≤ NED < inf, smaller is better.
**Notes** Also sometimes referred to as the squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The normalized euclidean distance value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ned(sim, obs)
0.2872053604165771
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array / np.mean(observed_array)
b = simulated_array / np.mean(simulated_array)
return np.linalg.norm(a - b)
def rmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square error between the simulated and observed data.
.. image:: /pictures/RMSE.png
**Range** 0 ≤ RMSE < inf, smaller is better.
**Notes:** The standard deviation of the residuals. A lower spread indicates that the points
are better concentrated around the line of best fit (linear). Random errors do not cancel.
This metric will highlights larger errors.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.rmse(sim, obs)
0.668331255192114
References
----------
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.sqrt(np.mean((simulated_array - observed_array) ** 2))
def rmsle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square log error between the simulated and observed data.
.. image:: /pictures/RMSLE.png
**Range:** 0 ≤ RMSLE < inf. Smaller is better, and it does not indicate bias.
**Notes:** Random errors do not cancel while using this metric. This metric limits the
impact of outliers by more evenly weighting high and low values. To calculate the log values,
each value in the observed and simulated array is increased by one unit in order to avoid
run-time errors and nan values (function np.log1p).
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square log error value.
Examples
--------
Notice that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.rmsle(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
"""
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf, remove_neg=remove_neg,
remove_zero=remove_zero)
return np.sqrt(np.mean(np.power(np.log1p(simulated_array) - np.log1p(observed_array), 2)))
def nrmse_range(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the range normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Range.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the range of the observed time series (x).
Normalizing allows comparison between data sets with different scales. The NRMSErange is the
most sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The range normalized root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_range(sim, obs)
0.0891108340256152
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_max = np.max(observed_array)
obs_min = np.min(observed_array)
return rmse_value / (obs_max - obs_min)
def nrmse_mean(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Mean.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the mean of the observed time series (x).
Normalizing allows comparison between data sets with different scales.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_mean(sim, obs)
0.11725109740212526
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_mean = np.mean(observed_array)
return rmse_value / obs_mean
def nrmse_iqr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the IQR normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_IQR.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the interquartile range of the observed time
series (x). Normalizing allows comparison between data sets with different scales.
The NRMSEquartile is the least sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The IQR normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_iqr(sim, obs)
0.2595461185212093
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
q1 = np.percentile(observed_array, 25)
q3 = np.percentile(observed_array, 75)
iqr = q3 - q1
return rmse_value / iqr
def irmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the inertial root mean square error (IRMSE) between the simulated and observed data.
.. image:: /pictures/IRMSE.png
**Range:** 0 ≤ IRMSE < inf, lower is better.
**Notes:** This metric is the RMSE devided by by the standard deviation of the gradient of the
observed timeseries data. This metric is meant to be help understand the ability of the model
to predict changes in observation.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The inertial root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.irmse(sim, obs)
0.14572738134831856
References
----------
- Daga, M., Deo, M.C., 2009. Alternative data-driven methods to estimate wind from waves by
inverse modeling. Natural Hazards 49(2) 293-310.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Getting the gradient of the observed data
obs_len = observed_array.size
obs_grad = observed_array[1:obs_len] - observed_array[0:obs_len - 1]
# Standard deviation of the gradient
obs_grad_std = np.std(obs_grad, ddof=1)
# Divide RMSE by the standard deviation of the gradient of the observed data
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
return rmse_value / obs_grad_std
def mase(simulated_array, observed_array, m=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute scaled error between the simulated and observed data.
.. image:: /pictures/MASE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
m: int
If given, indicates the seasonal period m. If not given, the default is 1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute scaled error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mase(sim, obs)
0.17341040462427745
References
----------
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
start = m
end = simulated_array.size - m
a = np.mean(np.abs(simulated_array - observed_array))
b = np.abs(observed_array[start:observed_array.size] - observed_array[:end])
return a / (np.sum(b) / end)
def pearson_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the pearson correlation coefficient.
.. image:: /pictures/R_pearson.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The pearson r coefficient measures linear correlation. It is sensitive to outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Pearson correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.pearson_r(sim, obs)
0.9610793632835262
References
----------
- Pearson, K. (1895). Note on regression and inheritance in the case of two parents.
Proceedings of the Royal Society of London, 58, 240-242.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
top = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1 = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2 = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
return top / (bot1 * bot2)
def spearman_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the spearman rank correlation coefficient.
.. image:: /pictures/R_spearman.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The spearman r coefficient measures the monotonic relation between simulated and
observed data. Because it uses a nonparametric measure of rank correlation, it is less sensitive
to outliers compared to the Pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spearman rank correlation coefficient.
Examples
----------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.spearman_r(sim, obs)
0.942857142857143
References
----------
- Spearman C (1904). "The proof and measurement of association between two things". American
Journal of Psychology. 15: 72–101. doi:10.2307/1412159
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rank_sim = rankdata(simulated_array)
rank_obs = rankdata(observed_array)
mean_rank_sim = np.mean(rank_sim)
mean_rank_obs = np.mean(rank_obs)
top = np.mean((rank_obs - mean_rank_obs) * (rank_sim - mean_rank_sim))
bot = np.sqrt(
np.mean((rank_obs - mean_rank_obs) ** 2) * np.mean((rank_sim - mean_rank_sim) ** 2))
return top / bot
def r_squared(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Coefficient of Determination (r2).
.. image:: /pictures/r2.png
**Range:** 0 ≤ r2 ≤ 1. 1 indicates perfect correlation, 0 indicates complete randomness.
**Notes:** The Coefficient of Determination measures the linear relation between simulated and
observed data. Because it is the pearson correlation coefficient squared, it is more heavily
affected by outliers than the pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The coefficient of determination (R^2).
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.r_squared(sim, obs)
0.9236735425294681
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array - np.mean(observed_array)
b = simulated_array - np.mean(simulated_array)
return (np.sum(a * b)) ** 2 / (np.sum(a ** 2) * np.sum(b ** 2))
def acc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the anomaly correlation coefficient (ACC).
.. image:: /pictures/ACC.png
**Range:** -1 ≤ ACC ≤ 1. -1 indicates perfect negative correlation of the variation
pattern of the anomalies, 0 indicates complete randomness of the variation patterns of the
anomalies, 1 indicates perfect correlation of the variation pattern of the anomalies.
**Notes:** Common measure in the verification of spatial fields. Measures the correlation
between the variation pattern of the simulated data compared to the observed data.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The anomaly correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.acc(sim, obs)
0.8008994694029383
References
----------
- Langland, Rolf H., and Ryan N. Maue. “Recent Northern Hemisphere Mid-Latitude Medium-Range
Deterministic Forecast Skill.” Tellus A: Dynamic Meteorology and Oceanography 64,
no. 1 (2012): 17531.
- Miyakoda, K., G. D. Hembree, R. F. Strickler, and I. Shulman. “Cumulative Results of Extended
Forecast Experiments I. Model Performance for Winter Cases.” Monthly Weather Review 100, no.
12(1972): 836–55.
- Murphy, Allan H., and Edward S. Epstein. “Skill Scores and Correlation Coefficients in Model
Verification.” Monthly Weather Review 117, no. 3 (1989): 572–82.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - np.mean(simulated_array)
b = observed_array - np.mean(observed_array)
c = np.std(observed_array, ddof=1) * np.std(simulated_array, ddof=1) * simulated_array.size
return np.dot(a, b / c)
def mape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the mean absolute percentage error (MAPE).
.. image:: /pictures/MAPE.png
**Range:** 0% ≤ MAPE ≤ inf. 0% indicates perfect correlation, a larger error indicates a
larger percent error in the data.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
c = 100 / simulated_array.size
return c * np.sum(b)
def mapd(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the mean absolute percentage deviation (MAPD).
.. image:: /pictures/MAPD.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage deviation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mapd(sim, obs)
0.10526315789473682
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(np.abs(observed_array))
return a / b
def maape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the Mean Arctangent Absolute Percentage Error (MAAPE).
.. image:: /pictures/MAAPE.png
**Range:** 0 ≤ MAAPE < π/2, does not indicate bias, smaller is better.
**Notes:** Represents the mean absolute error as a percentage of the observed values. Handles
0s in the observed data. This metric is not as biased as MAPE by under-over predictions.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean arctangent absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
- Kim, S., Kim, H., 2016. A new metric of absolute percentage error for intermittent demand
forecasts. International Journal of Forecasting 32(3) 669-679.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
return np.mean(np.arctan(b))
def smape1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (1) (SMAPE1).
.. image:: /pictures/SMAPE1.png
**Range:** 0 ≤ SMAPE1 < 100%, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (1).
Examples
--------
Note that if we switch the simulated and observed arrays the result is the same
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape1(sim, obs)
5.871915694397428
>>> he.smape1(obs, sim)
5.871915694397428
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 100 / simulated_array.size
b = np.abs(simulated_array - observed_array)
c = np.abs(simulated_array) + np.abs(observed_array)
return a * np.sum(b / c)
def smape2(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (2) (SMAPE2).
.. image:: /pictures/SMAPE2.png
**Range:** 0 ≤ SMAPE1 < 200%, does not indicate bias, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE with only positive metric values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (2).
Examples
--------
Note that switching the simulated and observed arrays yields the same results
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape2(sim, obs)
11.743831388794856
>>> he.smape2(obs, sim)
11.743831388794856
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = (simulated_array + observed_array) / 2
c = 100 / simulated_array.size
return c * np.sum(np.abs(a / b))
def d(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d).
.. image:: /pictures/d.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d(sim, obs)
0.978477353035657
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (observed_array - simulated_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
return 1 - (np.sum(a) / np.sum((b + c) ** 2))
def d1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d1).
.. image:: /pictures/d1.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric. Compared
to the other index of agreement (d) it has a reduced impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (d1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1(sim, obs)
0.8434782608695652
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
obs_mean = np.mean(observed_array)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.abs(simulated_array - obs_mean)
c = np.abs(observed_array - obs_mean)
return 1 - np.sum(a) / np.sum(b + c)
def dr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the refined index of agreement (dr).
.. image:: /pictures/dr.png
**Range:** -1 ≤ dr < 1, does not indicate bias, larger is better.
**Notes:** Reformulation of Willmott’s index of agreement. This metric was created to address
issues in the index of agreement and the Nash-Sutcliffe efficiency metric. Meant to be a
flexible metric for use in climatology.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The refined index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dr(sim, obs)
0.847457627118644
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = 2 * np.sum(np.abs(observed_array - observed_array.mean()))
if a <= b:
return 1 - (a / b)
else:
return (b / a) - 1
def drel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the relative index of agreement (drel).
.. image:: /pictures/drel.png
**Range:** 0 ≤ drel < 1, does not indicate bias, larger is better.
**Notes:** Instead of absolute differences, this metric uses relative differences.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.drel(sim, obs)
0.9740868625579597
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = ((simulated_array - observed_array) / observed_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = ((b + c) / np.mean(observed_array)) ** 2
return 1 - (np.sum(a) / np.sum(e))
def dmod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the modified index of agreement (dmod).
.. image:: /pictures/dmod.png
**Range:** 0 ≤ dmod < 1, does not indicate bias, larger is better.
**Notes:** When j=1, this metric is the same as d1. As j becomes larger, outliers have a larger
impact on the value.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
Optional input indicating the j values desired. A higher j places more emphasis on
outliers. j is 1 by default.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified index of agreement.
Examples
--------
Note that using the default is the same as calculating the d1 metric. Changing the value of j
modification of the metric.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dmod(sim, obs) # Same as d1
0.8434782608695652
>>> he.dmod(sim, obs, j=1.5)
0.9413310986805733
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = (b + c) ** j
return 1 - (np.sum(a) / np.sum(e))
def watt_m(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute Watterson's M (M).
.. image:: /pictures/M.png
**Range:** -1 ≤ M < 1, does not indicate bias, larger is better.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
Watterson's M value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.watt_m(sim, obs)
0.8307913876595929
References
----------
- Watterson, I.G., 1996. Non‐dimensional measures of climate model performance. International
Journal of Climatology 16(4) 379-391.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 2 / np.pi
b = np.mean((simulated_array - observed_array) ** 2) # MSE
c = np.std(observed_array, ddof=1) ** 2 + np.std(simulated_array, ddof=1) ** 2
e = (np.mean(simulated_array) - np.mean(observed_array)) ** 2
f = c + e
return a * np.arcsin(1 - (b / f))
def mb_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute Mielke-Berry R value (MB R).
.. image:: /pictures/MB_R.png
**Range:** 0 ≤ MB R < 1, does not indicate bias, larger is better.
**Notes:** Compares prediction to probability it arose by chance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Mielke-Berry R value.
Notes
-----
If a more optimized version is desired, the `numba package <http://numba.pydata.org/doc.html>`_ can be implemented
for a much more optimized performance when computing this metric. An example is given below.
>>> from numba import njit, prange
>>> @njit(parallel=True, fastmath=True)
>>> def mb_par_fastmath(pred, obs): # uses LLVM compiler
>>> assert pred.size == obs.size
>>> n = pred.size
>>> tot = 0.0
>>> mae = 0.0
>>> for i in range(n):
>>> for j in prange(n):
>>> tot += abs(pred[i] - obs[j])
>>> mae += abs(pred[i] - obs[i])
>>> mae = mae / n
>>> mb = 1 - ((n ** 2) * mae / tot)
>>>
>>> return mb
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mb_r(sim, obs)
0.7726315789473684
References
----------
- Berry, K.J., Mielke, P.W., 1988. A Generalization of Cohen's Kappa Agreement Measure to
Interval Measurement and Multiple Raters. Educational and Psychological Measurement 48(4)
921-933.
- Mielke, P.W., Berry, K.J., 2007. Permutation methods: a distance function approach.
Springer Science & Business Media.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Calculate metric
n = simulated_array.size
tot = 0.0
for i in range(n):
tot = tot + np.sum(np.abs(simulated_array - observed_array[i]))
mae_val = np.sum(np.abs(simulated_array - observed_array)) / n
mb = 1 - ((n ** 2) * mae_val / tot)
return mb
def nse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Nash-Sutcliffe Efficiency.
.. image:: /pictures/NSE.png
**Range:** -inf < NSE < 1, does not indicate bias, larger is better.
**Notes:** The Nash-Sutcliffe efficiency metric compares prediction values to naive predictions
(i.e. average value). One major flaw of this metric is that it punishes a higher variance in
the observed values (denominator). This metric is analogous to the mean absolute error skill
score (MAESS) using the mean flow as a benchmark.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Nash-Sutcliffe Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse(sim, obs)
0.922093023255814
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
- McCuen, R.H., Knight, Z., Cutter, A.G., 2006. Evaluation of the Nash-Sutcliffe Efficiency
Index. Journal of Hydraulic Engineering.
- Nash, J.E., Sutcliffe, J.V., 1970. River flow forecasting through conceptual models part
I — A discussion of principles. Journal of Hydrology 282-290.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** 2
b = (np.abs(observed_array - np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def nse_mod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the modified Nash-Sutcliffe efficiency (NSE mod).
.. image:: /pictures/NSEmod.png
**Range:** -inf < NSE (mod) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
If given, sets the value of j to the input. j is 1 by default. A higher j gives more
emphasis to outliers
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_mod(sim, obs)
0.6949152542372882
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = (np.abs(observed_array - np.mean(observed_array))) ** j
return 1 - (np.sum(a) / np.sum(b))
def nse_rel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the relative Nash-Sutcliffe efficiency (NSE rel).
.. image:: /pictures/NSErel.png
**Range:** -inf < NSE (rel) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_rel(sim, obs)
0.9062004687708474
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs((simulated_array - observed_array) / observed_array)) ** 2
b = (np.abs((observed_array - np.mean(observed_array)) / np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def kge_2009(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""Compute the Kling-Gupta efficiency (2009).
.. image:: /pictures/KGE_2009.png
**Range:** -inf < KGE (2009) < 1, larger is better.
**Notes:** Gupta et al. (2009) created this metric to demonstrate the relative importance of
the three components of the NSE, which are correlation, bias and variability. This was done
with hydrologic modeling as the context. This metric is meant to address issues with the NSE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), Alpha, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, alpha, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2009) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2009(sim, obs)
0.912223072345668
>>> he.kge_2009(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.927910707932087, 1.0058823529411764, 0.9181073779138655)
References
----------
- Gupta, H. V., Kling, H., Yilmaz, K. K., & Martinez, G. F. (2009). Decomposition of the mean
squared error and NSE performance criteria: Implications for improving hydrological modelling.
Journal of Hydrology, 377(1-2), 80-91.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array, ddof=1)
obs_sigma = np.std(observed_array, ddof=1)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
if obs_mean != 0:
beta = sim_mean / obs_mean
else:
beta = np.nan
# Relative variability between simulated and observed values
if obs_sigma != 0:
alpha = sim_sigma / obs_sigma
else:
alpha = np.nan
if not np.isnan(beta) and not np.isnan(alpha):
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (alpha - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Alpha is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, alpha, beta, kge
else:
return kge
def kge_2012(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""
Compute the Kling-Gupta efficiency (2012).
.. image:: /pictures/KGE_2012.png
**Range:** -inf < KGE (2012) < 1, does not indicate bias, larger is better.
**Notes:** The modified version of the KGE (2009). Kling proposed this version to avoid
cross-correlation between bias and variability ratios.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), gamma, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, gamma, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2012) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2012(sim, obs)
0.9122230723456678
>>> he.kge_2012(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.9224843295231272, 1.0058823529411764, 0.9132923608280753)
References
----------
- Kling, H., Fuchs, M., & Paulin, M. (2012). Runoff conditions in the upper Danube basin under
an ensemble of climate change scenarios. Journal of Hydrology, 424, 264-277.
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array)
obs_sigma = np.std(observed_array)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
beta = sim_mean / obs_mean
# CV is the coefficient of variation (standard deviation / mean)
sim_cv = sim_sigma / sim_mean
obs_cv = obs_sigma / obs_mean
# Variability Ratio, or the ratio of simulated CV to observed CV
gam = sim_cv / obs_cv
if obs_mean != 0 and obs_sigma != 0 and sim_mean != 0:
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (gam - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
if sim_mean == 0:
warnings.warn(
'Warning: The simulated data mean is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, gam, beta, kge
else:
return kge
def lm_index(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""
Compute the Legate-McCabe Efficiency Index.
.. image:: /pictures/E1p.png
**Range:** 0 ≤ E1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.lm_index(sim, obs)
0.6949152542372882
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
mean_obs = np.mean(observed_array)
if obs_bar_p is not None:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def d1_p(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""Compute the Legate-McCabe Index of Agreement.
.. image:: /pictures/D1p.png
**Range:** 0 ≤ d1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1_p(sim, obs)
0.8434782608695652
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
if obs_bar_p is not None:
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - obs_bar_p) + np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
mean_obs = np.mean(observed_array)
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - mean_obs) + np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def ve(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Volumetric Efficiency (VE).
.. image:: /pictures/VE.png
**Range:** 0 ≤ VE < 1 smaller is better, does not indicate bias.
**Notes:** Represents the error as a percentage of flow.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Volumetric Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ve(sim, obs)
0.8947368421052632
References
----------
- Criss, R.E., Winston, W.E., 2008. Do Nash values have value? Discussion and alternate
proposals. Hydrological Processes 22(14) 2723.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(observed_array)
return 1 - (a / b)
def sc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Correlation (SC).
.. image:: /pictures/SC.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral correlation metric measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Correlation value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sc(sim, obs)
0.27991341383646606
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(observed_array - np.mean(observed_array), simulated_array - np.mean(simulated_array))
b = np.linalg.norm(observed_array - np.mean(observed_array))
c = np.linalg.norm(simulated_array - np.mean(simulated_array))
e = b * c
return np.arccos(a / e)
def sid(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Information Divergence (SID).
.. image:: /pictures/SID.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral information divergence measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral information divergence value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sid(sim, obs)
0.03517616895318012
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
first = (observed_array / np.mean(observed_array)) - (
simulated_array / np.mean(simulated_array))
second1 = np.log10(observed_array) - np.log10(np.mean(observed_array))
second2 = np.log10(simulated_array) - np.log10(np.mean(simulated_array))
return np.dot(first, second1 - second2)
def sga(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Gradient Angle (SGA).
.. image:: /pictures/SGA.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral gradient angle measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
SG is the gradient of the simulated or observed time series.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Gradient Angle.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sga(sim, obs)
0.26764286472739834
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sgx = observed_array[1:] - observed_array[:observed_array.size - 1]
sgy = simulated_array[1:] - simulated_array[:simulated_array.size - 1]
a = np.dot(sgx, sgy)
b = np.linalg.norm(sgx) * np.linalg.norm(sgy)
return np.arccos(a / b)
####################################################################################################
# H Metrics: Methods from Tornqvist L, Vartia P, and Vartia YO. (1985) #
####################################################################################################
def h1_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the H1 mean error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mhe(sim, obs)
0.002106551840594386
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(h)
def h1_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H1 absolute error.
.. image:: /pictures/H1.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The H1 absolute error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mahe(sim, obs)
0.11639226612630865
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(np.abs(h))
def h1_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H1 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean squared H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_rmshe(sim, obs)
0.12865571253672756
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.sqrt(np.mean(h ** 2))
def h2_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean error.
.. image:: /pictures/H2.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mhe(sim, obs)
-0.015319829424307036
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(h)
def h2_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean absolute error.
.. image:: /pictures/H2.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mahe(sim, obs)
0.11997591408039167
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(np.abs(h))
def h2_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_rmshe(sim, obs)
0.1373586680669673
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.sqrt(np.mean(h ** 2))
def h3_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 mean error.
.. image:: /pictures/H3.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mhe(sim, obs)
-0.006322019630356533
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(h)
def h3_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H3 mean absolute error.
.. image:: /pictures/H3.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mahe(sim, obs)
0.11743831388794855
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(np.abs(h))
def h3_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 root mean square error.
.. image:: /pictures/H3.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.sqrt(np.mean(h ** 2))
def h4_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mhe(sim, obs)
-0.0064637371129817
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(h)
def h4_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H4 mean absolute error.
.. image:: /pictures/H4.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mahe(sim, obs)
0.11781032209144082
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(np.abs(h))
def h4_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_rmshe(sim, obs)
0.13200901963465006
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.sqrt(np.mean(h ** 2))
def h5_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean error.
.. image:: /pictures/H5.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mhe(sim, obs)
-0.006606638791856322
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(h)
def h5_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean absolute error.
.. image:: /pictures/H5.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mahe(sim, obs)
0.11818409010335018
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(np.abs(h))
def h5_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 root mean square error.
.. image:: /pictures/H5.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_rmshe(sim, obs)
0.13254476469410933
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h6_mhe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H6 mean error.
.. image:: /pictures/H6.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mhe(sim, obs)
-0.006322019630356514
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(h)
def h6_mahe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""Compute the H6 mean absolute error.
.. image:: /pictures/H6.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mahe(sim, obs)
0.11743831388794852
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(np.abs(h))
def h6_rmshe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the H6 root mean square error.
.. image:: /pictures/H6.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h7_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean error.
.. image:: /pictures/H7.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mhe(sim, obs)
0.0026331898007430263
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(h)
def h7_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean absolute error.
.. image:: /pictures/H7.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mahe(sim, obs)
0.14549033265788583
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(np.abs(h))
def h7_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 root mean square error.
.. image:: /pictures/H7.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_rmshe(sim, obs)
0.16081964067090945
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
def h8_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H8 mean error.
.. image:: /pictures/H8.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mhe(sim, obs)
0.0018056158633666466
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(h)
def h8_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 mean absolute error.
.. image:: /pictures/H8.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mahe(sim, obs)
0.099764799536836
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(np.abs(h))
def h8_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 root mean square error.
.. image:: /pictures/H8.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_rmshe(sim, obs)
0.11027632503148076
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
# def h9(simulated_array, observed_array, h_type='mhe', k=1):
# h = (simulated_array / observed_array - 1) / \
# np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
# if h_type == 'mhe':
# return h.mean()
# elif h_type == 'ahe':
# return np.abs(h).mean()
# elif h_type == 'rmshe':
# return np.sqrt((h**2).mean())
# else:
# raise RuntimeError("The three types available are 'mhe', 'ahe', and 'rmshe'.")
def h10_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean error.
.. image:: /pictures/H10.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h10_mhe(sim, obs)
-0.0012578676058971154
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(h)
def h10_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean absolute error.
.. image:: /pictures/H10.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_mahe(sim, obs), 6)
0.094636
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(np.abs(h))
def h10_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 root mean square error.
.. image:: /pictures/H10.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_rmshe(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.sqrt(np.mean(h ** 2))
###################################################################################################
# Statistical Error Metrics for Distribution Testing #
###################################################################################################
def g_mean_diff(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the geometric mean difference.
.. image:: /pictures/GMD.png
**Range:**
**Notes:** For the difference of geometric means, the geometric mean is computed for each of
two samples then their difference is taken.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The geometric mean difference value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.g_mean_diff(sim, obs)
0.988855412098022
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.exp(gmean(sim_log) - gmean(obs_log))
def mean_var(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the mean variance.
.. image:: /pictures/MV.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean variance.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.mean_var(sim, obs), 6)
0.010641
References
----------
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.var(np.log1p(observed_array) - np.log1p(simulated_array))
####################################################################################################
# HELPER FUNCTIONS AND API INFORMATION #
####################################################################################################
metric_names = [
'Mean Error', 'Mean Absolute Error', 'Mean Squared Error', 'Mean Log Error',
'Mean Absolute Log Error', 'Mean Squared Log Error', 'Median Error', 'Median Absolute Error',
'Median Squared Error', 'Eclidean Distance', 'Normalized Eclidean Distance',
'Root Mean Square Error', 'Root Mean Squared Log Error',
'Normalized Root Mean Square Error - Range', 'Normalized Root Mean Square Error - Mean',
'Normalized Root Mean Square Error - IQR', 'Inertial Root Mean Square Error',
'Mean Absolute Scaled Error', 'Coefficient of Determination', 'Pearson Correlation Coefficient',
'Spearman Rank Correlation Coefficient', 'Anomaly Correlation Coefficient',
'Mean Absolute Percentage Error', 'Mean Absolute Percentage Deviation',
'Mean Arctangent Absolute Percentage Error', 'Symmetric Mean Absolute Percentage Error (1)',
'Symmetric Mean Absolute Percentage Error (2)', 'Index of Agreement (d)',
'Index of Agreement (d1)', 'Modified Index of Agreement', 'Relative Index of Agreement',
'Index of Agreement Refined (dr)', "Watterson's M", 'Mielke-Berry R',
'Nash-Sutcliffe Efficiency', 'Modified Nash-Sutcliffe Efficiency',
'Relative Nash-Sutcliffe Efficiency', 'Kling-Gupta Efficiency (2009)',
'Kling-Gupta Efficiency (2012)', 'Legate-McCabe Efficiency Index',
'Legate-McCabe Index of Agreement', 'Volumetric Efficiency', 'Spectral Angle',
'Spectral Correlation', 'Spectral Information Divergence', 'Spectral Gradient Angle',
'Mean H1 Error', 'Mean Absolute H1 Error', 'Root Mean Square H1 Error', 'Mean H2 Error',
'Mean Absolute H2 Error', 'Root Mean Square H2 Error', 'Mean H3 Error',
'Mean Absolute H3 Error', 'Root Mean Square H3 Error', 'Mean H4 Error',
'Mean Absolute H4 Error', 'Root Mean Square H4 Error', 'Mean H5 Error',
'Mean Absolute H5 Error', 'Root Mean Square H5 Error', 'Mean H6 Error',
'Mean Absolute H6 Error', 'Root Mean Square H6 Error', 'Mean H7 Error',
'Mean Absolute H7 Error', 'Root Mean Square H7 Error', 'Mean H8 Error',
'Mean Absolute H8 Error', 'Root Mean Square H8 Error', 'Mean H10 Error',
'Mean Absolute H10 Error', 'Root Mean Square H10 Error', 'Geometric Mean Difference',
'Mean Variance'
]
metric_abbr = [
'ME', 'MAE', 'MSE', 'MLE', 'MALE', 'MSLE', 'MdE', 'MdAE', 'MdSE', 'ED', 'NED', 'RMSE', 'RMSLE',
'NRMSE (Range)', 'NRMSE (Mean)', 'NRMSE (IQR)', 'IRMSE', 'MASE', 'r2', 'R (Pearson)',
'R (Spearman)', 'ACC', 'MAPE', 'MAPD', 'MAAPE', 'SMAPE1', 'SMAPE2', 'd', 'd1', 'd (Mod.)',
'd (Rel.)', 'dr', 'M', '(MB) R', 'NSE', 'NSE (Mod.)', 'NSE (Rel.)', 'KGE (2009)', 'KGE (2012)',
"E1'", "D1'", 'VE', 'SA', 'SC', 'SID', 'SGA', 'H1 (MHE)', 'H1 (MAHE)', 'H1 (RMSHE)', 'H2 (MHE)',
'H2 (MAHE)', 'H2 (RMSHE)', 'H3 (MHE)', 'H3 (MAHE)', 'H3 (RMSHE)', 'H4 (MHE)', 'H4 (MAHE)',
'H4 (RMSHE)', 'H5 (MHE)', 'H5 (MAHE)', 'H5 (RMSHE)', 'H6 (MHE)', 'H6 (MAHE)', 'H6 (RMSHE)',
'H7 (MHE)', 'H7 (MAHE)', 'H7 (RMSHE)', 'H8 (MHE)', 'H8 (MAHE)', 'H8 (RMSHE)', 'H10 (MHE)',
'H10 (MAHE)', 'H10 (RMSHE)', 'GMD', 'MV'
]
function_list = [
me, mae, mse, mle, male, msle, mde, mdae, mdse, ed, ned, rmse, rmsle, nrmse_range, nrmse_mean,
nrmse_iqr, irmse, mase, r_squared, pearson_r, spearman_r, acc, mape, mapd, maape, smape1,
smape2, d, d1, dmod, drel, dr, watt_m, mb_r, nse, nse_mod, nse_rel, kge_2009, kge_2012,
lm_index, d1_p, ve, sa, sc, sid, sga, h1_mhe, h1_mahe, h1_rmshe, h2_mhe, h2_mahe, h2_rmshe,
h3_mhe, h3_mahe, h3_rmshe, h4_mhe, h4_mahe, h4_rmshe, h5_mhe, h5_mahe, h5_rmshe, h6_mhe,
h6_mahe, h6_rmshe, h7_mhe, h7_mahe, h7_rmshe, h8_mhe, h8_mahe, h8_rmshe, h10_mhe, h10_mahe,
h10_rmshe, g_mean_diff, mean_var,
]
# Assign some properties to each function for ease of use for users
for i in range(len(function_list)):
function_list[i].name = metric_names[i]
function_list[i].abbr = metric_abbr[i]
def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Removes the nan, negative, and inf values in two numpy arrays"""
sim_copy = np.copy(simulated_array)
obs_copy = np.copy(observed_array)
# Checking to see if the vectors are the same length
assert sim_copy.ndim == 1, "The simulated array is not one dimensional."
assert obs_copy.ndim == 1, "The observed array is not one dimensional."
if sim_copy.size != obs_copy.size:
raise RuntimeError("The two ndarrays are not the same size.")
# Treat missing data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain nan values
all_treatment_array = np.ones(obs_copy.size, dtype=bool)
if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_nan = np.isnan(sim_copy)
obs_nan = np.isnan(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_nan] = replace_nan
obs_copy[obs_nan] = replace_nan
warnings.warn("Elements(s) {} contained NaN values in the simulated array and "
"elements(s) {} contained NaN values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_nan)[0],
np.where(obs_nan)[0]),
UserWarning)
else:
# Getting the indices of the nan values, combining them, and informing user.
nan_indices_fcst = ~np.isnan(sim_copy)
nan_indices_obs = ~np.isnan(obs_copy)
all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)
warnings.warn("Row(s) {} contained NaN values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_nan_indices)[0]),
UserWarning)
if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_inf = np.isinf(sim_copy)
obs_inf = np.isinf(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_inf] = replace_inf
obs_copy[obs_inf] = replace_inf
warnings.warn("Elements(s) {} contained Inf values in the simulated array and "
"elements(s) {} contained Inf values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_inf)[0],
np.where(obs_inf)[0]),
UserWarning)
else:
inf_indices_fcst = ~(np.isinf(sim_copy))
inf_indices_obs = ~np.isinf(obs_copy)
all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)
warnings.warn(
"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows "
"are zero indexed).".format(np.where(~all_inf_indices)[0]),
UserWarning
)
# Treat zero data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain zero values
if remove_zero:
if (obs_copy == 0).any() or (sim_copy == 0).any():
zero_indices_fcst = ~(sim_copy == 0)
zero_indices_obs = ~(obs_copy == 0)
all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)
warnings.warn(
"Row(s) {} contained zero values and the row(s) have been removed (Rows are "
"zero indexed).".format(np.where(~all_zero_indices)[0]),
UserWarning
)
# Treat negative data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain negative values
# Ignore runtime warnings from comparing
if remove_neg:
with np.errstate(invalid='ignore'):
obs_copy_bool = obs_copy < 0
sim_copy_bool = sim_copy < 0
if obs_copy_bool.any() or sim_copy_bool.any():
neg_indices_fcst = ~sim_copy_bool
neg_indices_obs = ~obs_copy_bool
all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)
warnings.warn("Row(s) {} contained negative values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_neg_indices)[0]),
UserWarning)
obs_copy = obs_copy[all_treatment_array]
sim_copy = sim_copy[all_treatment_array]
return sim_copy, obs_copy
if __name__ == "__main__":
pass
|
BYU-Hydroinformatics/HydroErr | HydroErr/HydroErr.py | sc | python | def sc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(observed_array - np.mean(observed_array), simulated_array - np.mean(simulated_array))
b = np.linalg.norm(observed_array - np.mean(observed_array))
c = np.linalg.norm(simulated_array - np.mean(simulated_array))
e = b * c
return np.arccos(a / e) | Compute the Spectral Correlation (SC).
.. image:: /pictures/SC.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral correlation metric measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Correlation value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sc(sim, obs)
0.27991341383646606
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166. | train | https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L3615-L3691 | [
"def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,\n remove_neg=False, remove_zero=False):\n \"\"\"Removes the nan, negative, and inf values in two numpy arrays\"\"\"\n sim_copy = np.copy(simulated_array)\n obs_copy = np.copy(observed_array)\n\n # Checking to see if the vectors are the same length\n assert sim_copy.ndim == 1, \"The simulated array is not one dimensional.\"\n assert obs_copy.ndim == 1, \"The observed array is not one dimensional.\"\n\n if sim_copy.size != obs_copy.size:\n raise RuntimeError(\"The two ndarrays are not the same size.\")\n\n # Treat missing data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain nan values\n all_treatment_array = np.ones(obs_copy.size, dtype=bool)\n\n if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_nan = np.isnan(sim_copy)\n obs_nan = np.isnan(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_nan] = replace_nan\n obs_copy[obs_nan] = replace_nan\n\n warnings.warn(\"Elements(s) {} contained NaN values in the simulated array and \"\n \"elements(s) {} contained NaN values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_nan)[0],\n np.where(obs_nan)[0]),\n UserWarning)\n else:\n # Getting the indices of the nan values, combining them, and informing user.\n nan_indices_fcst = ~np.isnan(sim_copy)\n nan_indices_obs = ~np.isnan(obs_copy)\n all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)\n\n warnings.warn(\"Row(s) {} contained NaN values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_nan_indices)[0]),\n UserWarning)\n\n if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_inf = np.isinf(sim_copy)\n obs_inf = np.isinf(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_inf] = replace_inf\n obs_copy[obs_inf] = replace_inf\n\n warnings.warn(\"Elements(s) {} contained Inf values in the simulated array and \"\n \"elements(s) {} contained Inf values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_inf)[0],\n np.where(obs_inf)[0]),\n UserWarning)\n else:\n inf_indices_fcst = ~(np.isinf(sim_copy))\n inf_indices_obs = ~np.isinf(obs_copy)\n all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)\n\n warnings.warn(\n \"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows \"\n \"are zero indexed).\".format(np.where(~all_inf_indices)[0]),\n UserWarning\n )\n\n # Treat zero data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain zero values\n if remove_zero:\n if (obs_copy == 0).any() or (sim_copy == 0).any():\n zero_indices_fcst = ~(sim_copy == 0)\n zero_indices_obs = ~(obs_copy == 0)\n all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)\n\n warnings.warn(\n \"Row(s) {} contained zero values and the row(s) have been removed (Rows are \"\n \"zero indexed).\".format(np.where(~all_zero_indices)[0]),\n UserWarning\n )\n\n # Treat negative data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain negative values\n\n # Ignore runtime warnings from comparing\n if remove_neg:\n with np.errstate(invalid='ignore'):\n obs_copy_bool = obs_copy < 0\n sim_copy_bool = sim_copy < 0\n\n if obs_copy_bool.any() or sim_copy_bool.any():\n neg_indices_fcst = ~sim_copy_bool\n neg_indices_obs = ~obs_copy_bool\n all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)\n\n warnings.warn(\"Row(s) {} contained negative values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_neg_indices)[0]),\n UserWarning)\n\n obs_copy = obs_copy[all_treatment_array]\n sim_copy = sim_copy[all_treatment_array]\n\n return sim_copy, obs_copy\n"
] | # -*- coding: utf-8 -*-
"""
HydroErr contains a library of goodness of fit metrics that measure hydrologic skill.
Each metric is contained in function, and every function has the parameters to treat missing values as
well as remove zero and negative values from the timeseries data.
Each function contains two properties, name and abbr. These can be used in the Hydrostats package when creating tables
and adding metrics to the plots. Link to the hydrostats package: https://github.com/BYU-Hydroinformatics/Hydrostats.
An example of this functionality is shown below.
>>> import HydroErr as he
>>>
>>> he.acc.name
'Anomaly Correlation Coefficient'
>>> he.acc.abbr
'ACC'
"""
from __future__ import division
import numpy as np
from scipy.stats import gmean, rankdata
import warnings
__all__ = ['me', 'mae', 'mse', 'mle', 'male', 'msle', 'mde', 'mdae', 'mdse', 'ed', 'ned', 'rmse',
'rmsle', 'nrmse_range', 'nrmse_mean', 'nrmse_iqr', 'irmse', 'mase', 'r_squared',
'pearson_r', 'spearman_r', 'acc', 'mape', 'mapd', 'maape', 'smape1', 'smape2', 'd', 'd1',
'dmod', 'drel', 'dr', 'watt_m', 'mb_r', 'nse', 'nse_mod', 'nse_rel', 'kge_2009',
'kge_2012', 'lm_index', 'd1_p', 've', 'sa', 'sc', 'sid', 'sga', 'h1_mhe', 'h1_mahe',
'h1_rmshe', 'h2_mhe', 'h2_mahe', 'h2_rmshe', 'h3_mhe', 'h3_mahe', 'h3_rmshe', 'h4_mhe',
'h4_mahe', 'h4_rmshe', 'h5_mhe', 'h5_mahe', 'h5_rmshe', 'h6_mhe', 'h6_mahe', 'h6_rmshe',
'h7_mhe', 'h7_mahe', 'h7_rmshe', 'h8_mhe', 'h8_mahe', 'h8_rmshe', 'h10_mhe', 'h10_mahe',
'h10_rmshe', 'g_mean_diff', 'mean_var']
####################################################################################################
# General and Hydrological Error Metrics #
####################################################################################################
def me(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean error of the simulated and observed data.
.. image:: /pictures/ME.png
**Range:** -inf < MAE < inf, data units, closer to zero is better, indicates bias.
**Notes:** The mean error (ME) measures the difference between the simulated data and the
observed data. For the mean error, a smaller number indicates a better fit to the original
data. Note that if the error is in the form of random noise, the mean error will be very small,
which can skew the accuracy of this metric. ME is cumulative and will be small even if there
are large positive and negative errors that balance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean error value.
Examples
--------
Note that in this example the random noise cancels, leaving a very small ME.
>>> import HydroErr as he
>>> import numpy as np
>>> # Seed for reproducibility
>>> np.random.seed(54839)
>>> x = np.arange(100) / 20
>>> sim = np.sin(x) + 2
>>> obs = sim * (((np.random.rand(100) - 0.5) / 10) + 1)
>>> he.me(sim, obs)
-0.006832220968967168
References
----------
- Fisher, R.A., 1920. A Mathematical Examination of the Methods of Determining the Accuracy of
an Observation by the Mean Error, and by the Mean Square Error. Monthly Notices of the Royal
Astronomical Society 80 758 - 770.
"""
# Treating missing values
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero)
return np.mean(simulated_array - observed_array)
def mae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute error of the simulated and observed data.
.. image:: /pictures/MAE.png
**Range:** 0 ≤ MAE < inf, data units, smaller is better.
**Notes:** The ME measures the absolute difference between the simulated data and the observed
data. For the mean abolute error, a smaller number indicates a better fit to the original data.
Also note that random errors do not cancel. Also referred to as an L1-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute error value.
References
----------
- Willmott, Cort J., and Kenji Matsuura. “Advantages of the Mean Absolute Error (MAE) over the
Root Mean Square Error (RMSE) in Assessing Average Model Performance.” Climate Research 30,
no. 1 (2005): 79–82.
- Willmott, Cort J., and Kenji Matsuura. “On the Use of Dimensioned Measures of Error to
Evaluate the Performance of Spatial Interpolators.” International Journal of Geographical
Information Science 20, no. 1 (2006): 89–102.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mae(sim, obs)
0.5666666666666665
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean(np.absolute(simulated_array - observed_array))
def mse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared error of the simulated and observed data.
.. image:: /pictures/MSE.png
**Range:** 0 ≤ MSE < inf, data units squared, smaller is better.
**Notes:** Random errors do not cancel, highlights larger errors, also referred to as a
squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mse(sim, obs)
0.4333333333333333
References
----------
- Wang, Zhou, and Alan C. Bovik. “Mean Squared Error: Love It or Leave It? A New Look at Signal
Fidelity Measures.” IEEE Signal Processing Magazine 26, no. 1 (2009): 98–117.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean((simulated_array - observed_array) ** 2)
def mle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean log error of the simulated and observed data.
.. image:: /pictures/MLE.png
**Range:** -inf < MLE < inf, data units, closer to zero is better.
**Notes** Same as the mean erro (ME) only use log ratios as the error term. Limits the impact of outliers, more
evenly weights high and low data values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mle(sim, obs)
0.002961767058151136
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(sim_log - obs_log)
def male(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean absolute log error of the simulated and observed data.
.. image:: /pictures/MALE.png
**Range:** 0 ≤ MALE < inf, data units squared, smaller is better.
**Notes** Same as MAE only use log ratios as the error term. Limits the impact of outliers,
more evenly weights high and low flows.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.male(sim, obs), 6)
0.090417
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(np.abs(sim_log - obs_log))
def msle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared log error of the simulated and observed data.
.. image:: /pictures/MSLE.png
**Range:** 0 ≤ MSLE < inf, data units squared, smaller is better.
**Notes** Same as the mean squared error (MSE) only use log ratios as the error term. Limits
the impact of outliers, more evenly weights high and low values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.msle(sim, obs), 6)
0.010426
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean((sim_log - obs_log) ** 2)
def mde(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median error (MdE) between the simulated and observed data.
.. image:: /pictures/MdE.png
**Range** -inf < MdE < inf, closer to zero is better.
**Notes** This metric indicates bias. It is similar to the mean error (ME), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mde(sim, obs)
-0.10000000000000009
Returns
-------
float
The median error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(simulated_array - observed_array)
def mdae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median absolute error (MdAE) between the simulated and observed data.
.. image:: /pictures/MdAE.png
**Range** 0 ≤ MdAE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean absolute error (MAE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdae(sim, obs)
0.75
Returns
-------
float
The median absolute error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(np.abs(simulated_array - observed_array))
def mdse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median squared error (MdSE) between the simulated and observed data.
.. image:: /pictures/MdSE.png
**Range** 0 ≤ MdSE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean squared error (MSE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdse(sim, obs)
0.625
Returns
-------
float
The median squared error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median((simulated_array - observed_array) ** 2)
def ed(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Euclidean distance between predicted and observed values in vector space.
.. image:: /pictures/ED.png
**Range** 0 ≤ ED < inf, smaller is better.
**Notes** Also sometimes referred to as the L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ed(sim, obs)
1.63707055437449
Returns
-------
float
The euclidean distance error value.
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.linalg.norm(observed_array - simulated_array)
def ned(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the normalized Euclidian distance between the simulated and observed data in vector
space.
.. image:: /pictures/NED.png
**Range** 0 ≤ NED < inf, smaller is better.
**Notes** Also sometimes referred to as the squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The normalized euclidean distance value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ned(sim, obs)
0.2872053604165771
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array / np.mean(observed_array)
b = simulated_array / np.mean(simulated_array)
return np.linalg.norm(a - b)
def rmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square error between the simulated and observed data.
.. image:: /pictures/RMSE.png
**Range** 0 ≤ RMSE < inf, smaller is better.
**Notes:** The standard deviation of the residuals. A lower spread indicates that the points
are better concentrated around the line of best fit (linear). Random errors do not cancel.
This metric will highlights larger errors.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.rmse(sim, obs)
0.668331255192114
References
----------
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.sqrt(np.mean((simulated_array - observed_array) ** 2))
def rmsle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square log error between the simulated and observed data.
.. image:: /pictures/RMSLE.png
**Range:** 0 ≤ RMSLE < inf. Smaller is better, and it does not indicate bias.
**Notes:** Random errors do not cancel while using this metric. This metric limits the
impact of outliers by more evenly weighting high and low values. To calculate the log values,
each value in the observed and simulated array is increased by one unit in order to avoid
run-time errors and nan values (function np.log1p).
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square log error value.
Examples
--------
Notice that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.rmsle(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
"""
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf, remove_neg=remove_neg,
remove_zero=remove_zero)
return np.sqrt(np.mean(np.power(np.log1p(simulated_array) - np.log1p(observed_array), 2)))
def nrmse_range(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the range normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Range.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the range of the observed time series (x).
Normalizing allows comparison between data sets with different scales. The NRMSErange is the
most sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The range normalized root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_range(sim, obs)
0.0891108340256152
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_max = np.max(observed_array)
obs_min = np.min(observed_array)
return rmse_value / (obs_max - obs_min)
def nrmse_mean(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Mean.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the mean of the observed time series (x).
Normalizing allows comparison between data sets with different scales.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_mean(sim, obs)
0.11725109740212526
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_mean = np.mean(observed_array)
return rmse_value / obs_mean
def nrmse_iqr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the IQR normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_IQR.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the interquartile range of the observed time
series (x). Normalizing allows comparison between data sets with different scales.
The NRMSEquartile is the least sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The IQR normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_iqr(sim, obs)
0.2595461185212093
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
q1 = np.percentile(observed_array, 25)
q3 = np.percentile(observed_array, 75)
iqr = q3 - q1
return rmse_value / iqr
def irmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the inertial root mean square error (IRMSE) between the simulated and observed data.
.. image:: /pictures/IRMSE.png
**Range:** 0 ≤ IRMSE < inf, lower is better.
**Notes:** This metric is the RMSE devided by by the standard deviation of the gradient of the
observed timeseries data. This metric is meant to be help understand the ability of the model
to predict changes in observation.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The inertial root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.irmse(sim, obs)
0.14572738134831856
References
----------
- Daga, M., Deo, M.C., 2009. Alternative data-driven methods to estimate wind from waves by
inverse modeling. Natural Hazards 49(2) 293-310.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Getting the gradient of the observed data
obs_len = observed_array.size
obs_grad = observed_array[1:obs_len] - observed_array[0:obs_len - 1]
# Standard deviation of the gradient
obs_grad_std = np.std(obs_grad, ddof=1)
# Divide RMSE by the standard deviation of the gradient of the observed data
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
return rmse_value / obs_grad_std
def mase(simulated_array, observed_array, m=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute scaled error between the simulated and observed data.
.. image:: /pictures/MASE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
m: int
If given, indicates the seasonal period m. If not given, the default is 1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute scaled error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mase(sim, obs)
0.17341040462427745
References
----------
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
start = m
end = simulated_array.size - m
a = np.mean(np.abs(simulated_array - observed_array))
b = np.abs(observed_array[start:observed_array.size] - observed_array[:end])
return a / (np.sum(b) / end)
def pearson_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the pearson correlation coefficient.
.. image:: /pictures/R_pearson.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The pearson r coefficient measures linear correlation. It is sensitive to outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Pearson correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.pearson_r(sim, obs)
0.9610793632835262
References
----------
- Pearson, K. (1895). Note on regression and inheritance in the case of two parents.
Proceedings of the Royal Society of London, 58, 240-242.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
top = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1 = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2 = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
return top / (bot1 * bot2)
def spearman_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the spearman rank correlation coefficient.
.. image:: /pictures/R_spearman.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The spearman r coefficient measures the monotonic relation between simulated and
observed data. Because it uses a nonparametric measure of rank correlation, it is less sensitive
to outliers compared to the Pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spearman rank correlation coefficient.
Examples
----------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.spearman_r(sim, obs)
0.942857142857143
References
----------
- Spearman C (1904). "The proof and measurement of association between two things". American
Journal of Psychology. 15: 72–101. doi:10.2307/1412159
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rank_sim = rankdata(simulated_array)
rank_obs = rankdata(observed_array)
mean_rank_sim = np.mean(rank_sim)
mean_rank_obs = np.mean(rank_obs)
top = np.mean((rank_obs - mean_rank_obs) * (rank_sim - mean_rank_sim))
bot = np.sqrt(
np.mean((rank_obs - mean_rank_obs) ** 2) * np.mean((rank_sim - mean_rank_sim) ** 2))
return top / bot
def r_squared(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Coefficient of Determination (r2).
.. image:: /pictures/r2.png
**Range:** 0 ≤ r2 ≤ 1. 1 indicates perfect correlation, 0 indicates complete randomness.
**Notes:** The Coefficient of Determination measures the linear relation between simulated and
observed data. Because it is the pearson correlation coefficient squared, it is more heavily
affected by outliers than the pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The coefficient of determination (R^2).
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.r_squared(sim, obs)
0.9236735425294681
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array - np.mean(observed_array)
b = simulated_array - np.mean(simulated_array)
return (np.sum(a * b)) ** 2 / (np.sum(a ** 2) * np.sum(b ** 2))
def acc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the anomaly correlation coefficient (ACC).
.. image:: /pictures/ACC.png
**Range:** -1 ≤ ACC ≤ 1. -1 indicates perfect negative correlation of the variation
pattern of the anomalies, 0 indicates complete randomness of the variation patterns of the
anomalies, 1 indicates perfect correlation of the variation pattern of the anomalies.
**Notes:** Common measure in the verification of spatial fields. Measures the correlation
between the variation pattern of the simulated data compared to the observed data.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The anomaly correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.acc(sim, obs)
0.8008994694029383
References
----------
- Langland, Rolf H., and Ryan N. Maue. “Recent Northern Hemisphere Mid-Latitude Medium-Range
Deterministic Forecast Skill.” Tellus A: Dynamic Meteorology and Oceanography 64,
no. 1 (2012): 17531.
- Miyakoda, K., G. D. Hembree, R. F. Strickler, and I. Shulman. “Cumulative Results of Extended
Forecast Experiments I. Model Performance for Winter Cases.” Monthly Weather Review 100, no.
12(1972): 836–55.
- Murphy, Allan H., and Edward S. Epstein. “Skill Scores and Correlation Coefficients in Model
Verification.” Monthly Weather Review 117, no. 3 (1989): 572–82.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - np.mean(simulated_array)
b = observed_array - np.mean(observed_array)
c = np.std(observed_array, ddof=1) * np.std(simulated_array, ddof=1) * simulated_array.size
return np.dot(a, b / c)
def mape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the mean absolute percentage error (MAPE).
.. image:: /pictures/MAPE.png
**Range:** 0% ≤ MAPE ≤ inf. 0% indicates perfect correlation, a larger error indicates a
larger percent error in the data.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
c = 100 / simulated_array.size
return c * np.sum(b)
def mapd(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the mean absolute percentage deviation (MAPD).
.. image:: /pictures/MAPD.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage deviation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mapd(sim, obs)
0.10526315789473682
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(np.abs(observed_array))
return a / b
def maape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the Mean Arctangent Absolute Percentage Error (MAAPE).
.. image:: /pictures/MAAPE.png
**Range:** 0 ≤ MAAPE < π/2, does not indicate bias, smaller is better.
**Notes:** Represents the mean absolute error as a percentage of the observed values. Handles
0s in the observed data. This metric is not as biased as MAPE by under-over predictions.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean arctangent absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
- Kim, S., Kim, H., 2016. A new metric of absolute percentage error for intermittent demand
forecasts. International Journal of Forecasting 32(3) 669-679.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
return np.mean(np.arctan(b))
def smape1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (1) (SMAPE1).
.. image:: /pictures/SMAPE1.png
**Range:** 0 ≤ SMAPE1 < 100%, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (1).
Examples
--------
Note that if we switch the simulated and observed arrays the result is the same
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape1(sim, obs)
5.871915694397428
>>> he.smape1(obs, sim)
5.871915694397428
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 100 / simulated_array.size
b = np.abs(simulated_array - observed_array)
c = np.abs(simulated_array) + np.abs(observed_array)
return a * np.sum(b / c)
def smape2(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (2) (SMAPE2).
.. image:: /pictures/SMAPE2.png
**Range:** 0 ≤ SMAPE1 < 200%, does not indicate bias, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE with only positive metric values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (2).
Examples
--------
Note that switching the simulated and observed arrays yields the same results
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape2(sim, obs)
11.743831388794856
>>> he.smape2(obs, sim)
11.743831388794856
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = (simulated_array + observed_array) / 2
c = 100 / simulated_array.size
return c * np.sum(np.abs(a / b))
def d(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d).
.. image:: /pictures/d.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d(sim, obs)
0.978477353035657
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (observed_array - simulated_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
return 1 - (np.sum(a) / np.sum((b + c) ** 2))
def d1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d1).
.. image:: /pictures/d1.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric. Compared
to the other index of agreement (d) it has a reduced impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (d1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1(sim, obs)
0.8434782608695652
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
obs_mean = np.mean(observed_array)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.abs(simulated_array - obs_mean)
c = np.abs(observed_array - obs_mean)
return 1 - np.sum(a) / np.sum(b + c)
def dr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the refined index of agreement (dr).
.. image:: /pictures/dr.png
**Range:** -1 ≤ dr < 1, does not indicate bias, larger is better.
**Notes:** Reformulation of Willmott’s index of agreement. This metric was created to address
issues in the index of agreement and the Nash-Sutcliffe efficiency metric. Meant to be a
flexible metric for use in climatology.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The refined index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dr(sim, obs)
0.847457627118644
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = 2 * np.sum(np.abs(observed_array - observed_array.mean()))
if a <= b:
return 1 - (a / b)
else:
return (b / a) - 1
def drel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the relative index of agreement (drel).
.. image:: /pictures/drel.png
**Range:** 0 ≤ drel < 1, does not indicate bias, larger is better.
**Notes:** Instead of absolute differences, this metric uses relative differences.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.drel(sim, obs)
0.9740868625579597
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = ((simulated_array - observed_array) / observed_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = ((b + c) / np.mean(observed_array)) ** 2
return 1 - (np.sum(a) / np.sum(e))
def dmod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the modified index of agreement (dmod).
.. image:: /pictures/dmod.png
**Range:** 0 ≤ dmod < 1, does not indicate bias, larger is better.
**Notes:** When j=1, this metric is the same as d1. As j becomes larger, outliers have a larger
impact on the value.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
Optional input indicating the j values desired. A higher j places more emphasis on
outliers. j is 1 by default.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified index of agreement.
Examples
--------
Note that using the default is the same as calculating the d1 metric. Changing the value of j
modification of the metric.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dmod(sim, obs) # Same as d1
0.8434782608695652
>>> he.dmod(sim, obs, j=1.5)
0.9413310986805733
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = (b + c) ** j
return 1 - (np.sum(a) / np.sum(e))
def watt_m(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute Watterson's M (M).
.. image:: /pictures/M.png
**Range:** -1 ≤ M < 1, does not indicate bias, larger is better.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
Watterson's M value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.watt_m(sim, obs)
0.8307913876595929
References
----------
- Watterson, I.G., 1996. Non‐dimensional measures of climate model performance. International
Journal of Climatology 16(4) 379-391.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 2 / np.pi
b = np.mean((simulated_array - observed_array) ** 2) # MSE
c = np.std(observed_array, ddof=1) ** 2 + np.std(simulated_array, ddof=1) ** 2
e = (np.mean(simulated_array) - np.mean(observed_array)) ** 2
f = c + e
return a * np.arcsin(1 - (b / f))
def mb_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute Mielke-Berry R value (MB R).
.. image:: /pictures/MB_R.png
**Range:** 0 ≤ MB R < 1, does not indicate bias, larger is better.
**Notes:** Compares prediction to probability it arose by chance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Mielke-Berry R value.
Notes
-----
If a more optimized version is desired, the `numba package <http://numba.pydata.org/doc.html>`_ can be implemented
for a much more optimized performance when computing this metric. An example is given below.
>>> from numba import njit, prange
>>> @njit(parallel=True, fastmath=True)
>>> def mb_par_fastmath(pred, obs): # uses LLVM compiler
>>> assert pred.size == obs.size
>>> n = pred.size
>>> tot = 0.0
>>> mae = 0.0
>>> for i in range(n):
>>> for j in prange(n):
>>> tot += abs(pred[i] - obs[j])
>>> mae += abs(pred[i] - obs[i])
>>> mae = mae / n
>>> mb = 1 - ((n ** 2) * mae / tot)
>>>
>>> return mb
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mb_r(sim, obs)
0.7726315789473684
References
----------
- Berry, K.J., Mielke, P.W., 1988. A Generalization of Cohen's Kappa Agreement Measure to
Interval Measurement and Multiple Raters. Educational and Psychological Measurement 48(4)
921-933.
- Mielke, P.W., Berry, K.J., 2007. Permutation methods: a distance function approach.
Springer Science & Business Media.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Calculate metric
n = simulated_array.size
tot = 0.0
for i in range(n):
tot = tot + np.sum(np.abs(simulated_array - observed_array[i]))
mae_val = np.sum(np.abs(simulated_array - observed_array)) / n
mb = 1 - ((n ** 2) * mae_val / tot)
return mb
def nse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Nash-Sutcliffe Efficiency.
.. image:: /pictures/NSE.png
**Range:** -inf < NSE < 1, does not indicate bias, larger is better.
**Notes:** The Nash-Sutcliffe efficiency metric compares prediction values to naive predictions
(i.e. average value). One major flaw of this metric is that it punishes a higher variance in
the observed values (denominator). This metric is analogous to the mean absolute error skill
score (MAESS) using the mean flow as a benchmark.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Nash-Sutcliffe Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse(sim, obs)
0.922093023255814
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
- McCuen, R.H., Knight, Z., Cutter, A.G., 2006. Evaluation of the Nash-Sutcliffe Efficiency
Index. Journal of Hydraulic Engineering.
- Nash, J.E., Sutcliffe, J.V., 1970. River flow forecasting through conceptual models part
I — A discussion of principles. Journal of Hydrology 282-290.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** 2
b = (np.abs(observed_array - np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def nse_mod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the modified Nash-Sutcliffe efficiency (NSE mod).
.. image:: /pictures/NSEmod.png
**Range:** -inf < NSE (mod) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
If given, sets the value of j to the input. j is 1 by default. A higher j gives more
emphasis to outliers
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_mod(sim, obs)
0.6949152542372882
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = (np.abs(observed_array - np.mean(observed_array))) ** j
return 1 - (np.sum(a) / np.sum(b))
def nse_rel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the relative Nash-Sutcliffe efficiency (NSE rel).
.. image:: /pictures/NSErel.png
**Range:** -inf < NSE (rel) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_rel(sim, obs)
0.9062004687708474
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs((simulated_array - observed_array) / observed_array)) ** 2
b = (np.abs((observed_array - np.mean(observed_array)) / np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def kge_2009(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""Compute the Kling-Gupta efficiency (2009).
.. image:: /pictures/KGE_2009.png
**Range:** -inf < KGE (2009) < 1, larger is better.
**Notes:** Gupta et al. (2009) created this metric to demonstrate the relative importance of
the three components of the NSE, which are correlation, bias and variability. This was done
with hydrologic modeling as the context. This metric is meant to address issues with the NSE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), Alpha, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, alpha, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2009) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2009(sim, obs)
0.912223072345668
>>> he.kge_2009(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.927910707932087, 1.0058823529411764, 0.9181073779138655)
References
----------
- Gupta, H. V., Kling, H., Yilmaz, K. K., & Martinez, G. F. (2009). Decomposition of the mean
squared error and NSE performance criteria: Implications for improving hydrological modelling.
Journal of Hydrology, 377(1-2), 80-91.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array, ddof=1)
obs_sigma = np.std(observed_array, ddof=1)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
if obs_mean != 0:
beta = sim_mean / obs_mean
else:
beta = np.nan
# Relative variability between simulated and observed values
if obs_sigma != 0:
alpha = sim_sigma / obs_sigma
else:
alpha = np.nan
if not np.isnan(beta) and not np.isnan(alpha):
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (alpha - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Alpha is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, alpha, beta, kge
else:
return kge
def kge_2012(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""
Compute the Kling-Gupta efficiency (2012).
.. image:: /pictures/KGE_2012.png
**Range:** -inf < KGE (2012) < 1, does not indicate bias, larger is better.
**Notes:** The modified version of the KGE (2009). Kling proposed this version to avoid
cross-correlation between bias and variability ratios.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), gamma, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, gamma, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2012) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2012(sim, obs)
0.9122230723456678
>>> he.kge_2012(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.9224843295231272, 1.0058823529411764, 0.9132923608280753)
References
----------
- Kling, H., Fuchs, M., & Paulin, M. (2012). Runoff conditions in the upper Danube basin under
an ensemble of climate change scenarios. Journal of Hydrology, 424, 264-277.
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array)
obs_sigma = np.std(observed_array)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
beta = sim_mean / obs_mean
# CV is the coefficient of variation (standard deviation / mean)
sim_cv = sim_sigma / sim_mean
obs_cv = obs_sigma / obs_mean
# Variability Ratio, or the ratio of simulated CV to observed CV
gam = sim_cv / obs_cv
if obs_mean != 0 and obs_sigma != 0 and sim_mean != 0:
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (gam - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
if sim_mean == 0:
warnings.warn(
'Warning: The simulated data mean is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, gam, beta, kge
else:
return kge
def lm_index(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""
Compute the Legate-McCabe Efficiency Index.
.. image:: /pictures/E1p.png
**Range:** 0 ≤ E1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.lm_index(sim, obs)
0.6949152542372882
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
mean_obs = np.mean(observed_array)
if obs_bar_p is not None:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def d1_p(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""Compute the Legate-McCabe Index of Agreement.
.. image:: /pictures/D1p.png
**Range:** 0 ≤ d1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1_p(sim, obs)
0.8434782608695652
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
if obs_bar_p is not None:
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - obs_bar_p) + np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
mean_obs = np.mean(observed_array)
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - mean_obs) + np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def ve(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Volumetric Efficiency (VE).
.. image:: /pictures/VE.png
**Range:** 0 ≤ VE < 1 smaller is better, does not indicate bias.
**Notes:** Represents the error as a percentage of flow.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Volumetric Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ve(sim, obs)
0.8947368421052632
References
----------
- Criss, R.E., Winston, W.E., 2008. Do Nash values have value? Discussion and alternate
proposals. Hydrological Processes 22(14) 2723.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(observed_array)
return 1 - (a / b)
def sa(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Angle (SA).
.. image:: /pictures/SA.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral angle metric measures the angle between the two vectors in hyperspace.
It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Angle value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sa(sim, obs)
0.10816831366492945
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(simulated_array, observed_array)
b = np.linalg.norm(simulated_array) * np.linalg.norm(observed_array)
return np.arccos(a / b)
def sid(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Information Divergence (SID).
.. image:: /pictures/SID.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral information divergence measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral information divergence value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sid(sim, obs)
0.03517616895318012
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
first = (observed_array / np.mean(observed_array)) - (
simulated_array / np.mean(simulated_array))
second1 = np.log10(observed_array) - np.log10(np.mean(observed_array))
second2 = np.log10(simulated_array) - np.log10(np.mean(simulated_array))
return np.dot(first, second1 - second2)
def sga(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Gradient Angle (SGA).
.. image:: /pictures/SGA.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral gradient angle measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
SG is the gradient of the simulated or observed time series.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Gradient Angle.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sga(sim, obs)
0.26764286472739834
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sgx = observed_array[1:] - observed_array[:observed_array.size - 1]
sgy = simulated_array[1:] - simulated_array[:simulated_array.size - 1]
a = np.dot(sgx, sgy)
b = np.linalg.norm(sgx) * np.linalg.norm(sgy)
return np.arccos(a / b)
####################################################################################################
# H Metrics: Methods from Tornqvist L, Vartia P, and Vartia YO. (1985) #
####################################################################################################
def h1_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the H1 mean error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mhe(sim, obs)
0.002106551840594386
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(h)
def h1_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H1 absolute error.
.. image:: /pictures/H1.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The H1 absolute error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mahe(sim, obs)
0.11639226612630865
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(np.abs(h))
def h1_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H1 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean squared H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_rmshe(sim, obs)
0.12865571253672756
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.sqrt(np.mean(h ** 2))
def h2_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean error.
.. image:: /pictures/H2.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mhe(sim, obs)
-0.015319829424307036
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(h)
def h2_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean absolute error.
.. image:: /pictures/H2.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mahe(sim, obs)
0.11997591408039167
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(np.abs(h))
def h2_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_rmshe(sim, obs)
0.1373586680669673
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.sqrt(np.mean(h ** 2))
def h3_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 mean error.
.. image:: /pictures/H3.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mhe(sim, obs)
-0.006322019630356533
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(h)
def h3_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H3 mean absolute error.
.. image:: /pictures/H3.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mahe(sim, obs)
0.11743831388794855
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(np.abs(h))
def h3_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 root mean square error.
.. image:: /pictures/H3.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.sqrt(np.mean(h ** 2))
def h4_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mhe(sim, obs)
-0.0064637371129817
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(h)
def h4_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H4 mean absolute error.
.. image:: /pictures/H4.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mahe(sim, obs)
0.11781032209144082
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(np.abs(h))
def h4_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_rmshe(sim, obs)
0.13200901963465006
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.sqrt(np.mean(h ** 2))
def h5_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean error.
.. image:: /pictures/H5.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mhe(sim, obs)
-0.006606638791856322
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(h)
def h5_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean absolute error.
.. image:: /pictures/H5.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mahe(sim, obs)
0.11818409010335018
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(np.abs(h))
def h5_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 root mean square error.
.. image:: /pictures/H5.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_rmshe(sim, obs)
0.13254476469410933
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h6_mhe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H6 mean error.
.. image:: /pictures/H6.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mhe(sim, obs)
-0.006322019630356514
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(h)
def h6_mahe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""Compute the H6 mean absolute error.
.. image:: /pictures/H6.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mahe(sim, obs)
0.11743831388794852
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(np.abs(h))
def h6_rmshe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the H6 root mean square error.
.. image:: /pictures/H6.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h7_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean error.
.. image:: /pictures/H7.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mhe(sim, obs)
0.0026331898007430263
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(h)
def h7_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean absolute error.
.. image:: /pictures/H7.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mahe(sim, obs)
0.14549033265788583
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(np.abs(h))
def h7_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 root mean square error.
.. image:: /pictures/H7.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_rmshe(sim, obs)
0.16081964067090945
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
def h8_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H8 mean error.
.. image:: /pictures/H8.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mhe(sim, obs)
0.0018056158633666466
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(h)
def h8_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 mean absolute error.
.. image:: /pictures/H8.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mahe(sim, obs)
0.099764799536836
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(np.abs(h))
def h8_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 root mean square error.
.. image:: /pictures/H8.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_rmshe(sim, obs)
0.11027632503148076
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
# def h9(simulated_array, observed_array, h_type='mhe', k=1):
# h = (simulated_array / observed_array - 1) / \
# np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
# if h_type == 'mhe':
# return h.mean()
# elif h_type == 'ahe':
# return np.abs(h).mean()
# elif h_type == 'rmshe':
# return np.sqrt((h**2).mean())
# else:
# raise RuntimeError("The three types available are 'mhe', 'ahe', and 'rmshe'.")
def h10_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean error.
.. image:: /pictures/H10.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h10_mhe(sim, obs)
-0.0012578676058971154
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(h)
def h10_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean absolute error.
.. image:: /pictures/H10.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_mahe(sim, obs), 6)
0.094636
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(np.abs(h))
def h10_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 root mean square error.
.. image:: /pictures/H10.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_rmshe(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.sqrt(np.mean(h ** 2))
###################################################################################################
# Statistical Error Metrics for Distribution Testing #
###################################################################################################
def g_mean_diff(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the geometric mean difference.
.. image:: /pictures/GMD.png
**Range:**
**Notes:** For the difference of geometric means, the geometric mean is computed for each of
two samples then their difference is taken.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The geometric mean difference value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.g_mean_diff(sim, obs)
0.988855412098022
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.exp(gmean(sim_log) - gmean(obs_log))
def mean_var(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the mean variance.
.. image:: /pictures/MV.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean variance.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.mean_var(sim, obs), 6)
0.010641
References
----------
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.var(np.log1p(observed_array) - np.log1p(simulated_array))
####################################################################################################
# HELPER FUNCTIONS AND API INFORMATION #
####################################################################################################
metric_names = [
'Mean Error', 'Mean Absolute Error', 'Mean Squared Error', 'Mean Log Error',
'Mean Absolute Log Error', 'Mean Squared Log Error', 'Median Error', 'Median Absolute Error',
'Median Squared Error', 'Eclidean Distance', 'Normalized Eclidean Distance',
'Root Mean Square Error', 'Root Mean Squared Log Error',
'Normalized Root Mean Square Error - Range', 'Normalized Root Mean Square Error - Mean',
'Normalized Root Mean Square Error - IQR', 'Inertial Root Mean Square Error',
'Mean Absolute Scaled Error', 'Coefficient of Determination', 'Pearson Correlation Coefficient',
'Spearman Rank Correlation Coefficient', 'Anomaly Correlation Coefficient',
'Mean Absolute Percentage Error', 'Mean Absolute Percentage Deviation',
'Mean Arctangent Absolute Percentage Error', 'Symmetric Mean Absolute Percentage Error (1)',
'Symmetric Mean Absolute Percentage Error (2)', 'Index of Agreement (d)',
'Index of Agreement (d1)', 'Modified Index of Agreement', 'Relative Index of Agreement',
'Index of Agreement Refined (dr)', "Watterson's M", 'Mielke-Berry R',
'Nash-Sutcliffe Efficiency', 'Modified Nash-Sutcliffe Efficiency',
'Relative Nash-Sutcliffe Efficiency', 'Kling-Gupta Efficiency (2009)',
'Kling-Gupta Efficiency (2012)', 'Legate-McCabe Efficiency Index',
'Legate-McCabe Index of Agreement', 'Volumetric Efficiency', 'Spectral Angle',
'Spectral Correlation', 'Spectral Information Divergence', 'Spectral Gradient Angle',
'Mean H1 Error', 'Mean Absolute H1 Error', 'Root Mean Square H1 Error', 'Mean H2 Error',
'Mean Absolute H2 Error', 'Root Mean Square H2 Error', 'Mean H3 Error',
'Mean Absolute H3 Error', 'Root Mean Square H3 Error', 'Mean H4 Error',
'Mean Absolute H4 Error', 'Root Mean Square H4 Error', 'Mean H5 Error',
'Mean Absolute H5 Error', 'Root Mean Square H5 Error', 'Mean H6 Error',
'Mean Absolute H6 Error', 'Root Mean Square H6 Error', 'Mean H7 Error',
'Mean Absolute H7 Error', 'Root Mean Square H7 Error', 'Mean H8 Error',
'Mean Absolute H8 Error', 'Root Mean Square H8 Error', 'Mean H10 Error',
'Mean Absolute H10 Error', 'Root Mean Square H10 Error', 'Geometric Mean Difference',
'Mean Variance'
]
metric_abbr = [
'ME', 'MAE', 'MSE', 'MLE', 'MALE', 'MSLE', 'MdE', 'MdAE', 'MdSE', 'ED', 'NED', 'RMSE', 'RMSLE',
'NRMSE (Range)', 'NRMSE (Mean)', 'NRMSE (IQR)', 'IRMSE', 'MASE', 'r2', 'R (Pearson)',
'R (Spearman)', 'ACC', 'MAPE', 'MAPD', 'MAAPE', 'SMAPE1', 'SMAPE2', 'd', 'd1', 'd (Mod.)',
'd (Rel.)', 'dr', 'M', '(MB) R', 'NSE', 'NSE (Mod.)', 'NSE (Rel.)', 'KGE (2009)', 'KGE (2012)',
"E1'", "D1'", 'VE', 'SA', 'SC', 'SID', 'SGA', 'H1 (MHE)', 'H1 (MAHE)', 'H1 (RMSHE)', 'H2 (MHE)',
'H2 (MAHE)', 'H2 (RMSHE)', 'H3 (MHE)', 'H3 (MAHE)', 'H3 (RMSHE)', 'H4 (MHE)', 'H4 (MAHE)',
'H4 (RMSHE)', 'H5 (MHE)', 'H5 (MAHE)', 'H5 (RMSHE)', 'H6 (MHE)', 'H6 (MAHE)', 'H6 (RMSHE)',
'H7 (MHE)', 'H7 (MAHE)', 'H7 (RMSHE)', 'H8 (MHE)', 'H8 (MAHE)', 'H8 (RMSHE)', 'H10 (MHE)',
'H10 (MAHE)', 'H10 (RMSHE)', 'GMD', 'MV'
]
function_list = [
me, mae, mse, mle, male, msle, mde, mdae, mdse, ed, ned, rmse, rmsle, nrmse_range, nrmse_mean,
nrmse_iqr, irmse, mase, r_squared, pearson_r, spearman_r, acc, mape, mapd, maape, smape1,
smape2, d, d1, dmod, drel, dr, watt_m, mb_r, nse, nse_mod, nse_rel, kge_2009, kge_2012,
lm_index, d1_p, ve, sa, sc, sid, sga, h1_mhe, h1_mahe, h1_rmshe, h2_mhe, h2_mahe, h2_rmshe,
h3_mhe, h3_mahe, h3_rmshe, h4_mhe, h4_mahe, h4_rmshe, h5_mhe, h5_mahe, h5_rmshe, h6_mhe,
h6_mahe, h6_rmshe, h7_mhe, h7_mahe, h7_rmshe, h8_mhe, h8_mahe, h8_rmshe, h10_mhe, h10_mahe,
h10_rmshe, g_mean_diff, mean_var,
]
# Assign some properties to each function for ease of use for users
for i in range(len(function_list)):
function_list[i].name = metric_names[i]
function_list[i].abbr = metric_abbr[i]
def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Removes the nan, negative, and inf values in two numpy arrays"""
sim_copy = np.copy(simulated_array)
obs_copy = np.copy(observed_array)
# Checking to see if the vectors are the same length
assert sim_copy.ndim == 1, "The simulated array is not one dimensional."
assert obs_copy.ndim == 1, "The observed array is not one dimensional."
if sim_copy.size != obs_copy.size:
raise RuntimeError("The two ndarrays are not the same size.")
# Treat missing data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain nan values
all_treatment_array = np.ones(obs_copy.size, dtype=bool)
if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_nan = np.isnan(sim_copy)
obs_nan = np.isnan(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_nan] = replace_nan
obs_copy[obs_nan] = replace_nan
warnings.warn("Elements(s) {} contained NaN values in the simulated array and "
"elements(s) {} contained NaN values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_nan)[0],
np.where(obs_nan)[0]),
UserWarning)
else:
# Getting the indices of the nan values, combining them, and informing user.
nan_indices_fcst = ~np.isnan(sim_copy)
nan_indices_obs = ~np.isnan(obs_copy)
all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)
warnings.warn("Row(s) {} contained NaN values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_nan_indices)[0]),
UserWarning)
if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_inf = np.isinf(sim_copy)
obs_inf = np.isinf(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_inf] = replace_inf
obs_copy[obs_inf] = replace_inf
warnings.warn("Elements(s) {} contained Inf values in the simulated array and "
"elements(s) {} contained Inf values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_inf)[0],
np.where(obs_inf)[0]),
UserWarning)
else:
inf_indices_fcst = ~(np.isinf(sim_copy))
inf_indices_obs = ~np.isinf(obs_copy)
all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)
warnings.warn(
"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows "
"are zero indexed).".format(np.where(~all_inf_indices)[0]),
UserWarning
)
# Treat zero data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain zero values
if remove_zero:
if (obs_copy == 0).any() or (sim_copy == 0).any():
zero_indices_fcst = ~(sim_copy == 0)
zero_indices_obs = ~(obs_copy == 0)
all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)
warnings.warn(
"Row(s) {} contained zero values and the row(s) have been removed (Rows are "
"zero indexed).".format(np.where(~all_zero_indices)[0]),
UserWarning
)
# Treat negative data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain negative values
# Ignore runtime warnings from comparing
if remove_neg:
with np.errstate(invalid='ignore'):
obs_copy_bool = obs_copy < 0
sim_copy_bool = sim_copy < 0
if obs_copy_bool.any() or sim_copy_bool.any():
neg_indices_fcst = ~sim_copy_bool
neg_indices_obs = ~obs_copy_bool
all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)
warnings.warn("Row(s) {} contained negative values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_neg_indices)[0]),
UserWarning)
obs_copy = obs_copy[all_treatment_array]
sim_copy = sim_copy[all_treatment_array]
return sim_copy, obs_copy
if __name__ == "__main__":
pass
|
BYU-Hydroinformatics/HydroErr | HydroErr/HydroErr.py | sid | python | def sid(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
first = (observed_array / np.mean(observed_array)) - (
simulated_array / np.mean(simulated_array))
second1 = np.log10(observed_array) - np.log10(np.mean(observed_array))
second2 = np.log10(simulated_array) - np.log10(np.mean(simulated_array))
return np.dot(first, second1 - second2) | Compute the Spectral Information Divergence (SID).
.. image:: /pictures/SID.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral information divergence measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral information divergence value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sid(sim, obs)
0.03517616895318012
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166. | train | https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L3694-L3770 | [
"def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,\n remove_neg=False, remove_zero=False):\n \"\"\"Removes the nan, negative, and inf values in two numpy arrays\"\"\"\n sim_copy = np.copy(simulated_array)\n obs_copy = np.copy(observed_array)\n\n # Checking to see if the vectors are the same length\n assert sim_copy.ndim == 1, \"The simulated array is not one dimensional.\"\n assert obs_copy.ndim == 1, \"The observed array is not one dimensional.\"\n\n if sim_copy.size != obs_copy.size:\n raise RuntimeError(\"The two ndarrays are not the same size.\")\n\n # Treat missing data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain nan values\n all_treatment_array = np.ones(obs_copy.size, dtype=bool)\n\n if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_nan = np.isnan(sim_copy)\n obs_nan = np.isnan(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_nan] = replace_nan\n obs_copy[obs_nan] = replace_nan\n\n warnings.warn(\"Elements(s) {} contained NaN values in the simulated array and \"\n \"elements(s) {} contained NaN values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_nan)[0],\n np.where(obs_nan)[0]),\n UserWarning)\n else:\n # Getting the indices of the nan values, combining them, and informing user.\n nan_indices_fcst = ~np.isnan(sim_copy)\n nan_indices_obs = ~np.isnan(obs_copy)\n all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)\n\n warnings.warn(\"Row(s) {} contained NaN values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_nan_indices)[0]),\n UserWarning)\n\n if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_inf = np.isinf(sim_copy)\n obs_inf = np.isinf(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_inf] = replace_inf\n obs_copy[obs_inf] = replace_inf\n\n warnings.warn(\"Elements(s) {} contained Inf values in the simulated array and \"\n \"elements(s) {} contained Inf values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_inf)[0],\n np.where(obs_inf)[0]),\n UserWarning)\n else:\n inf_indices_fcst = ~(np.isinf(sim_copy))\n inf_indices_obs = ~np.isinf(obs_copy)\n all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)\n\n warnings.warn(\n \"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows \"\n \"are zero indexed).\".format(np.where(~all_inf_indices)[0]),\n UserWarning\n )\n\n # Treat zero data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain zero values\n if remove_zero:\n if (obs_copy == 0).any() or (sim_copy == 0).any():\n zero_indices_fcst = ~(sim_copy == 0)\n zero_indices_obs = ~(obs_copy == 0)\n all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)\n\n warnings.warn(\n \"Row(s) {} contained zero values and the row(s) have been removed (Rows are \"\n \"zero indexed).\".format(np.where(~all_zero_indices)[0]),\n UserWarning\n )\n\n # Treat negative data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain negative values\n\n # Ignore runtime warnings from comparing\n if remove_neg:\n with np.errstate(invalid='ignore'):\n obs_copy_bool = obs_copy < 0\n sim_copy_bool = sim_copy < 0\n\n if obs_copy_bool.any() or sim_copy_bool.any():\n neg_indices_fcst = ~sim_copy_bool\n neg_indices_obs = ~obs_copy_bool\n all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)\n\n warnings.warn(\"Row(s) {} contained negative values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_neg_indices)[0]),\n UserWarning)\n\n obs_copy = obs_copy[all_treatment_array]\n sim_copy = sim_copy[all_treatment_array]\n\n return sim_copy, obs_copy\n"
] | # -*- coding: utf-8 -*-
"""
HydroErr contains a library of goodness of fit metrics that measure hydrologic skill.
Each metric is contained in function, and every function has the parameters to treat missing values as
well as remove zero and negative values from the timeseries data.
Each function contains two properties, name and abbr. These can be used in the Hydrostats package when creating tables
and adding metrics to the plots. Link to the hydrostats package: https://github.com/BYU-Hydroinformatics/Hydrostats.
An example of this functionality is shown below.
>>> import HydroErr as he
>>>
>>> he.acc.name
'Anomaly Correlation Coefficient'
>>> he.acc.abbr
'ACC'
"""
from __future__ import division
import numpy as np
from scipy.stats import gmean, rankdata
import warnings
__all__ = ['me', 'mae', 'mse', 'mle', 'male', 'msle', 'mde', 'mdae', 'mdse', 'ed', 'ned', 'rmse',
'rmsle', 'nrmse_range', 'nrmse_mean', 'nrmse_iqr', 'irmse', 'mase', 'r_squared',
'pearson_r', 'spearman_r', 'acc', 'mape', 'mapd', 'maape', 'smape1', 'smape2', 'd', 'd1',
'dmod', 'drel', 'dr', 'watt_m', 'mb_r', 'nse', 'nse_mod', 'nse_rel', 'kge_2009',
'kge_2012', 'lm_index', 'd1_p', 've', 'sa', 'sc', 'sid', 'sga', 'h1_mhe', 'h1_mahe',
'h1_rmshe', 'h2_mhe', 'h2_mahe', 'h2_rmshe', 'h3_mhe', 'h3_mahe', 'h3_rmshe', 'h4_mhe',
'h4_mahe', 'h4_rmshe', 'h5_mhe', 'h5_mahe', 'h5_rmshe', 'h6_mhe', 'h6_mahe', 'h6_rmshe',
'h7_mhe', 'h7_mahe', 'h7_rmshe', 'h8_mhe', 'h8_mahe', 'h8_rmshe', 'h10_mhe', 'h10_mahe',
'h10_rmshe', 'g_mean_diff', 'mean_var']
####################################################################################################
# General and Hydrological Error Metrics #
####################################################################################################
def me(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean error of the simulated and observed data.
.. image:: /pictures/ME.png
**Range:** -inf < MAE < inf, data units, closer to zero is better, indicates bias.
**Notes:** The mean error (ME) measures the difference between the simulated data and the
observed data. For the mean error, a smaller number indicates a better fit to the original
data. Note that if the error is in the form of random noise, the mean error will be very small,
which can skew the accuracy of this metric. ME is cumulative and will be small even if there
are large positive and negative errors that balance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean error value.
Examples
--------
Note that in this example the random noise cancels, leaving a very small ME.
>>> import HydroErr as he
>>> import numpy as np
>>> # Seed for reproducibility
>>> np.random.seed(54839)
>>> x = np.arange(100) / 20
>>> sim = np.sin(x) + 2
>>> obs = sim * (((np.random.rand(100) - 0.5) / 10) + 1)
>>> he.me(sim, obs)
-0.006832220968967168
References
----------
- Fisher, R.A., 1920. A Mathematical Examination of the Methods of Determining the Accuracy of
an Observation by the Mean Error, and by the Mean Square Error. Monthly Notices of the Royal
Astronomical Society 80 758 - 770.
"""
# Treating missing values
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero)
return np.mean(simulated_array - observed_array)
def mae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute error of the simulated and observed data.
.. image:: /pictures/MAE.png
**Range:** 0 ≤ MAE < inf, data units, smaller is better.
**Notes:** The ME measures the absolute difference between the simulated data and the observed
data. For the mean abolute error, a smaller number indicates a better fit to the original data.
Also note that random errors do not cancel. Also referred to as an L1-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute error value.
References
----------
- Willmott, Cort J., and Kenji Matsuura. “Advantages of the Mean Absolute Error (MAE) over the
Root Mean Square Error (RMSE) in Assessing Average Model Performance.” Climate Research 30,
no. 1 (2005): 79–82.
- Willmott, Cort J., and Kenji Matsuura. “On the Use of Dimensioned Measures of Error to
Evaluate the Performance of Spatial Interpolators.” International Journal of Geographical
Information Science 20, no. 1 (2006): 89–102.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mae(sim, obs)
0.5666666666666665
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean(np.absolute(simulated_array - observed_array))
def mse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared error of the simulated and observed data.
.. image:: /pictures/MSE.png
**Range:** 0 ≤ MSE < inf, data units squared, smaller is better.
**Notes:** Random errors do not cancel, highlights larger errors, also referred to as a
squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mse(sim, obs)
0.4333333333333333
References
----------
- Wang, Zhou, and Alan C. Bovik. “Mean Squared Error: Love It or Leave It? A New Look at Signal
Fidelity Measures.” IEEE Signal Processing Magazine 26, no. 1 (2009): 98–117.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean((simulated_array - observed_array) ** 2)
def mle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean log error of the simulated and observed data.
.. image:: /pictures/MLE.png
**Range:** -inf < MLE < inf, data units, closer to zero is better.
**Notes** Same as the mean erro (ME) only use log ratios as the error term. Limits the impact of outliers, more
evenly weights high and low data values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mle(sim, obs)
0.002961767058151136
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(sim_log - obs_log)
def male(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean absolute log error of the simulated and observed data.
.. image:: /pictures/MALE.png
**Range:** 0 ≤ MALE < inf, data units squared, smaller is better.
**Notes** Same as MAE only use log ratios as the error term. Limits the impact of outliers,
more evenly weights high and low flows.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.male(sim, obs), 6)
0.090417
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(np.abs(sim_log - obs_log))
def msle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared log error of the simulated and observed data.
.. image:: /pictures/MSLE.png
**Range:** 0 ≤ MSLE < inf, data units squared, smaller is better.
**Notes** Same as the mean squared error (MSE) only use log ratios as the error term. Limits
the impact of outliers, more evenly weights high and low values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.msle(sim, obs), 6)
0.010426
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean((sim_log - obs_log) ** 2)
def mde(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median error (MdE) between the simulated and observed data.
.. image:: /pictures/MdE.png
**Range** -inf < MdE < inf, closer to zero is better.
**Notes** This metric indicates bias. It is similar to the mean error (ME), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mde(sim, obs)
-0.10000000000000009
Returns
-------
float
The median error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(simulated_array - observed_array)
def mdae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median absolute error (MdAE) between the simulated and observed data.
.. image:: /pictures/MdAE.png
**Range** 0 ≤ MdAE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean absolute error (MAE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdae(sim, obs)
0.75
Returns
-------
float
The median absolute error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(np.abs(simulated_array - observed_array))
def mdse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median squared error (MdSE) between the simulated and observed data.
.. image:: /pictures/MdSE.png
**Range** 0 ≤ MdSE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean squared error (MSE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdse(sim, obs)
0.625
Returns
-------
float
The median squared error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median((simulated_array - observed_array) ** 2)
def ed(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Euclidean distance between predicted and observed values in vector space.
.. image:: /pictures/ED.png
**Range** 0 ≤ ED < inf, smaller is better.
**Notes** Also sometimes referred to as the L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ed(sim, obs)
1.63707055437449
Returns
-------
float
The euclidean distance error value.
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.linalg.norm(observed_array - simulated_array)
def ned(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the normalized Euclidian distance between the simulated and observed data in vector
space.
.. image:: /pictures/NED.png
**Range** 0 ≤ NED < inf, smaller is better.
**Notes** Also sometimes referred to as the squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The normalized euclidean distance value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ned(sim, obs)
0.2872053604165771
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array / np.mean(observed_array)
b = simulated_array / np.mean(simulated_array)
return np.linalg.norm(a - b)
def rmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square error between the simulated and observed data.
.. image:: /pictures/RMSE.png
**Range** 0 ≤ RMSE < inf, smaller is better.
**Notes:** The standard deviation of the residuals. A lower spread indicates that the points
are better concentrated around the line of best fit (linear). Random errors do not cancel.
This metric will highlights larger errors.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.rmse(sim, obs)
0.668331255192114
References
----------
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.sqrt(np.mean((simulated_array - observed_array) ** 2))
def rmsle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square log error between the simulated and observed data.
.. image:: /pictures/RMSLE.png
**Range:** 0 ≤ RMSLE < inf. Smaller is better, and it does not indicate bias.
**Notes:** Random errors do not cancel while using this metric. This metric limits the
impact of outliers by more evenly weighting high and low values. To calculate the log values,
each value in the observed and simulated array is increased by one unit in order to avoid
run-time errors and nan values (function np.log1p).
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square log error value.
Examples
--------
Notice that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.rmsle(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
"""
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf, remove_neg=remove_neg,
remove_zero=remove_zero)
return np.sqrt(np.mean(np.power(np.log1p(simulated_array) - np.log1p(observed_array), 2)))
def nrmse_range(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the range normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Range.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the range of the observed time series (x).
Normalizing allows comparison between data sets with different scales. The NRMSErange is the
most sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The range normalized root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_range(sim, obs)
0.0891108340256152
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_max = np.max(observed_array)
obs_min = np.min(observed_array)
return rmse_value / (obs_max - obs_min)
def nrmse_mean(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Mean.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the mean of the observed time series (x).
Normalizing allows comparison between data sets with different scales.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_mean(sim, obs)
0.11725109740212526
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_mean = np.mean(observed_array)
return rmse_value / obs_mean
def nrmse_iqr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the IQR normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_IQR.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the interquartile range of the observed time
series (x). Normalizing allows comparison between data sets with different scales.
The NRMSEquartile is the least sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The IQR normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_iqr(sim, obs)
0.2595461185212093
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
q1 = np.percentile(observed_array, 25)
q3 = np.percentile(observed_array, 75)
iqr = q3 - q1
return rmse_value / iqr
def irmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the inertial root mean square error (IRMSE) between the simulated and observed data.
.. image:: /pictures/IRMSE.png
**Range:** 0 ≤ IRMSE < inf, lower is better.
**Notes:** This metric is the RMSE devided by by the standard deviation of the gradient of the
observed timeseries data. This metric is meant to be help understand the ability of the model
to predict changes in observation.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The inertial root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.irmse(sim, obs)
0.14572738134831856
References
----------
- Daga, M., Deo, M.C., 2009. Alternative data-driven methods to estimate wind from waves by
inverse modeling. Natural Hazards 49(2) 293-310.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Getting the gradient of the observed data
obs_len = observed_array.size
obs_grad = observed_array[1:obs_len] - observed_array[0:obs_len - 1]
# Standard deviation of the gradient
obs_grad_std = np.std(obs_grad, ddof=1)
# Divide RMSE by the standard deviation of the gradient of the observed data
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
return rmse_value / obs_grad_std
def mase(simulated_array, observed_array, m=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute scaled error between the simulated and observed data.
.. image:: /pictures/MASE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
m: int
If given, indicates the seasonal period m. If not given, the default is 1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute scaled error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mase(sim, obs)
0.17341040462427745
References
----------
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
start = m
end = simulated_array.size - m
a = np.mean(np.abs(simulated_array - observed_array))
b = np.abs(observed_array[start:observed_array.size] - observed_array[:end])
return a / (np.sum(b) / end)
def pearson_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the pearson correlation coefficient.
.. image:: /pictures/R_pearson.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The pearson r coefficient measures linear correlation. It is sensitive to outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Pearson correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.pearson_r(sim, obs)
0.9610793632835262
References
----------
- Pearson, K. (1895). Note on regression and inheritance in the case of two parents.
Proceedings of the Royal Society of London, 58, 240-242.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
top = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1 = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2 = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
return top / (bot1 * bot2)
def spearman_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the spearman rank correlation coefficient.
.. image:: /pictures/R_spearman.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The spearman r coefficient measures the monotonic relation between simulated and
observed data. Because it uses a nonparametric measure of rank correlation, it is less sensitive
to outliers compared to the Pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spearman rank correlation coefficient.
Examples
----------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.spearman_r(sim, obs)
0.942857142857143
References
----------
- Spearman C (1904). "The proof and measurement of association between two things". American
Journal of Psychology. 15: 72–101. doi:10.2307/1412159
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rank_sim = rankdata(simulated_array)
rank_obs = rankdata(observed_array)
mean_rank_sim = np.mean(rank_sim)
mean_rank_obs = np.mean(rank_obs)
top = np.mean((rank_obs - mean_rank_obs) * (rank_sim - mean_rank_sim))
bot = np.sqrt(
np.mean((rank_obs - mean_rank_obs) ** 2) * np.mean((rank_sim - mean_rank_sim) ** 2))
return top / bot
def r_squared(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Coefficient of Determination (r2).
.. image:: /pictures/r2.png
**Range:** 0 ≤ r2 ≤ 1. 1 indicates perfect correlation, 0 indicates complete randomness.
**Notes:** The Coefficient of Determination measures the linear relation between simulated and
observed data. Because it is the pearson correlation coefficient squared, it is more heavily
affected by outliers than the pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The coefficient of determination (R^2).
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.r_squared(sim, obs)
0.9236735425294681
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array - np.mean(observed_array)
b = simulated_array - np.mean(simulated_array)
return (np.sum(a * b)) ** 2 / (np.sum(a ** 2) * np.sum(b ** 2))
def acc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the anomaly correlation coefficient (ACC).
.. image:: /pictures/ACC.png
**Range:** -1 ≤ ACC ≤ 1. -1 indicates perfect negative correlation of the variation
pattern of the anomalies, 0 indicates complete randomness of the variation patterns of the
anomalies, 1 indicates perfect correlation of the variation pattern of the anomalies.
**Notes:** Common measure in the verification of spatial fields. Measures the correlation
between the variation pattern of the simulated data compared to the observed data.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The anomaly correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.acc(sim, obs)
0.8008994694029383
References
----------
- Langland, Rolf H., and Ryan N. Maue. “Recent Northern Hemisphere Mid-Latitude Medium-Range
Deterministic Forecast Skill.” Tellus A: Dynamic Meteorology and Oceanography 64,
no. 1 (2012): 17531.
- Miyakoda, K., G. D. Hembree, R. F. Strickler, and I. Shulman. “Cumulative Results of Extended
Forecast Experiments I. Model Performance for Winter Cases.” Monthly Weather Review 100, no.
12(1972): 836–55.
- Murphy, Allan H., and Edward S. Epstein. “Skill Scores and Correlation Coefficients in Model
Verification.” Monthly Weather Review 117, no. 3 (1989): 572–82.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - np.mean(simulated_array)
b = observed_array - np.mean(observed_array)
c = np.std(observed_array, ddof=1) * np.std(simulated_array, ddof=1) * simulated_array.size
return np.dot(a, b / c)
def mape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the mean absolute percentage error (MAPE).
.. image:: /pictures/MAPE.png
**Range:** 0% ≤ MAPE ≤ inf. 0% indicates perfect correlation, a larger error indicates a
larger percent error in the data.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
c = 100 / simulated_array.size
return c * np.sum(b)
def mapd(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the mean absolute percentage deviation (MAPD).
.. image:: /pictures/MAPD.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage deviation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mapd(sim, obs)
0.10526315789473682
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(np.abs(observed_array))
return a / b
def maape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the Mean Arctangent Absolute Percentage Error (MAAPE).
.. image:: /pictures/MAAPE.png
**Range:** 0 ≤ MAAPE < π/2, does not indicate bias, smaller is better.
**Notes:** Represents the mean absolute error as a percentage of the observed values. Handles
0s in the observed data. This metric is not as biased as MAPE by under-over predictions.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean arctangent absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
- Kim, S., Kim, H., 2016. A new metric of absolute percentage error for intermittent demand
forecasts. International Journal of Forecasting 32(3) 669-679.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
return np.mean(np.arctan(b))
def smape1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (1) (SMAPE1).
.. image:: /pictures/SMAPE1.png
**Range:** 0 ≤ SMAPE1 < 100%, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (1).
Examples
--------
Note that if we switch the simulated and observed arrays the result is the same
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape1(sim, obs)
5.871915694397428
>>> he.smape1(obs, sim)
5.871915694397428
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 100 / simulated_array.size
b = np.abs(simulated_array - observed_array)
c = np.abs(simulated_array) + np.abs(observed_array)
return a * np.sum(b / c)
def smape2(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (2) (SMAPE2).
.. image:: /pictures/SMAPE2.png
**Range:** 0 ≤ SMAPE1 < 200%, does not indicate bias, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE with only positive metric values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (2).
Examples
--------
Note that switching the simulated and observed arrays yields the same results
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape2(sim, obs)
11.743831388794856
>>> he.smape2(obs, sim)
11.743831388794856
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = (simulated_array + observed_array) / 2
c = 100 / simulated_array.size
return c * np.sum(np.abs(a / b))
def d(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d).
.. image:: /pictures/d.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d(sim, obs)
0.978477353035657
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (observed_array - simulated_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
return 1 - (np.sum(a) / np.sum((b + c) ** 2))
def d1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d1).
.. image:: /pictures/d1.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric. Compared
to the other index of agreement (d) it has a reduced impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (d1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1(sim, obs)
0.8434782608695652
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
obs_mean = np.mean(observed_array)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.abs(simulated_array - obs_mean)
c = np.abs(observed_array - obs_mean)
return 1 - np.sum(a) / np.sum(b + c)
def dr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the refined index of agreement (dr).
.. image:: /pictures/dr.png
**Range:** -1 ≤ dr < 1, does not indicate bias, larger is better.
**Notes:** Reformulation of Willmott’s index of agreement. This metric was created to address
issues in the index of agreement and the Nash-Sutcliffe efficiency metric. Meant to be a
flexible metric for use in climatology.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The refined index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dr(sim, obs)
0.847457627118644
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = 2 * np.sum(np.abs(observed_array - observed_array.mean()))
if a <= b:
return 1 - (a / b)
else:
return (b / a) - 1
def drel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the relative index of agreement (drel).
.. image:: /pictures/drel.png
**Range:** 0 ≤ drel < 1, does not indicate bias, larger is better.
**Notes:** Instead of absolute differences, this metric uses relative differences.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.drel(sim, obs)
0.9740868625579597
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = ((simulated_array - observed_array) / observed_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = ((b + c) / np.mean(observed_array)) ** 2
return 1 - (np.sum(a) / np.sum(e))
def dmod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the modified index of agreement (dmod).
.. image:: /pictures/dmod.png
**Range:** 0 ≤ dmod < 1, does not indicate bias, larger is better.
**Notes:** When j=1, this metric is the same as d1. As j becomes larger, outliers have a larger
impact on the value.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
Optional input indicating the j values desired. A higher j places more emphasis on
outliers. j is 1 by default.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified index of agreement.
Examples
--------
Note that using the default is the same as calculating the d1 metric. Changing the value of j
modification of the metric.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dmod(sim, obs) # Same as d1
0.8434782608695652
>>> he.dmod(sim, obs, j=1.5)
0.9413310986805733
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = (b + c) ** j
return 1 - (np.sum(a) / np.sum(e))
def watt_m(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute Watterson's M (M).
.. image:: /pictures/M.png
**Range:** -1 ≤ M < 1, does not indicate bias, larger is better.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
Watterson's M value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.watt_m(sim, obs)
0.8307913876595929
References
----------
- Watterson, I.G., 1996. Non‐dimensional measures of climate model performance. International
Journal of Climatology 16(4) 379-391.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 2 / np.pi
b = np.mean((simulated_array - observed_array) ** 2) # MSE
c = np.std(observed_array, ddof=1) ** 2 + np.std(simulated_array, ddof=1) ** 2
e = (np.mean(simulated_array) - np.mean(observed_array)) ** 2
f = c + e
return a * np.arcsin(1 - (b / f))
def mb_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute Mielke-Berry R value (MB R).
.. image:: /pictures/MB_R.png
**Range:** 0 ≤ MB R < 1, does not indicate bias, larger is better.
**Notes:** Compares prediction to probability it arose by chance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Mielke-Berry R value.
Notes
-----
If a more optimized version is desired, the `numba package <http://numba.pydata.org/doc.html>`_ can be implemented
for a much more optimized performance when computing this metric. An example is given below.
>>> from numba import njit, prange
>>> @njit(parallel=True, fastmath=True)
>>> def mb_par_fastmath(pred, obs): # uses LLVM compiler
>>> assert pred.size == obs.size
>>> n = pred.size
>>> tot = 0.0
>>> mae = 0.0
>>> for i in range(n):
>>> for j in prange(n):
>>> tot += abs(pred[i] - obs[j])
>>> mae += abs(pred[i] - obs[i])
>>> mae = mae / n
>>> mb = 1 - ((n ** 2) * mae / tot)
>>>
>>> return mb
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mb_r(sim, obs)
0.7726315789473684
References
----------
- Berry, K.J., Mielke, P.W., 1988. A Generalization of Cohen's Kappa Agreement Measure to
Interval Measurement and Multiple Raters. Educational and Psychological Measurement 48(4)
921-933.
- Mielke, P.W., Berry, K.J., 2007. Permutation methods: a distance function approach.
Springer Science & Business Media.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Calculate metric
n = simulated_array.size
tot = 0.0
for i in range(n):
tot = tot + np.sum(np.abs(simulated_array - observed_array[i]))
mae_val = np.sum(np.abs(simulated_array - observed_array)) / n
mb = 1 - ((n ** 2) * mae_val / tot)
return mb
def nse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Nash-Sutcliffe Efficiency.
.. image:: /pictures/NSE.png
**Range:** -inf < NSE < 1, does not indicate bias, larger is better.
**Notes:** The Nash-Sutcliffe efficiency metric compares prediction values to naive predictions
(i.e. average value). One major flaw of this metric is that it punishes a higher variance in
the observed values (denominator). This metric is analogous to the mean absolute error skill
score (MAESS) using the mean flow as a benchmark.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Nash-Sutcliffe Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse(sim, obs)
0.922093023255814
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
- McCuen, R.H., Knight, Z., Cutter, A.G., 2006. Evaluation of the Nash-Sutcliffe Efficiency
Index. Journal of Hydraulic Engineering.
- Nash, J.E., Sutcliffe, J.V., 1970. River flow forecasting through conceptual models part
I — A discussion of principles. Journal of Hydrology 282-290.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** 2
b = (np.abs(observed_array - np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def nse_mod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the modified Nash-Sutcliffe efficiency (NSE mod).
.. image:: /pictures/NSEmod.png
**Range:** -inf < NSE (mod) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
If given, sets the value of j to the input. j is 1 by default. A higher j gives more
emphasis to outliers
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_mod(sim, obs)
0.6949152542372882
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = (np.abs(observed_array - np.mean(observed_array))) ** j
return 1 - (np.sum(a) / np.sum(b))
def nse_rel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the relative Nash-Sutcliffe efficiency (NSE rel).
.. image:: /pictures/NSErel.png
**Range:** -inf < NSE (rel) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_rel(sim, obs)
0.9062004687708474
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs((simulated_array - observed_array) / observed_array)) ** 2
b = (np.abs((observed_array - np.mean(observed_array)) / np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def kge_2009(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""Compute the Kling-Gupta efficiency (2009).
.. image:: /pictures/KGE_2009.png
**Range:** -inf < KGE (2009) < 1, larger is better.
**Notes:** Gupta et al. (2009) created this metric to demonstrate the relative importance of
the three components of the NSE, which are correlation, bias and variability. This was done
with hydrologic modeling as the context. This metric is meant to address issues with the NSE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), Alpha, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, alpha, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2009) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2009(sim, obs)
0.912223072345668
>>> he.kge_2009(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.927910707932087, 1.0058823529411764, 0.9181073779138655)
References
----------
- Gupta, H. V., Kling, H., Yilmaz, K. K., & Martinez, G. F. (2009). Decomposition of the mean
squared error and NSE performance criteria: Implications for improving hydrological modelling.
Journal of Hydrology, 377(1-2), 80-91.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array, ddof=1)
obs_sigma = np.std(observed_array, ddof=1)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
if obs_mean != 0:
beta = sim_mean / obs_mean
else:
beta = np.nan
# Relative variability between simulated and observed values
if obs_sigma != 0:
alpha = sim_sigma / obs_sigma
else:
alpha = np.nan
if not np.isnan(beta) and not np.isnan(alpha):
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (alpha - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Alpha is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, alpha, beta, kge
else:
return kge
def kge_2012(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""
Compute the Kling-Gupta efficiency (2012).
.. image:: /pictures/KGE_2012.png
**Range:** -inf < KGE (2012) < 1, does not indicate bias, larger is better.
**Notes:** The modified version of the KGE (2009). Kling proposed this version to avoid
cross-correlation between bias and variability ratios.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), gamma, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, gamma, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2012) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2012(sim, obs)
0.9122230723456678
>>> he.kge_2012(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.9224843295231272, 1.0058823529411764, 0.9132923608280753)
References
----------
- Kling, H., Fuchs, M., & Paulin, M. (2012). Runoff conditions in the upper Danube basin under
an ensemble of climate change scenarios. Journal of Hydrology, 424, 264-277.
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array)
obs_sigma = np.std(observed_array)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
beta = sim_mean / obs_mean
# CV is the coefficient of variation (standard deviation / mean)
sim_cv = sim_sigma / sim_mean
obs_cv = obs_sigma / obs_mean
# Variability Ratio, or the ratio of simulated CV to observed CV
gam = sim_cv / obs_cv
if obs_mean != 0 and obs_sigma != 0 and sim_mean != 0:
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (gam - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
if sim_mean == 0:
warnings.warn(
'Warning: The simulated data mean is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, gam, beta, kge
else:
return kge
def lm_index(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""
Compute the Legate-McCabe Efficiency Index.
.. image:: /pictures/E1p.png
**Range:** 0 ≤ E1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.lm_index(sim, obs)
0.6949152542372882
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
mean_obs = np.mean(observed_array)
if obs_bar_p is not None:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def d1_p(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""Compute the Legate-McCabe Index of Agreement.
.. image:: /pictures/D1p.png
**Range:** 0 ≤ d1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1_p(sim, obs)
0.8434782608695652
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
if obs_bar_p is not None:
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - obs_bar_p) + np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
mean_obs = np.mean(observed_array)
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - mean_obs) + np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def ve(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Volumetric Efficiency (VE).
.. image:: /pictures/VE.png
**Range:** 0 ≤ VE < 1 smaller is better, does not indicate bias.
**Notes:** Represents the error as a percentage of flow.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Volumetric Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ve(sim, obs)
0.8947368421052632
References
----------
- Criss, R.E., Winston, W.E., 2008. Do Nash values have value? Discussion and alternate
proposals. Hydrological Processes 22(14) 2723.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(observed_array)
return 1 - (a / b)
def sa(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Angle (SA).
.. image:: /pictures/SA.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral angle metric measures the angle between the two vectors in hyperspace.
It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Angle value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sa(sim, obs)
0.10816831366492945
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(simulated_array, observed_array)
b = np.linalg.norm(simulated_array) * np.linalg.norm(observed_array)
return np.arccos(a / b)
def sc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Correlation (SC).
.. image:: /pictures/SC.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral correlation metric measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Correlation value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sc(sim, obs)
0.27991341383646606
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(observed_array - np.mean(observed_array), simulated_array - np.mean(simulated_array))
b = np.linalg.norm(observed_array - np.mean(observed_array))
c = np.linalg.norm(simulated_array - np.mean(simulated_array))
e = b * c
return np.arccos(a / e)
def sga(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Gradient Angle (SGA).
.. image:: /pictures/SGA.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral gradient angle measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
SG is the gradient of the simulated or observed time series.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Gradient Angle.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sga(sim, obs)
0.26764286472739834
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sgx = observed_array[1:] - observed_array[:observed_array.size - 1]
sgy = simulated_array[1:] - simulated_array[:simulated_array.size - 1]
a = np.dot(sgx, sgy)
b = np.linalg.norm(sgx) * np.linalg.norm(sgy)
return np.arccos(a / b)
####################################################################################################
# H Metrics: Methods from Tornqvist L, Vartia P, and Vartia YO. (1985) #
####################################################################################################
def h1_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the H1 mean error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mhe(sim, obs)
0.002106551840594386
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(h)
def h1_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H1 absolute error.
.. image:: /pictures/H1.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The H1 absolute error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mahe(sim, obs)
0.11639226612630865
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(np.abs(h))
def h1_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H1 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean squared H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_rmshe(sim, obs)
0.12865571253672756
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.sqrt(np.mean(h ** 2))
def h2_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean error.
.. image:: /pictures/H2.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mhe(sim, obs)
-0.015319829424307036
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(h)
def h2_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean absolute error.
.. image:: /pictures/H2.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mahe(sim, obs)
0.11997591408039167
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(np.abs(h))
def h2_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_rmshe(sim, obs)
0.1373586680669673
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.sqrt(np.mean(h ** 2))
def h3_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 mean error.
.. image:: /pictures/H3.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mhe(sim, obs)
-0.006322019630356533
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(h)
def h3_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H3 mean absolute error.
.. image:: /pictures/H3.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mahe(sim, obs)
0.11743831388794855
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(np.abs(h))
def h3_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 root mean square error.
.. image:: /pictures/H3.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.sqrt(np.mean(h ** 2))
def h4_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mhe(sim, obs)
-0.0064637371129817
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(h)
def h4_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H4 mean absolute error.
.. image:: /pictures/H4.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mahe(sim, obs)
0.11781032209144082
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(np.abs(h))
def h4_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_rmshe(sim, obs)
0.13200901963465006
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.sqrt(np.mean(h ** 2))
def h5_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean error.
.. image:: /pictures/H5.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mhe(sim, obs)
-0.006606638791856322
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(h)
def h5_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean absolute error.
.. image:: /pictures/H5.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mahe(sim, obs)
0.11818409010335018
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(np.abs(h))
def h5_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 root mean square error.
.. image:: /pictures/H5.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_rmshe(sim, obs)
0.13254476469410933
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h6_mhe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H6 mean error.
.. image:: /pictures/H6.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mhe(sim, obs)
-0.006322019630356514
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(h)
def h6_mahe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""Compute the H6 mean absolute error.
.. image:: /pictures/H6.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mahe(sim, obs)
0.11743831388794852
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(np.abs(h))
def h6_rmshe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the H6 root mean square error.
.. image:: /pictures/H6.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h7_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean error.
.. image:: /pictures/H7.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mhe(sim, obs)
0.0026331898007430263
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(h)
def h7_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean absolute error.
.. image:: /pictures/H7.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mahe(sim, obs)
0.14549033265788583
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(np.abs(h))
def h7_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 root mean square error.
.. image:: /pictures/H7.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_rmshe(sim, obs)
0.16081964067090945
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
def h8_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H8 mean error.
.. image:: /pictures/H8.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mhe(sim, obs)
0.0018056158633666466
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(h)
def h8_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 mean absolute error.
.. image:: /pictures/H8.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mahe(sim, obs)
0.099764799536836
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(np.abs(h))
def h8_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 root mean square error.
.. image:: /pictures/H8.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_rmshe(sim, obs)
0.11027632503148076
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
# def h9(simulated_array, observed_array, h_type='mhe', k=1):
# h = (simulated_array / observed_array - 1) / \
# np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
# if h_type == 'mhe':
# return h.mean()
# elif h_type == 'ahe':
# return np.abs(h).mean()
# elif h_type == 'rmshe':
# return np.sqrt((h**2).mean())
# else:
# raise RuntimeError("The three types available are 'mhe', 'ahe', and 'rmshe'.")
def h10_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean error.
.. image:: /pictures/H10.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h10_mhe(sim, obs)
-0.0012578676058971154
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(h)
def h10_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean absolute error.
.. image:: /pictures/H10.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_mahe(sim, obs), 6)
0.094636
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(np.abs(h))
def h10_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 root mean square error.
.. image:: /pictures/H10.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_rmshe(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.sqrt(np.mean(h ** 2))
###################################################################################################
# Statistical Error Metrics for Distribution Testing #
###################################################################################################
def g_mean_diff(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the geometric mean difference.
.. image:: /pictures/GMD.png
**Range:**
**Notes:** For the difference of geometric means, the geometric mean is computed for each of
two samples then their difference is taken.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The geometric mean difference value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.g_mean_diff(sim, obs)
0.988855412098022
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.exp(gmean(sim_log) - gmean(obs_log))
def mean_var(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the mean variance.
.. image:: /pictures/MV.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean variance.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.mean_var(sim, obs), 6)
0.010641
References
----------
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.var(np.log1p(observed_array) - np.log1p(simulated_array))
####################################################################################################
# HELPER FUNCTIONS AND API INFORMATION #
####################################################################################################
metric_names = [
'Mean Error', 'Mean Absolute Error', 'Mean Squared Error', 'Mean Log Error',
'Mean Absolute Log Error', 'Mean Squared Log Error', 'Median Error', 'Median Absolute Error',
'Median Squared Error', 'Eclidean Distance', 'Normalized Eclidean Distance',
'Root Mean Square Error', 'Root Mean Squared Log Error',
'Normalized Root Mean Square Error - Range', 'Normalized Root Mean Square Error - Mean',
'Normalized Root Mean Square Error - IQR', 'Inertial Root Mean Square Error',
'Mean Absolute Scaled Error', 'Coefficient of Determination', 'Pearson Correlation Coefficient',
'Spearman Rank Correlation Coefficient', 'Anomaly Correlation Coefficient',
'Mean Absolute Percentage Error', 'Mean Absolute Percentage Deviation',
'Mean Arctangent Absolute Percentage Error', 'Symmetric Mean Absolute Percentage Error (1)',
'Symmetric Mean Absolute Percentage Error (2)', 'Index of Agreement (d)',
'Index of Agreement (d1)', 'Modified Index of Agreement', 'Relative Index of Agreement',
'Index of Agreement Refined (dr)', "Watterson's M", 'Mielke-Berry R',
'Nash-Sutcliffe Efficiency', 'Modified Nash-Sutcliffe Efficiency',
'Relative Nash-Sutcliffe Efficiency', 'Kling-Gupta Efficiency (2009)',
'Kling-Gupta Efficiency (2012)', 'Legate-McCabe Efficiency Index',
'Legate-McCabe Index of Agreement', 'Volumetric Efficiency', 'Spectral Angle',
'Spectral Correlation', 'Spectral Information Divergence', 'Spectral Gradient Angle',
'Mean H1 Error', 'Mean Absolute H1 Error', 'Root Mean Square H1 Error', 'Mean H2 Error',
'Mean Absolute H2 Error', 'Root Mean Square H2 Error', 'Mean H3 Error',
'Mean Absolute H3 Error', 'Root Mean Square H3 Error', 'Mean H4 Error',
'Mean Absolute H4 Error', 'Root Mean Square H4 Error', 'Mean H5 Error',
'Mean Absolute H5 Error', 'Root Mean Square H5 Error', 'Mean H6 Error',
'Mean Absolute H6 Error', 'Root Mean Square H6 Error', 'Mean H7 Error',
'Mean Absolute H7 Error', 'Root Mean Square H7 Error', 'Mean H8 Error',
'Mean Absolute H8 Error', 'Root Mean Square H8 Error', 'Mean H10 Error',
'Mean Absolute H10 Error', 'Root Mean Square H10 Error', 'Geometric Mean Difference',
'Mean Variance'
]
metric_abbr = [
'ME', 'MAE', 'MSE', 'MLE', 'MALE', 'MSLE', 'MdE', 'MdAE', 'MdSE', 'ED', 'NED', 'RMSE', 'RMSLE',
'NRMSE (Range)', 'NRMSE (Mean)', 'NRMSE (IQR)', 'IRMSE', 'MASE', 'r2', 'R (Pearson)',
'R (Spearman)', 'ACC', 'MAPE', 'MAPD', 'MAAPE', 'SMAPE1', 'SMAPE2', 'd', 'd1', 'd (Mod.)',
'd (Rel.)', 'dr', 'M', '(MB) R', 'NSE', 'NSE (Mod.)', 'NSE (Rel.)', 'KGE (2009)', 'KGE (2012)',
"E1'", "D1'", 'VE', 'SA', 'SC', 'SID', 'SGA', 'H1 (MHE)', 'H1 (MAHE)', 'H1 (RMSHE)', 'H2 (MHE)',
'H2 (MAHE)', 'H2 (RMSHE)', 'H3 (MHE)', 'H3 (MAHE)', 'H3 (RMSHE)', 'H4 (MHE)', 'H4 (MAHE)',
'H4 (RMSHE)', 'H5 (MHE)', 'H5 (MAHE)', 'H5 (RMSHE)', 'H6 (MHE)', 'H6 (MAHE)', 'H6 (RMSHE)',
'H7 (MHE)', 'H7 (MAHE)', 'H7 (RMSHE)', 'H8 (MHE)', 'H8 (MAHE)', 'H8 (RMSHE)', 'H10 (MHE)',
'H10 (MAHE)', 'H10 (RMSHE)', 'GMD', 'MV'
]
function_list = [
me, mae, mse, mle, male, msle, mde, mdae, mdse, ed, ned, rmse, rmsle, nrmse_range, nrmse_mean,
nrmse_iqr, irmse, mase, r_squared, pearson_r, spearman_r, acc, mape, mapd, maape, smape1,
smape2, d, d1, dmod, drel, dr, watt_m, mb_r, nse, nse_mod, nse_rel, kge_2009, kge_2012,
lm_index, d1_p, ve, sa, sc, sid, sga, h1_mhe, h1_mahe, h1_rmshe, h2_mhe, h2_mahe, h2_rmshe,
h3_mhe, h3_mahe, h3_rmshe, h4_mhe, h4_mahe, h4_rmshe, h5_mhe, h5_mahe, h5_rmshe, h6_mhe,
h6_mahe, h6_rmshe, h7_mhe, h7_mahe, h7_rmshe, h8_mhe, h8_mahe, h8_rmshe, h10_mhe, h10_mahe,
h10_rmshe, g_mean_diff, mean_var,
]
# Assign some properties to each function for ease of use for users
for i in range(len(function_list)):
function_list[i].name = metric_names[i]
function_list[i].abbr = metric_abbr[i]
def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Removes the nan, negative, and inf values in two numpy arrays"""
sim_copy = np.copy(simulated_array)
obs_copy = np.copy(observed_array)
# Checking to see if the vectors are the same length
assert sim_copy.ndim == 1, "The simulated array is not one dimensional."
assert obs_copy.ndim == 1, "The observed array is not one dimensional."
if sim_copy.size != obs_copy.size:
raise RuntimeError("The two ndarrays are not the same size.")
# Treat missing data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain nan values
all_treatment_array = np.ones(obs_copy.size, dtype=bool)
if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_nan = np.isnan(sim_copy)
obs_nan = np.isnan(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_nan] = replace_nan
obs_copy[obs_nan] = replace_nan
warnings.warn("Elements(s) {} contained NaN values in the simulated array and "
"elements(s) {} contained NaN values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_nan)[0],
np.where(obs_nan)[0]),
UserWarning)
else:
# Getting the indices of the nan values, combining them, and informing user.
nan_indices_fcst = ~np.isnan(sim_copy)
nan_indices_obs = ~np.isnan(obs_copy)
all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)
warnings.warn("Row(s) {} contained NaN values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_nan_indices)[0]),
UserWarning)
if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_inf = np.isinf(sim_copy)
obs_inf = np.isinf(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_inf] = replace_inf
obs_copy[obs_inf] = replace_inf
warnings.warn("Elements(s) {} contained Inf values in the simulated array and "
"elements(s) {} contained Inf values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_inf)[0],
np.where(obs_inf)[0]),
UserWarning)
else:
inf_indices_fcst = ~(np.isinf(sim_copy))
inf_indices_obs = ~np.isinf(obs_copy)
all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)
warnings.warn(
"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows "
"are zero indexed).".format(np.where(~all_inf_indices)[0]),
UserWarning
)
# Treat zero data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain zero values
if remove_zero:
if (obs_copy == 0).any() or (sim_copy == 0).any():
zero_indices_fcst = ~(sim_copy == 0)
zero_indices_obs = ~(obs_copy == 0)
all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)
warnings.warn(
"Row(s) {} contained zero values and the row(s) have been removed (Rows are "
"zero indexed).".format(np.where(~all_zero_indices)[0]),
UserWarning
)
# Treat negative data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain negative values
# Ignore runtime warnings from comparing
if remove_neg:
with np.errstate(invalid='ignore'):
obs_copy_bool = obs_copy < 0
sim_copy_bool = sim_copy < 0
if obs_copy_bool.any() or sim_copy_bool.any():
neg_indices_fcst = ~sim_copy_bool
neg_indices_obs = ~obs_copy_bool
all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)
warnings.warn("Row(s) {} contained negative values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_neg_indices)[0]),
UserWarning)
obs_copy = obs_copy[all_treatment_array]
sim_copy = sim_copy[all_treatment_array]
return sim_copy, obs_copy
if __name__ == "__main__":
pass
|
BYU-Hydroinformatics/HydroErr | HydroErr/HydroErr.py | sga | python | def sga(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sgx = observed_array[1:] - observed_array[:observed_array.size - 1]
sgy = simulated_array[1:] - simulated_array[:simulated_array.size - 1]
a = np.dot(sgx, sgy)
b = np.linalg.norm(sgx) * np.linalg.norm(sgy)
return np.arccos(a / b) | Compute the Spectral Gradient Angle (SGA).
.. image:: /pictures/SGA.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral gradient angle measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
SG is the gradient of the simulated or observed time series.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Gradient Angle.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sga(sim, obs)
0.26764286472739834
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166. | train | https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L3773-L3850 | [
"def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,\n remove_neg=False, remove_zero=False):\n \"\"\"Removes the nan, negative, and inf values in two numpy arrays\"\"\"\n sim_copy = np.copy(simulated_array)\n obs_copy = np.copy(observed_array)\n\n # Checking to see if the vectors are the same length\n assert sim_copy.ndim == 1, \"The simulated array is not one dimensional.\"\n assert obs_copy.ndim == 1, \"The observed array is not one dimensional.\"\n\n if sim_copy.size != obs_copy.size:\n raise RuntimeError(\"The two ndarrays are not the same size.\")\n\n # Treat missing data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain nan values\n all_treatment_array = np.ones(obs_copy.size, dtype=bool)\n\n if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_nan = np.isnan(sim_copy)\n obs_nan = np.isnan(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_nan] = replace_nan\n obs_copy[obs_nan] = replace_nan\n\n warnings.warn(\"Elements(s) {} contained NaN values in the simulated array and \"\n \"elements(s) {} contained NaN values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_nan)[0],\n np.where(obs_nan)[0]),\n UserWarning)\n else:\n # Getting the indices of the nan values, combining them, and informing user.\n nan_indices_fcst = ~np.isnan(sim_copy)\n nan_indices_obs = ~np.isnan(obs_copy)\n all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)\n\n warnings.warn(\"Row(s) {} contained NaN values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_nan_indices)[0]),\n UserWarning)\n\n if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_inf = np.isinf(sim_copy)\n obs_inf = np.isinf(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_inf] = replace_inf\n obs_copy[obs_inf] = replace_inf\n\n warnings.warn(\"Elements(s) {} contained Inf values in the simulated array and \"\n \"elements(s) {} contained Inf values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_inf)[0],\n np.where(obs_inf)[0]),\n UserWarning)\n else:\n inf_indices_fcst = ~(np.isinf(sim_copy))\n inf_indices_obs = ~np.isinf(obs_copy)\n all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)\n\n warnings.warn(\n \"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows \"\n \"are zero indexed).\".format(np.where(~all_inf_indices)[0]),\n UserWarning\n )\n\n # Treat zero data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain zero values\n if remove_zero:\n if (obs_copy == 0).any() or (sim_copy == 0).any():\n zero_indices_fcst = ~(sim_copy == 0)\n zero_indices_obs = ~(obs_copy == 0)\n all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)\n\n warnings.warn(\n \"Row(s) {} contained zero values and the row(s) have been removed (Rows are \"\n \"zero indexed).\".format(np.where(~all_zero_indices)[0]),\n UserWarning\n )\n\n # Treat negative data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain negative values\n\n # Ignore runtime warnings from comparing\n if remove_neg:\n with np.errstate(invalid='ignore'):\n obs_copy_bool = obs_copy < 0\n sim_copy_bool = sim_copy < 0\n\n if obs_copy_bool.any() or sim_copy_bool.any():\n neg_indices_fcst = ~sim_copy_bool\n neg_indices_obs = ~obs_copy_bool\n all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)\n\n warnings.warn(\"Row(s) {} contained negative values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_neg_indices)[0]),\n UserWarning)\n\n obs_copy = obs_copy[all_treatment_array]\n sim_copy = sim_copy[all_treatment_array]\n\n return sim_copy, obs_copy\n"
] | # -*- coding: utf-8 -*-
"""
HydroErr contains a library of goodness of fit metrics that measure hydrologic skill.
Each metric is contained in function, and every function has the parameters to treat missing values as
well as remove zero and negative values from the timeseries data.
Each function contains two properties, name and abbr. These can be used in the Hydrostats package when creating tables
and adding metrics to the plots. Link to the hydrostats package: https://github.com/BYU-Hydroinformatics/Hydrostats.
An example of this functionality is shown below.
>>> import HydroErr as he
>>>
>>> he.acc.name
'Anomaly Correlation Coefficient'
>>> he.acc.abbr
'ACC'
"""
from __future__ import division
import numpy as np
from scipy.stats import gmean, rankdata
import warnings
__all__ = ['me', 'mae', 'mse', 'mle', 'male', 'msle', 'mde', 'mdae', 'mdse', 'ed', 'ned', 'rmse',
'rmsle', 'nrmse_range', 'nrmse_mean', 'nrmse_iqr', 'irmse', 'mase', 'r_squared',
'pearson_r', 'spearman_r', 'acc', 'mape', 'mapd', 'maape', 'smape1', 'smape2', 'd', 'd1',
'dmod', 'drel', 'dr', 'watt_m', 'mb_r', 'nse', 'nse_mod', 'nse_rel', 'kge_2009',
'kge_2012', 'lm_index', 'd1_p', 've', 'sa', 'sc', 'sid', 'sga', 'h1_mhe', 'h1_mahe',
'h1_rmshe', 'h2_mhe', 'h2_mahe', 'h2_rmshe', 'h3_mhe', 'h3_mahe', 'h3_rmshe', 'h4_mhe',
'h4_mahe', 'h4_rmshe', 'h5_mhe', 'h5_mahe', 'h5_rmshe', 'h6_mhe', 'h6_mahe', 'h6_rmshe',
'h7_mhe', 'h7_mahe', 'h7_rmshe', 'h8_mhe', 'h8_mahe', 'h8_rmshe', 'h10_mhe', 'h10_mahe',
'h10_rmshe', 'g_mean_diff', 'mean_var']
####################################################################################################
# General and Hydrological Error Metrics #
####################################################################################################
def me(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean error of the simulated and observed data.
.. image:: /pictures/ME.png
**Range:** -inf < MAE < inf, data units, closer to zero is better, indicates bias.
**Notes:** The mean error (ME) measures the difference between the simulated data and the
observed data. For the mean error, a smaller number indicates a better fit to the original
data. Note that if the error is in the form of random noise, the mean error will be very small,
which can skew the accuracy of this metric. ME is cumulative and will be small even if there
are large positive and negative errors that balance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean error value.
Examples
--------
Note that in this example the random noise cancels, leaving a very small ME.
>>> import HydroErr as he
>>> import numpy as np
>>> # Seed for reproducibility
>>> np.random.seed(54839)
>>> x = np.arange(100) / 20
>>> sim = np.sin(x) + 2
>>> obs = sim * (((np.random.rand(100) - 0.5) / 10) + 1)
>>> he.me(sim, obs)
-0.006832220968967168
References
----------
- Fisher, R.A., 1920. A Mathematical Examination of the Methods of Determining the Accuracy of
an Observation by the Mean Error, and by the Mean Square Error. Monthly Notices of the Royal
Astronomical Society 80 758 - 770.
"""
# Treating missing values
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero)
return np.mean(simulated_array - observed_array)
def mae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute error of the simulated and observed data.
.. image:: /pictures/MAE.png
**Range:** 0 ≤ MAE < inf, data units, smaller is better.
**Notes:** The ME measures the absolute difference between the simulated data and the observed
data. For the mean abolute error, a smaller number indicates a better fit to the original data.
Also note that random errors do not cancel. Also referred to as an L1-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute error value.
References
----------
- Willmott, Cort J., and Kenji Matsuura. “Advantages of the Mean Absolute Error (MAE) over the
Root Mean Square Error (RMSE) in Assessing Average Model Performance.” Climate Research 30,
no. 1 (2005): 79–82.
- Willmott, Cort J., and Kenji Matsuura. “On the Use of Dimensioned Measures of Error to
Evaluate the Performance of Spatial Interpolators.” International Journal of Geographical
Information Science 20, no. 1 (2006): 89–102.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mae(sim, obs)
0.5666666666666665
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean(np.absolute(simulated_array - observed_array))
def mse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared error of the simulated and observed data.
.. image:: /pictures/MSE.png
**Range:** 0 ≤ MSE < inf, data units squared, smaller is better.
**Notes:** Random errors do not cancel, highlights larger errors, also referred to as a
squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mse(sim, obs)
0.4333333333333333
References
----------
- Wang, Zhou, and Alan C. Bovik. “Mean Squared Error: Love It or Leave It? A New Look at Signal
Fidelity Measures.” IEEE Signal Processing Magazine 26, no. 1 (2009): 98–117.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean((simulated_array - observed_array) ** 2)
def mle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean log error of the simulated and observed data.
.. image:: /pictures/MLE.png
**Range:** -inf < MLE < inf, data units, closer to zero is better.
**Notes** Same as the mean erro (ME) only use log ratios as the error term. Limits the impact of outliers, more
evenly weights high and low data values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mle(sim, obs)
0.002961767058151136
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(sim_log - obs_log)
def male(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean absolute log error of the simulated and observed data.
.. image:: /pictures/MALE.png
**Range:** 0 ≤ MALE < inf, data units squared, smaller is better.
**Notes** Same as MAE only use log ratios as the error term. Limits the impact of outliers,
more evenly weights high and low flows.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.male(sim, obs), 6)
0.090417
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(np.abs(sim_log - obs_log))
def msle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared log error of the simulated and observed data.
.. image:: /pictures/MSLE.png
**Range:** 0 ≤ MSLE < inf, data units squared, smaller is better.
**Notes** Same as the mean squared error (MSE) only use log ratios as the error term. Limits
the impact of outliers, more evenly weights high and low values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.msle(sim, obs), 6)
0.010426
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean((sim_log - obs_log) ** 2)
def mde(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median error (MdE) between the simulated and observed data.
.. image:: /pictures/MdE.png
**Range** -inf < MdE < inf, closer to zero is better.
**Notes** This metric indicates bias. It is similar to the mean error (ME), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mde(sim, obs)
-0.10000000000000009
Returns
-------
float
The median error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(simulated_array - observed_array)
def mdae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median absolute error (MdAE) between the simulated and observed data.
.. image:: /pictures/MdAE.png
**Range** 0 ≤ MdAE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean absolute error (MAE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdae(sim, obs)
0.75
Returns
-------
float
The median absolute error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(np.abs(simulated_array - observed_array))
def mdse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median squared error (MdSE) between the simulated and observed data.
.. image:: /pictures/MdSE.png
**Range** 0 ≤ MdSE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean squared error (MSE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdse(sim, obs)
0.625
Returns
-------
float
The median squared error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median((simulated_array - observed_array) ** 2)
def ed(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Euclidean distance between predicted and observed values in vector space.
.. image:: /pictures/ED.png
**Range** 0 ≤ ED < inf, smaller is better.
**Notes** Also sometimes referred to as the L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ed(sim, obs)
1.63707055437449
Returns
-------
float
The euclidean distance error value.
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.linalg.norm(observed_array - simulated_array)
def ned(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the normalized Euclidian distance between the simulated and observed data in vector
space.
.. image:: /pictures/NED.png
**Range** 0 ≤ NED < inf, smaller is better.
**Notes** Also sometimes referred to as the squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The normalized euclidean distance value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ned(sim, obs)
0.2872053604165771
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array / np.mean(observed_array)
b = simulated_array / np.mean(simulated_array)
return np.linalg.norm(a - b)
def rmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square error between the simulated and observed data.
.. image:: /pictures/RMSE.png
**Range** 0 ≤ RMSE < inf, smaller is better.
**Notes:** The standard deviation of the residuals. A lower spread indicates that the points
are better concentrated around the line of best fit (linear). Random errors do not cancel.
This metric will highlights larger errors.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.rmse(sim, obs)
0.668331255192114
References
----------
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.sqrt(np.mean((simulated_array - observed_array) ** 2))
def rmsle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square log error between the simulated and observed data.
.. image:: /pictures/RMSLE.png
**Range:** 0 ≤ RMSLE < inf. Smaller is better, and it does not indicate bias.
**Notes:** Random errors do not cancel while using this metric. This metric limits the
impact of outliers by more evenly weighting high and low values. To calculate the log values,
each value in the observed and simulated array is increased by one unit in order to avoid
run-time errors and nan values (function np.log1p).
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square log error value.
Examples
--------
Notice that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.rmsle(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
"""
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf, remove_neg=remove_neg,
remove_zero=remove_zero)
return np.sqrt(np.mean(np.power(np.log1p(simulated_array) - np.log1p(observed_array), 2)))
def nrmse_range(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the range normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Range.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the range of the observed time series (x).
Normalizing allows comparison between data sets with different scales. The NRMSErange is the
most sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The range normalized root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_range(sim, obs)
0.0891108340256152
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_max = np.max(observed_array)
obs_min = np.min(observed_array)
return rmse_value / (obs_max - obs_min)
def nrmse_mean(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Mean.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the mean of the observed time series (x).
Normalizing allows comparison between data sets with different scales.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_mean(sim, obs)
0.11725109740212526
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_mean = np.mean(observed_array)
return rmse_value / obs_mean
def nrmse_iqr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the IQR normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_IQR.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the interquartile range of the observed time
series (x). Normalizing allows comparison between data sets with different scales.
The NRMSEquartile is the least sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The IQR normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_iqr(sim, obs)
0.2595461185212093
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
q1 = np.percentile(observed_array, 25)
q3 = np.percentile(observed_array, 75)
iqr = q3 - q1
return rmse_value / iqr
def irmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the inertial root mean square error (IRMSE) between the simulated and observed data.
.. image:: /pictures/IRMSE.png
**Range:** 0 ≤ IRMSE < inf, lower is better.
**Notes:** This metric is the RMSE devided by by the standard deviation of the gradient of the
observed timeseries data. This metric is meant to be help understand the ability of the model
to predict changes in observation.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The inertial root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.irmse(sim, obs)
0.14572738134831856
References
----------
- Daga, M., Deo, M.C., 2009. Alternative data-driven methods to estimate wind from waves by
inverse modeling. Natural Hazards 49(2) 293-310.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Getting the gradient of the observed data
obs_len = observed_array.size
obs_grad = observed_array[1:obs_len] - observed_array[0:obs_len - 1]
# Standard deviation of the gradient
obs_grad_std = np.std(obs_grad, ddof=1)
# Divide RMSE by the standard deviation of the gradient of the observed data
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
return rmse_value / obs_grad_std
def mase(simulated_array, observed_array, m=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute scaled error between the simulated and observed data.
.. image:: /pictures/MASE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
m: int
If given, indicates the seasonal period m. If not given, the default is 1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute scaled error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mase(sim, obs)
0.17341040462427745
References
----------
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
start = m
end = simulated_array.size - m
a = np.mean(np.abs(simulated_array - observed_array))
b = np.abs(observed_array[start:observed_array.size] - observed_array[:end])
return a / (np.sum(b) / end)
def pearson_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the pearson correlation coefficient.
.. image:: /pictures/R_pearson.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The pearson r coefficient measures linear correlation. It is sensitive to outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Pearson correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.pearson_r(sim, obs)
0.9610793632835262
References
----------
- Pearson, K. (1895). Note on regression and inheritance in the case of two parents.
Proceedings of the Royal Society of London, 58, 240-242.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
top = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1 = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2 = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
return top / (bot1 * bot2)
def spearman_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the spearman rank correlation coefficient.
.. image:: /pictures/R_spearman.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The spearman r coefficient measures the monotonic relation between simulated and
observed data. Because it uses a nonparametric measure of rank correlation, it is less sensitive
to outliers compared to the Pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spearman rank correlation coefficient.
Examples
----------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.spearman_r(sim, obs)
0.942857142857143
References
----------
- Spearman C (1904). "The proof and measurement of association between two things". American
Journal of Psychology. 15: 72–101. doi:10.2307/1412159
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rank_sim = rankdata(simulated_array)
rank_obs = rankdata(observed_array)
mean_rank_sim = np.mean(rank_sim)
mean_rank_obs = np.mean(rank_obs)
top = np.mean((rank_obs - mean_rank_obs) * (rank_sim - mean_rank_sim))
bot = np.sqrt(
np.mean((rank_obs - mean_rank_obs) ** 2) * np.mean((rank_sim - mean_rank_sim) ** 2))
return top / bot
def r_squared(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Coefficient of Determination (r2).
.. image:: /pictures/r2.png
**Range:** 0 ≤ r2 ≤ 1. 1 indicates perfect correlation, 0 indicates complete randomness.
**Notes:** The Coefficient of Determination measures the linear relation between simulated and
observed data. Because it is the pearson correlation coefficient squared, it is more heavily
affected by outliers than the pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The coefficient of determination (R^2).
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.r_squared(sim, obs)
0.9236735425294681
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array - np.mean(observed_array)
b = simulated_array - np.mean(simulated_array)
return (np.sum(a * b)) ** 2 / (np.sum(a ** 2) * np.sum(b ** 2))
def acc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the anomaly correlation coefficient (ACC).
.. image:: /pictures/ACC.png
**Range:** -1 ≤ ACC ≤ 1. -1 indicates perfect negative correlation of the variation
pattern of the anomalies, 0 indicates complete randomness of the variation patterns of the
anomalies, 1 indicates perfect correlation of the variation pattern of the anomalies.
**Notes:** Common measure in the verification of spatial fields. Measures the correlation
between the variation pattern of the simulated data compared to the observed data.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The anomaly correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.acc(sim, obs)
0.8008994694029383
References
----------
- Langland, Rolf H., and Ryan N. Maue. “Recent Northern Hemisphere Mid-Latitude Medium-Range
Deterministic Forecast Skill.” Tellus A: Dynamic Meteorology and Oceanography 64,
no. 1 (2012): 17531.
- Miyakoda, K., G. D. Hembree, R. F. Strickler, and I. Shulman. “Cumulative Results of Extended
Forecast Experiments I. Model Performance for Winter Cases.” Monthly Weather Review 100, no.
12(1972): 836–55.
- Murphy, Allan H., and Edward S. Epstein. “Skill Scores and Correlation Coefficients in Model
Verification.” Monthly Weather Review 117, no. 3 (1989): 572–82.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - np.mean(simulated_array)
b = observed_array - np.mean(observed_array)
c = np.std(observed_array, ddof=1) * np.std(simulated_array, ddof=1) * simulated_array.size
return np.dot(a, b / c)
def mape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the mean absolute percentage error (MAPE).
.. image:: /pictures/MAPE.png
**Range:** 0% ≤ MAPE ≤ inf. 0% indicates perfect correlation, a larger error indicates a
larger percent error in the data.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
c = 100 / simulated_array.size
return c * np.sum(b)
def mapd(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the mean absolute percentage deviation (MAPD).
.. image:: /pictures/MAPD.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage deviation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mapd(sim, obs)
0.10526315789473682
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(np.abs(observed_array))
return a / b
def maape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the Mean Arctangent Absolute Percentage Error (MAAPE).
.. image:: /pictures/MAAPE.png
**Range:** 0 ≤ MAAPE < π/2, does not indicate bias, smaller is better.
**Notes:** Represents the mean absolute error as a percentage of the observed values. Handles
0s in the observed data. This metric is not as biased as MAPE by under-over predictions.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean arctangent absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
- Kim, S., Kim, H., 2016. A new metric of absolute percentage error for intermittent demand
forecasts. International Journal of Forecasting 32(3) 669-679.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
return np.mean(np.arctan(b))
def smape1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (1) (SMAPE1).
.. image:: /pictures/SMAPE1.png
**Range:** 0 ≤ SMAPE1 < 100%, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (1).
Examples
--------
Note that if we switch the simulated and observed arrays the result is the same
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape1(sim, obs)
5.871915694397428
>>> he.smape1(obs, sim)
5.871915694397428
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 100 / simulated_array.size
b = np.abs(simulated_array - observed_array)
c = np.abs(simulated_array) + np.abs(observed_array)
return a * np.sum(b / c)
def smape2(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (2) (SMAPE2).
.. image:: /pictures/SMAPE2.png
**Range:** 0 ≤ SMAPE1 < 200%, does not indicate bias, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE with only positive metric values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (2).
Examples
--------
Note that switching the simulated and observed arrays yields the same results
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape2(sim, obs)
11.743831388794856
>>> he.smape2(obs, sim)
11.743831388794856
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = (simulated_array + observed_array) / 2
c = 100 / simulated_array.size
return c * np.sum(np.abs(a / b))
def d(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d).
.. image:: /pictures/d.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d(sim, obs)
0.978477353035657
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (observed_array - simulated_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
return 1 - (np.sum(a) / np.sum((b + c) ** 2))
def d1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d1).
.. image:: /pictures/d1.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric. Compared
to the other index of agreement (d) it has a reduced impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (d1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1(sim, obs)
0.8434782608695652
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
obs_mean = np.mean(observed_array)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.abs(simulated_array - obs_mean)
c = np.abs(observed_array - obs_mean)
return 1 - np.sum(a) / np.sum(b + c)
def dr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the refined index of agreement (dr).
.. image:: /pictures/dr.png
**Range:** -1 ≤ dr < 1, does not indicate bias, larger is better.
**Notes:** Reformulation of Willmott’s index of agreement. This metric was created to address
issues in the index of agreement and the Nash-Sutcliffe efficiency metric. Meant to be a
flexible metric for use in climatology.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The refined index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dr(sim, obs)
0.847457627118644
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = 2 * np.sum(np.abs(observed_array - observed_array.mean()))
if a <= b:
return 1 - (a / b)
else:
return (b / a) - 1
def drel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the relative index of agreement (drel).
.. image:: /pictures/drel.png
**Range:** 0 ≤ drel < 1, does not indicate bias, larger is better.
**Notes:** Instead of absolute differences, this metric uses relative differences.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.drel(sim, obs)
0.9740868625579597
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = ((simulated_array - observed_array) / observed_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = ((b + c) / np.mean(observed_array)) ** 2
return 1 - (np.sum(a) / np.sum(e))
def dmod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the modified index of agreement (dmod).
.. image:: /pictures/dmod.png
**Range:** 0 ≤ dmod < 1, does not indicate bias, larger is better.
**Notes:** When j=1, this metric is the same as d1. As j becomes larger, outliers have a larger
impact on the value.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
Optional input indicating the j values desired. A higher j places more emphasis on
outliers. j is 1 by default.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified index of agreement.
Examples
--------
Note that using the default is the same as calculating the d1 metric. Changing the value of j
modification of the metric.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dmod(sim, obs) # Same as d1
0.8434782608695652
>>> he.dmod(sim, obs, j=1.5)
0.9413310986805733
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = (b + c) ** j
return 1 - (np.sum(a) / np.sum(e))
def watt_m(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute Watterson's M (M).
.. image:: /pictures/M.png
**Range:** -1 ≤ M < 1, does not indicate bias, larger is better.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
Watterson's M value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.watt_m(sim, obs)
0.8307913876595929
References
----------
- Watterson, I.G., 1996. Non‐dimensional measures of climate model performance. International
Journal of Climatology 16(4) 379-391.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 2 / np.pi
b = np.mean((simulated_array - observed_array) ** 2) # MSE
c = np.std(observed_array, ddof=1) ** 2 + np.std(simulated_array, ddof=1) ** 2
e = (np.mean(simulated_array) - np.mean(observed_array)) ** 2
f = c + e
return a * np.arcsin(1 - (b / f))
def mb_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute Mielke-Berry R value (MB R).
.. image:: /pictures/MB_R.png
**Range:** 0 ≤ MB R < 1, does not indicate bias, larger is better.
**Notes:** Compares prediction to probability it arose by chance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Mielke-Berry R value.
Notes
-----
If a more optimized version is desired, the `numba package <http://numba.pydata.org/doc.html>`_ can be implemented
for a much more optimized performance when computing this metric. An example is given below.
>>> from numba import njit, prange
>>> @njit(parallel=True, fastmath=True)
>>> def mb_par_fastmath(pred, obs): # uses LLVM compiler
>>> assert pred.size == obs.size
>>> n = pred.size
>>> tot = 0.0
>>> mae = 0.0
>>> for i in range(n):
>>> for j in prange(n):
>>> tot += abs(pred[i] - obs[j])
>>> mae += abs(pred[i] - obs[i])
>>> mae = mae / n
>>> mb = 1 - ((n ** 2) * mae / tot)
>>>
>>> return mb
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mb_r(sim, obs)
0.7726315789473684
References
----------
- Berry, K.J., Mielke, P.W., 1988. A Generalization of Cohen's Kappa Agreement Measure to
Interval Measurement and Multiple Raters. Educational and Psychological Measurement 48(4)
921-933.
- Mielke, P.W., Berry, K.J., 2007. Permutation methods: a distance function approach.
Springer Science & Business Media.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Calculate metric
n = simulated_array.size
tot = 0.0
for i in range(n):
tot = tot + np.sum(np.abs(simulated_array - observed_array[i]))
mae_val = np.sum(np.abs(simulated_array - observed_array)) / n
mb = 1 - ((n ** 2) * mae_val / tot)
return mb
def nse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Nash-Sutcliffe Efficiency.
.. image:: /pictures/NSE.png
**Range:** -inf < NSE < 1, does not indicate bias, larger is better.
**Notes:** The Nash-Sutcliffe efficiency metric compares prediction values to naive predictions
(i.e. average value). One major flaw of this metric is that it punishes a higher variance in
the observed values (denominator). This metric is analogous to the mean absolute error skill
score (MAESS) using the mean flow as a benchmark.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Nash-Sutcliffe Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse(sim, obs)
0.922093023255814
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
- McCuen, R.H., Knight, Z., Cutter, A.G., 2006. Evaluation of the Nash-Sutcliffe Efficiency
Index. Journal of Hydraulic Engineering.
- Nash, J.E., Sutcliffe, J.V., 1970. River flow forecasting through conceptual models part
I — A discussion of principles. Journal of Hydrology 282-290.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** 2
b = (np.abs(observed_array - np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def nse_mod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the modified Nash-Sutcliffe efficiency (NSE mod).
.. image:: /pictures/NSEmod.png
**Range:** -inf < NSE (mod) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
If given, sets the value of j to the input. j is 1 by default. A higher j gives more
emphasis to outliers
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_mod(sim, obs)
0.6949152542372882
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = (np.abs(observed_array - np.mean(observed_array))) ** j
return 1 - (np.sum(a) / np.sum(b))
def nse_rel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the relative Nash-Sutcliffe efficiency (NSE rel).
.. image:: /pictures/NSErel.png
**Range:** -inf < NSE (rel) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_rel(sim, obs)
0.9062004687708474
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs((simulated_array - observed_array) / observed_array)) ** 2
b = (np.abs((observed_array - np.mean(observed_array)) / np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def kge_2009(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""Compute the Kling-Gupta efficiency (2009).
.. image:: /pictures/KGE_2009.png
**Range:** -inf < KGE (2009) < 1, larger is better.
**Notes:** Gupta et al. (2009) created this metric to demonstrate the relative importance of
the three components of the NSE, which are correlation, bias and variability. This was done
with hydrologic modeling as the context. This metric is meant to address issues with the NSE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), Alpha, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, alpha, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2009) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2009(sim, obs)
0.912223072345668
>>> he.kge_2009(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.927910707932087, 1.0058823529411764, 0.9181073779138655)
References
----------
- Gupta, H. V., Kling, H., Yilmaz, K. K., & Martinez, G. F. (2009). Decomposition of the mean
squared error and NSE performance criteria: Implications for improving hydrological modelling.
Journal of Hydrology, 377(1-2), 80-91.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array, ddof=1)
obs_sigma = np.std(observed_array, ddof=1)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
if obs_mean != 0:
beta = sim_mean / obs_mean
else:
beta = np.nan
# Relative variability between simulated and observed values
if obs_sigma != 0:
alpha = sim_sigma / obs_sigma
else:
alpha = np.nan
if not np.isnan(beta) and not np.isnan(alpha):
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (alpha - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Alpha is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, alpha, beta, kge
else:
return kge
def kge_2012(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""
Compute the Kling-Gupta efficiency (2012).
.. image:: /pictures/KGE_2012.png
**Range:** -inf < KGE (2012) < 1, does not indicate bias, larger is better.
**Notes:** The modified version of the KGE (2009). Kling proposed this version to avoid
cross-correlation between bias and variability ratios.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), gamma, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, gamma, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2012) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2012(sim, obs)
0.9122230723456678
>>> he.kge_2012(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.9224843295231272, 1.0058823529411764, 0.9132923608280753)
References
----------
- Kling, H., Fuchs, M., & Paulin, M. (2012). Runoff conditions in the upper Danube basin under
an ensemble of climate change scenarios. Journal of Hydrology, 424, 264-277.
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array)
obs_sigma = np.std(observed_array)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
beta = sim_mean / obs_mean
# CV is the coefficient of variation (standard deviation / mean)
sim_cv = sim_sigma / sim_mean
obs_cv = obs_sigma / obs_mean
# Variability Ratio, or the ratio of simulated CV to observed CV
gam = sim_cv / obs_cv
if obs_mean != 0 and obs_sigma != 0 and sim_mean != 0:
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (gam - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
if sim_mean == 0:
warnings.warn(
'Warning: The simulated data mean is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, gam, beta, kge
else:
return kge
def lm_index(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""
Compute the Legate-McCabe Efficiency Index.
.. image:: /pictures/E1p.png
**Range:** 0 ≤ E1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.lm_index(sim, obs)
0.6949152542372882
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
mean_obs = np.mean(observed_array)
if obs_bar_p is not None:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def d1_p(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""Compute the Legate-McCabe Index of Agreement.
.. image:: /pictures/D1p.png
**Range:** 0 ≤ d1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1_p(sim, obs)
0.8434782608695652
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
if obs_bar_p is not None:
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - obs_bar_p) + np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
mean_obs = np.mean(observed_array)
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - mean_obs) + np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def ve(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Volumetric Efficiency (VE).
.. image:: /pictures/VE.png
**Range:** 0 ≤ VE < 1 smaller is better, does not indicate bias.
**Notes:** Represents the error as a percentage of flow.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Volumetric Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ve(sim, obs)
0.8947368421052632
References
----------
- Criss, R.E., Winston, W.E., 2008. Do Nash values have value? Discussion and alternate
proposals. Hydrological Processes 22(14) 2723.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(observed_array)
return 1 - (a / b)
def sa(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Angle (SA).
.. image:: /pictures/SA.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral angle metric measures the angle between the two vectors in hyperspace.
It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Angle value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sa(sim, obs)
0.10816831366492945
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(simulated_array, observed_array)
b = np.linalg.norm(simulated_array) * np.linalg.norm(observed_array)
return np.arccos(a / b)
def sc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Correlation (SC).
.. image:: /pictures/SC.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral correlation metric measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Correlation value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sc(sim, obs)
0.27991341383646606
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(observed_array - np.mean(observed_array), simulated_array - np.mean(simulated_array))
b = np.linalg.norm(observed_array - np.mean(observed_array))
c = np.linalg.norm(simulated_array - np.mean(simulated_array))
e = b * c
return np.arccos(a / e)
def sid(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Information Divergence (SID).
.. image:: /pictures/SID.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral information divergence measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral information divergence value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sid(sim, obs)
0.03517616895318012
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
first = (observed_array / np.mean(observed_array)) - (
simulated_array / np.mean(simulated_array))
second1 = np.log10(observed_array) - np.log10(np.mean(observed_array))
second2 = np.log10(simulated_array) - np.log10(np.mean(simulated_array))
return np.dot(first, second1 - second2)
####################################################################################################
# H Metrics: Methods from Tornqvist L, Vartia P, and Vartia YO. (1985) #
####################################################################################################
def h1_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the H1 mean error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mhe(sim, obs)
0.002106551840594386
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(h)
def h1_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H1 absolute error.
.. image:: /pictures/H1.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The H1 absolute error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mahe(sim, obs)
0.11639226612630865
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(np.abs(h))
def h1_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H1 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean squared H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_rmshe(sim, obs)
0.12865571253672756
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.sqrt(np.mean(h ** 2))
def h2_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean error.
.. image:: /pictures/H2.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mhe(sim, obs)
-0.015319829424307036
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(h)
def h2_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean absolute error.
.. image:: /pictures/H2.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mahe(sim, obs)
0.11997591408039167
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(np.abs(h))
def h2_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_rmshe(sim, obs)
0.1373586680669673
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.sqrt(np.mean(h ** 2))
def h3_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 mean error.
.. image:: /pictures/H3.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mhe(sim, obs)
-0.006322019630356533
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(h)
def h3_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H3 mean absolute error.
.. image:: /pictures/H3.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mahe(sim, obs)
0.11743831388794855
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(np.abs(h))
def h3_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 root mean square error.
.. image:: /pictures/H3.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.sqrt(np.mean(h ** 2))
def h4_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mhe(sim, obs)
-0.0064637371129817
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(h)
def h4_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H4 mean absolute error.
.. image:: /pictures/H4.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mahe(sim, obs)
0.11781032209144082
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(np.abs(h))
def h4_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_rmshe(sim, obs)
0.13200901963465006
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.sqrt(np.mean(h ** 2))
def h5_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean error.
.. image:: /pictures/H5.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mhe(sim, obs)
-0.006606638791856322
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(h)
def h5_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean absolute error.
.. image:: /pictures/H5.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mahe(sim, obs)
0.11818409010335018
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(np.abs(h))
def h5_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 root mean square error.
.. image:: /pictures/H5.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_rmshe(sim, obs)
0.13254476469410933
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h6_mhe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H6 mean error.
.. image:: /pictures/H6.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mhe(sim, obs)
-0.006322019630356514
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(h)
def h6_mahe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""Compute the H6 mean absolute error.
.. image:: /pictures/H6.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mahe(sim, obs)
0.11743831388794852
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(np.abs(h))
def h6_rmshe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the H6 root mean square error.
.. image:: /pictures/H6.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h7_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean error.
.. image:: /pictures/H7.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mhe(sim, obs)
0.0026331898007430263
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(h)
def h7_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean absolute error.
.. image:: /pictures/H7.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mahe(sim, obs)
0.14549033265788583
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(np.abs(h))
def h7_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 root mean square error.
.. image:: /pictures/H7.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_rmshe(sim, obs)
0.16081964067090945
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
def h8_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H8 mean error.
.. image:: /pictures/H8.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mhe(sim, obs)
0.0018056158633666466
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(h)
def h8_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 mean absolute error.
.. image:: /pictures/H8.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mahe(sim, obs)
0.099764799536836
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(np.abs(h))
def h8_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 root mean square error.
.. image:: /pictures/H8.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_rmshe(sim, obs)
0.11027632503148076
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
# def h9(simulated_array, observed_array, h_type='mhe', k=1):
# h = (simulated_array / observed_array - 1) / \
# np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
# if h_type == 'mhe':
# return h.mean()
# elif h_type == 'ahe':
# return np.abs(h).mean()
# elif h_type == 'rmshe':
# return np.sqrt((h**2).mean())
# else:
# raise RuntimeError("The three types available are 'mhe', 'ahe', and 'rmshe'.")
def h10_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean error.
.. image:: /pictures/H10.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h10_mhe(sim, obs)
-0.0012578676058971154
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(h)
def h10_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean absolute error.
.. image:: /pictures/H10.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_mahe(sim, obs), 6)
0.094636
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(np.abs(h))
def h10_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 root mean square error.
.. image:: /pictures/H10.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_rmshe(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.sqrt(np.mean(h ** 2))
###################################################################################################
# Statistical Error Metrics for Distribution Testing #
###################################################################################################
def g_mean_diff(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the geometric mean difference.
.. image:: /pictures/GMD.png
**Range:**
**Notes:** For the difference of geometric means, the geometric mean is computed for each of
two samples then their difference is taken.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The geometric mean difference value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.g_mean_diff(sim, obs)
0.988855412098022
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.exp(gmean(sim_log) - gmean(obs_log))
def mean_var(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the mean variance.
.. image:: /pictures/MV.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean variance.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.mean_var(sim, obs), 6)
0.010641
References
----------
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.var(np.log1p(observed_array) - np.log1p(simulated_array))
####################################################################################################
# HELPER FUNCTIONS AND API INFORMATION #
####################################################################################################
metric_names = [
'Mean Error', 'Mean Absolute Error', 'Mean Squared Error', 'Mean Log Error',
'Mean Absolute Log Error', 'Mean Squared Log Error', 'Median Error', 'Median Absolute Error',
'Median Squared Error', 'Eclidean Distance', 'Normalized Eclidean Distance',
'Root Mean Square Error', 'Root Mean Squared Log Error',
'Normalized Root Mean Square Error - Range', 'Normalized Root Mean Square Error - Mean',
'Normalized Root Mean Square Error - IQR', 'Inertial Root Mean Square Error',
'Mean Absolute Scaled Error', 'Coefficient of Determination', 'Pearson Correlation Coefficient',
'Spearman Rank Correlation Coefficient', 'Anomaly Correlation Coefficient',
'Mean Absolute Percentage Error', 'Mean Absolute Percentage Deviation',
'Mean Arctangent Absolute Percentage Error', 'Symmetric Mean Absolute Percentage Error (1)',
'Symmetric Mean Absolute Percentage Error (2)', 'Index of Agreement (d)',
'Index of Agreement (d1)', 'Modified Index of Agreement', 'Relative Index of Agreement',
'Index of Agreement Refined (dr)', "Watterson's M", 'Mielke-Berry R',
'Nash-Sutcliffe Efficiency', 'Modified Nash-Sutcliffe Efficiency',
'Relative Nash-Sutcliffe Efficiency', 'Kling-Gupta Efficiency (2009)',
'Kling-Gupta Efficiency (2012)', 'Legate-McCabe Efficiency Index',
'Legate-McCabe Index of Agreement', 'Volumetric Efficiency', 'Spectral Angle',
'Spectral Correlation', 'Spectral Information Divergence', 'Spectral Gradient Angle',
'Mean H1 Error', 'Mean Absolute H1 Error', 'Root Mean Square H1 Error', 'Mean H2 Error',
'Mean Absolute H2 Error', 'Root Mean Square H2 Error', 'Mean H3 Error',
'Mean Absolute H3 Error', 'Root Mean Square H3 Error', 'Mean H4 Error',
'Mean Absolute H4 Error', 'Root Mean Square H4 Error', 'Mean H5 Error',
'Mean Absolute H5 Error', 'Root Mean Square H5 Error', 'Mean H6 Error',
'Mean Absolute H6 Error', 'Root Mean Square H6 Error', 'Mean H7 Error',
'Mean Absolute H7 Error', 'Root Mean Square H7 Error', 'Mean H8 Error',
'Mean Absolute H8 Error', 'Root Mean Square H8 Error', 'Mean H10 Error',
'Mean Absolute H10 Error', 'Root Mean Square H10 Error', 'Geometric Mean Difference',
'Mean Variance'
]
metric_abbr = [
'ME', 'MAE', 'MSE', 'MLE', 'MALE', 'MSLE', 'MdE', 'MdAE', 'MdSE', 'ED', 'NED', 'RMSE', 'RMSLE',
'NRMSE (Range)', 'NRMSE (Mean)', 'NRMSE (IQR)', 'IRMSE', 'MASE', 'r2', 'R (Pearson)',
'R (Spearman)', 'ACC', 'MAPE', 'MAPD', 'MAAPE', 'SMAPE1', 'SMAPE2', 'd', 'd1', 'd (Mod.)',
'd (Rel.)', 'dr', 'M', '(MB) R', 'NSE', 'NSE (Mod.)', 'NSE (Rel.)', 'KGE (2009)', 'KGE (2012)',
"E1'", "D1'", 'VE', 'SA', 'SC', 'SID', 'SGA', 'H1 (MHE)', 'H1 (MAHE)', 'H1 (RMSHE)', 'H2 (MHE)',
'H2 (MAHE)', 'H2 (RMSHE)', 'H3 (MHE)', 'H3 (MAHE)', 'H3 (RMSHE)', 'H4 (MHE)', 'H4 (MAHE)',
'H4 (RMSHE)', 'H5 (MHE)', 'H5 (MAHE)', 'H5 (RMSHE)', 'H6 (MHE)', 'H6 (MAHE)', 'H6 (RMSHE)',
'H7 (MHE)', 'H7 (MAHE)', 'H7 (RMSHE)', 'H8 (MHE)', 'H8 (MAHE)', 'H8 (RMSHE)', 'H10 (MHE)',
'H10 (MAHE)', 'H10 (RMSHE)', 'GMD', 'MV'
]
function_list = [
me, mae, mse, mle, male, msle, mde, mdae, mdse, ed, ned, rmse, rmsle, nrmse_range, nrmse_mean,
nrmse_iqr, irmse, mase, r_squared, pearson_r, spearman_r, acc, mape, mapd, maape, smape1,
smape2, d, d1, dmod, drel, dr, watt_m, mb_r, nse, nse_mod, nse_rel, kge_2009, kge_2012,
lm_index, d1_p, ve, sa, sc, sid, sga, h1_mhe, h1_mahe, h1_rmshe, h2_mhe, h2_mahe, h2_rmshe,
h3_mhe, h3_mahe, h3_rmshe, h4_mhe, h4_mahe, h4_rmshe, h5_mhe, h5_mahe, h5_rmshe, h6_mhe,
h6_mahe, h6_rmshe, h7_mhe, h7_mahe, h7_rmshe, h8_mhe, h8_mahe, h8_rmshe, h10_mhe, h10_mahe,
h10_rmshe, g_mean_diff, mean_var,
]
# Assign some properties to each function for ease of use for users
for i in range(len(function_list)):
function_list[i].name = metric_names[i]
function_list[i].abbr = metric_abbr[i]
def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Removes the nan, negative, and inf values in two numpy arrays"""
sim_copy = np.copy(simulated_array)
obs_copy = np.copy(observed_array)
# Checking to see if the vectors are the same length
assert sim_copy.ndim == 1, "The simulated array is not one dimensional."
assert obs_copy.ndim == 1, "The observed array is not one dimensional."
if sim_copy.size != obs_copy.size:
raise RuntimeError("The two ndarrays are not the same size.")
# Treat missing data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain nan values
all_treatment_array = np.ones(obs_copy.size, dtype=bool)
if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_nan = np.isnan(sim_copy)
obs_nan = np.isnan(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_nan] = replace_nan
obs_copy[obs_nan] = replace_nan
warnings.warn("Elements(s) {} contained NaN values in the simulated array and "
"elements(s) {} contained NaN values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_nan)[0],
np.where(obs_nan)[0]),
UserWarning)
else:
# Getting the indices of the nan values, combining them, and informing user.
nan_indices_fcst = ~np.isnan(sim_copy)
nan_indices_obs = ~np.isnan(obs_copy)
all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)
warnings.warn("Row(s) {} contained NaN values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_nan_indices)[0]),
UserWarning)
if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_inf = np.isinf(sim_copy)
obs_inf = np.isinf(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_inf] = replace_inf
obs_copy[obs_inf] = replace_inf
warnings.warn("Elements(s) {} contained Inf values in the simulated array and "
"elements(s) {} contained Inf values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_inf)[0],
np.where(obs_inf)[0]),
UserWarning)
else:
inf_indices_fcst = ~(np.isinf(sim_copy))
inf_indices_obs = ~np.isinf(obs_copy)
all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)
warnings.warn(
"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows "
"are zero indexed).".format(np.where(~all_inf_indices)[0]),
UserWarning
)
# Treat zero data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain zero values
if remove_zero:
if (obs_copy == 0).any() or (sim_copy == 0).any():
zero_indices_fcst = ~(sim_copy == 0)
zero_indices_obs = ~(obs_copy == 0)
all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)
warnings.warn(
"Row(s) {} contained zero values and the row(s) have been removed (Rows are "
"zero indexed).".format(np.where(~all_zero_indices)[0]),
UserWarning
)
# Treat negative data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain negative values
# Ignore runtime warnings from comparing
if remove_neg:
with np.errstate(invalid='ignore'):
obs_copy_bool = obs_copy < 0
sim_copy_bool = sim_copy < 0
if obs_copy_bool.any() or sim_copy_bool.any():
neg_indices_fcst = ~sim_copy_bool
neg_indices_obs = ~obs_copy_bool
all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)
warnings.warn("Row(s) {} contained negative values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_neg_indices)[0]),
UserWarning)
obs_copy = obs_copy[all_treatment_array]
sim_copy = sim_copy[all_treatment_array]
return sim_copy, obs_copy
if __name__ == "__main__":
pass
|
BYU-Hydroinformatics/HydroErr | HydroErr/HydroErr.py | h1_mhe | python | def h1_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(h) | Compute the H1 mean error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mhe(sim, obs)
0.002106551840594386
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46. | train | https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L3858-L3930 | [
"def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,\n remove_neg=False, remove_zero=False):\n \"\"\"Removes the nan, negative, and inf values in two numpy arrays\"\"\"\n sim_copy = np.copy(simulated_array)\n obs_copy = np.copy(observed_array)\n\n # Checking to see if the vectors are the same length\n assert sim_copy.ndim == 1, \"The simulated array is not one dimensional.\"\n assert obs_copy.ndim == 1, \"The observed array is not one dimensional.\"\n\n if sim_copy.size != obs_copy.size:\n raise RuntimeError(\"The two ndarrays are not the same size.\")\n\n # Treat missing data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain nan values\n all_treatment_array = np.ones(obs_copy.size, dtype=bool)\n\n if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_nan = np.isnan(sim_copy)\n obs_nan = np.isnan(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_nan] = replace_nan\n obs_copy[obs_nan] = replace_nan\n\n warnings.warn(\"Elements(s) {} contained NaN values in the simulated array and \"\n \"elements(s) {} contained NaN values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_nan)[0],\n np.where(obs_nan)[0]),\n UserWarning)\n else:\n # Getting the indices of the nan values, combining them, and informing user.\n nan_indices_fcst = ~np.isnan(sim_copy)\n nan_indices_obs = ~np.isnan(obs_copy)\n all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)\n\n warnings.warn(\"Row(s) {} contained NaN values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_nan_indices)[0]),\n UserWarning)\n\n if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_inf = np.isinf(sim_copy)\n obs_inf = np.isinf(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_inf] = replace_inf\n obs_copy[obs_inf] = replace_inf\n\n warnings.warn(\"Elements(s) {} contained Inf values in the simulated array and \"\n \"elements(s) {} contained Inf values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_inf)[0],\n np.where(obs_inf)[0]),\n UserWarning)\n else:\n inf_indices_fcst = ~(np.isinf(sim_copy))\n inf_indices_obs = ~np.isinf(obs_copy)\n all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)\n\n warnings.warn(\n \"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows \"\n \"are zero indexed).\".format(np.where(~all_inf_indices)[0]),\n UserWarning\n )\n\n # Treat zero data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain zero values\n if remove_zero:\n if (obs_copy == 0).any() or (sim_copy == 0).any():\n zero_indices_fcst = ~(sim_copy == 0)\n zero_indices_obs = ~(obs_copy == 0)\n all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)\n\n warnings.warn(\n \"Row(s) {} contained zero values and the row(s) have been removed (Rows are \"\n \"zero indexed).\".format(np.where(~all_zero_indices)[0]),\n UserWarning\n )\n\n # Treat negative data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain negative values\n\n # Ignore runtime warnings from comparing\n if remove_neg:\n with np.errstate(invalid='ignore'):\n obs_copy_bool = obs_copy < 0\n sim_copy_bool = sim_copy < 0\n\n if obs_copy_bool.any() or sim_copy_bool.any():\n neg_indices_fcst = ~sim_copy_bool\n neg_indices_obs = ~obs_copy_bool\n all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)\n\n warnings.warn(\"Row(s) {} contained negative values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_neg_indices)[0]),\n UserWarning)\n\n obs_copy = obs_copy[all_treatment_array]\n sim_copy = sim_copy[all_treatment_array]\n\n return sim_copy, obs_copy\n"
] | # -*- coding: utf-8 -*-
"""
HydroErr contains a library of goodness of fit metrics that measure hydrologic skill.
Each metric is contained in function, and every function has the parameters to treat missing values as
well as remove zero and negative values from the timeseries data.
Each function contains two properties, name and abbr. These can be used in the Hydrostats package when creating tables
and adding metrics to the plots. Link to the hydrostats package: https://github.com/BYU-Hydroinformatics/Hydrostats.
An example of this functionality is shown below.
>>> import HydroErr as he
>>>
>>> he.acc.name
'Anomaly Correlation Coefficient'
>>> he.acc.abbr
'ACC'
"""
from __future__ import division
import numpy as np
from scipy.stats import gmean, rankdata
import warnings
__all__ = ['me', 'mae', 'mse', 'mle', 'male', 'msle', 'mde', 'mdae', 'mdse', 'ed', 'ned', 'rmse',
'rmsle', 'nrmse_range', 'nrmse_mean', 'nrmse_iqr', 'irmse', 'mase', 'r_squared',
'pearson_r', 'spearman_r', 'acc', 'mape', 'mapd', 'maape', 'smape1', 'smape2', 'd', 'd1',
'dmod', 'drel', 'dr', 'watt_m', 'mb_r', 'nse', 'nse_mod', 'nse_rel', 'kge_2009',
'kge_2012', 'lm_index', 'd1_p', 've', 'sa', 'sc', 'sid', 'sga', 'h1_mhe', 'h1_mahe',
'h1_rmshe', 'h2_mhe', 'h2_mahe', 'h2_rmshe', 'h3_mhe', 'h3_mahe', 'h3_rmshe', 'h4_mhe',
'h4_mahe', 'h4_rmshe', 'h5_mhe', 'h5_mahe', 'h5_rmshe', 'h6_mhe', 'h6_mahe', 'h6_rmshe',
'h7_mhe', 'h7_mahe', 'h7_rmshe', 'h8_mhe', 'h8_mahe', 'h8_rmshe', 'h10_mhe', 'h10_mahe',
'h10_rmshe', 'g_mean_diff', 'mean_var']
####################################################################################################
# General and Hydrological Error Metrics #
####################################################################################################
def me(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean error of the simulated and observed data.
.. image:: /pictures/ME.png
**Range:** -inf < MAE < inf, data units, closer to zero is better, indicates bias.
**Notes:** The mean error (ME) measures the difference between the simulated data and the
observed data. For the mean error, a smaller number indicates a better fit to the original
data. Note that if the error is in the form of random noise, the mean error will be very small,
which can skew the accuracy of this metric. ME is cumulative and will be small even if there
are large positive and negative errors that balance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean error value.
Examples
--------
Note that in this example the random noise cancels, leaving a very small ME.
>>> import HydroErr as he
>>> import numpy as np
>>> # Seed for reproducibility
>>> np.random.seed(54839)
>>> x = np.arange(100) / 20
>>> sim = np.sin(x) + 2
>>> obs = sim * (((np.random.rand(100) - 0.5) / 10) + 1)
>>> he.me(sim, obs)
-0.006832220968967168
References
----------
- Fisher, R.A., 1920. A Mathematical Examination of the Methods of Determining the Accuracy of
an Observation by the Mean Error, and by the Mean Square Error. Monthly Notices of the Royal
Astronomical Society 80 758 - 770.
"""
# Treating missing values
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero)
return np.mean(simulated_array - observed_array)
def mae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute error of the simulated and observed data.
.. image:: /pictures/MAE.png
**Range:** 0 ≤ MAE < inf, data units, smaller is better.
**Notes:** The ME measures the absolute difference between the simulated data and the observed
data. For the mean abolute error, a smaller number indicates a better fit to the original data.
Also note that random errors do not cancel. Also referred to as an L1-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute error value.
References
----------
- Willmott, Cort J., and Kenji Matsuura. “Advantages of the Mean Absolute Error (MAE) over the
Root Mean Square Error (RMSE) in Assessing Average Model Performance.” Climate Research 30,
no. 1 (2005): 79–82.
- Willmott, Cort J., and Kenji Matsuura. “On the Use of Dimensioned Measures of Error to
Evaluate the Performance of Spatial Interpolators.” International Journal of Geographical
Information Science 20, no. 1 (2006): 89–102.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mae(sim, obs)
0.5666666666666665
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean(np.absolute(simulated_array - observed_array))
def mse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared error of the simulated and observed data.
.. image:: /pictures/MSE.png
**Range:** 0 ≤ MSE < inf, data units squared, smaller is better.
**Notes:** Random errors do not cancel, highlights larger errors, also referred to as a
squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mse(sim, obs)
0.4333333333333333
References
----------
- Wang, Zhou, and Alan C. Bovik. “Mean Squared Error: Love It or Leave It? A New Look at Signal
Fidelity Measures.” IEEE Signal Processing Magazine 26, no. 1 (2009): 98–117.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean((simulated_array - observed_array) ** 2)
def mle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean log error of the simulated and observed data.
.. image:: /pictures/MLE.png
**Range:** -inf < MLE < inf, data units, closer to zero is better.
**Notes** Same as the mean erro (ME) only use log ratios as the error term. Limits the impact of outliers, more
evenly weights high and low data values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mle(sim, obs)
0.002961767058151136
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(sim_log - obs_log)
def male(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean absolute log error of the simulated and observed data.
.. image:: /pictures/MALE.png
**Range:** 0 ≤ MALE < inf, data units squared, smaller is better.
**Notes** Same as MAE only use log ratios as the error term. Limits the impact of outliers,
more evenly weights high and low flows.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.male(sim, obs), 6)
0.090417
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(np.abs(sim_log - obs_log))
def msle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared log error of the simulated and observed data.
.. image:: /pictures/MSLE.png
**Range:** 0 ≤ MSLE < inf, data units squared, smaller is better.
**Notes** Same as the mean squared error (MSE) only use log ratios as the error term. Limits
the impact of outliers, more evenly weights high and low values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.msle(sim, obs), 6)
0.010426
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean((sim_log - obs_log) ** 2)
def mde(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median error (MdE) between the simulated and observed data.
.. image:: /pictures/MdE.png
**Range** -inf < MdE < inf, closer to zero is better.
**Notes** This metric indicates bias. It is similar to the mean error (ME), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mde(sim, obs)
-0.10000000000000009
Returns
-------
float
The median error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(simulated_array - observed_array)
def mdae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median absolute error (MdAE) between the simulated and observed data.
.. image:: /pictures/MdAE.png
**Range** 0 ≤ MdAE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean absolute error (MAE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdae(sim, obs)
0.75
Returns
-------
float
The median absolute error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(np.abs(simulated_array - observed_array))
def mdse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median squared error (MdSE) between the simulated and observed data.
.. image:: /pictures/MdSE.png
**Range** 0 ≤ MdSE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean squared error (MSE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdse(sim, obs)
0.625
Returns
-------
float
The median squared error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median((simulated_array - observed_array) ** 2)
def ed(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Euclidean distance between predicted and observed values in vector space.
.. image:: /pictures/ED.png
**Range** 0 ≤ ED < inf, smaller is better.
**Notes** Also sometimes referred to as the L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ed(sim, obs)
1.63707055437449
Returns
-------
float
The euclidean distance error value.
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.linalg.norm(observed_array - simulated_array)
def ned(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the normalized Euclidian distance between the simulated and observed data in vector
space.
.. image:: /pictures/NED.png
**Range** 0 ≤ NED < inf, smaller is better.
**Notes** Also sometimes referred to as the squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The normalized euclidean distance value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ned(sim, obs)
0.2872053604165771
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array / np.mean(observed_array)
b = simulated_array / np.mean(simulated_array)
return np.linalg.norm(a - b)
def rmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square error between the simulated and observed data.
.. image:: /pictures/RMSE.png
**Range** 0 ≤ RMSE < inf, smaller is better.
**Notes:** The standard deviation of the residuals. A lower spread indicates that the points
are better concentrated around the line of best fit (linear). Random errors do not cancel.
This metric will highlights larger errors.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.rmse(sim, obs)
0.668331255192114
References
----------
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.sqrt(np.mean((simulated_array - observed_array) ** 2))
def rmsle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square log error between the simulated and observed data.
.. image:: /pictures/RMSLE.png
**Range:** 0 ≤ RMSLE < inf. Smaller is better, and it does not indicate bias.
**Notes:** Random errors do not cancel while using this metric. This metric limits the
impact of outliers by more evenly weighting high and low values. To calculate the log values,
each value in the observed and simulated array is increased by one unit in order to avoid
run-time errors and nan values (function np.log1p).
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square log error value.
Examples
--------
Notice that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.rmsle(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
"""
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf, remove_neg=remove_neg,
remove_zero=remove_zero)
return np.sqrt(np.mean(np.power(np.log1p(simulated_array) - np.log1p(observed_array), 2)))
def nrmse_range(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the range normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Range.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the range of the observed time series (x).
Normalizing allows comparison between data sets with different scales. The NRMSErange is the
most sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The range normalized root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_range(sim, obs)
0.0891108340256152
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_max = np.max(observed_array)
obs_min = np.min(observed_array)
return rmse_value / (obs_max - obs_min)
def nrmse_mean(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Mean.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the mean of the observed time series (x).
Normalizing allows comparison between data sets with different scales.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_mean(sim, obs)
0.11725109740212526
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_mean = np.mean(observed_array)
return rmse_value / obs_mean
def nrmse_iqr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the IQR normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_IQR.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the interquartile range of the observed time
series (x). Normalizing allows comparison between data sets with different scales.
The NRMSEquartile is the least sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The IQR normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_iqr(sim, obs)
0.2595461185212093
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
q1 = np.percentile(observed_array, 25)
q3 = np.percentile(observed_array, 75)
iqr = q3 - q1
return rmse_value / iqr
def irmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the inertial root mean square error (IRMSE) between the simulated and observed data.
.. image:: /pictures/IRMSE.png
**Range:** 0 ≤ IRMSE < inf, lower is better.
**Notes:** This metric is the RMSE devided by by the standard deviation of the gradient of the
observed timeseries data. This metric is meant to be help understand the ability of the model
to predict changes in observation.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The inertial root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.irmse(sim, obs)
0.14572738134831856
References
----------
- Daga, M., Deo, M.C., 2009. Alternative data-driven methods to estimate wind from waves by
inverse modeling. Natural Hazards 49(2) 293-310.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Getting the gradient of the observed data
obs_len = observed_array.size
obs_grad = observed_array[1:obs_len] - observed_array[0:obs_len - 1]
# Standard deviation of the gradient
obs_grad_std = np.std(obs_grad, ddof=1)
# Divide RMSE by the standard deviation of the gradient of the observed data
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
return rmse_value / obs_grad_std
def mase(simulated_array, observed_array, m=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute scaled error between the simulated and observed data.
.. image:: /pictures/MASE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
m: int
If given, indicates the seasonal period m. If not given, the default is 1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute scaled error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mase(sim, obs)
0.17341040462427745
References
----------
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
start = m
end = simulated_array.size - m
a = np.mean(np.abs(simulated_array - observed_array))
b = np.abs(observed_array[start:observed_array.size] - observed_array[:end])
return a / (np.sum(b) / end)
def pearson_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the pearson correlation coefficient.
.. image:: /pictures/R_pearson.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The pearson r coefficient measures linear correlation. It is sensitive to outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Pearson correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.pearson_r(sim, obs)
0.9610793632835262
References
----------
- Pearson, K. (1895). Note on regression and inheritance in the case of two parents.
Proceedings of the Royal Society of London, 58, 240-242.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
top = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1 = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2 = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
return top / (bot1 * bot2)
def spearman_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the spearman rank correlation coefficient.
.. image:: /pictures/R_spearman.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The spearman r coefficient measures the monotonic relation between simulated and
observed data. Because it uses a nonparametric measure of rank correlation, it is less sensitive
to outliers compared to the Pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spearman rank correlation coefficient.
Examples
----------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.spearman_r(sim, obs)
0.942857142857143
References
----------
- Spearman C (1904). "The proof and measurement of association between two things". American
Journal of Psychology. 15: 72–101. doi:10.2307/1412159
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rank_sim = rankdata(simulated_array)
rank_obs = rankdata(observed_array)
mean_rank_sim = np.mean(rank_sim)
mean_rank_obs = np.mean(rank_obs)
top = np.mean((rank_obs - mean_rank_obs) * (rank_sim - mean_rank_sim))
bot = np.sqrt(
np.mean((rank_obs - mean_rank_obs) ** 2) * np.mean((rank_sim - mean_rank_sim) ** 2))
return top / bot
def r_squared(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Coefficient of Determination (r2).
.. image:: /pictures/r2.png
**Range:** 0 ≤ r2 ≤ 1. 1 indicates perfect correlation, 0 indicates complete randomness.
**Notes:** The Coefficient of Determination measures the linear relation between simulated and
observed data. Because it is the pearson correlation coefficient squared, it is more heavily
affected by outliers than the pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The coefficient of determination (R^2).
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.r_squared(sim, obs)
0.9236735425294681
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array - np.mean(observed_array)
b = simulated_array - np.mean(simulated_array)
return (np.sum(a * b)) ** 2 / (np.sum(a ** 2) * np.sum(b ** 2))
def acc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the anomaly correlation coefficient (ACC).
.. image:: /pictures/ACC.png
**Range:** -1 ≤ ACC ≤ 1. -1 indicates perfect negative correlation of the variation
pattern of the anomalies, 0 indicates complete randomness of the variation patterns of the
anomalies, 1 indicates perfect correlation of the variation pattern of the anomalies.
**Notes:** Common measure in the verification of spatial fields. Measures the correlation
between the variation pattern of the simulated data compared to the observed data.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The anomaly correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.acc(sim, obs)
0.8008994694029383
References
----------
- Langland, Rolf H., and Ryan N. Maue. “Recent Northern Hemisphere Mid-Latitude Medium-Range
Deterministic Forecast Skill.” Tellus A: Dynamic Meteorology and Oceanography 64,
no. 1 (2012): 17531.
- Miyakoda, K., G. D. Hembree, R. F. Strickler, and I. Shulman. “Cumulative Results of Extended
Forecast Experiments I. Model Performance for Winter Cases.” Monthly Weather Review 100, no.
12(1972): 836–55.
- Murphy, Allan H., and Edward S. Epstein. “Skill Scores and Correlation Coefficients in Model
Verification.” Monthly Weather Review 117, no. 3 (1989): 572–82.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - np.mean(simulated_array)
b = observed_array - np.mean(observed_array)
c = np.std(observed_array, ddof=1) * np.std(simulated_array, ddof=1) * simulated_array.size
return np.dot(a, b / c)
def mape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the mean absolute percentage error (MAPE).
.. image:: /pictures/MAPE.png
**Range:** 0% ≤ MAPE ≤ inf. 0% indicates perfect correlation, a larger error indicates a
larger percent error in the data.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
c = 100 / simulated_array.size
return c * np.sum(b)
def mapd(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the mean absolute percentage deviation (MAPD).
.. image:: /pictures/MAPD.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage deviation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mapd(sim, obs)
0.10526315789473682
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(np.abs(observed_array))
return a / b
def maape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the Mean Arctangent Absolute Percentage Error (MAAPE).
.. image:: /pictures/MAAPE.png
**Range:** 0 ≤ MAAPE < π/2, does not indicate bias, smaller is better.
**Notes:** Represents the mean absolute error as a percentage of the observed values. Handles
0s in the observed data. This metric is not as biased as MAPE by under-over predictions.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean arctangent absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
- Kim, S., Kim, H., 2016. A new metric of absolute percentage error for intermittent demand
forecasts. International Journal of Forecasting 32(3) 669-679.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
return np.mean(np.arctan(b))
def smape1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (1) (SMAPE1).
.. image:: /pictures/SMAPE1.png
**Range:** 0 ≤ SMAPE1 < 100%, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (1).
Examples
--------
Note that if we switch the simulated and observed arrays the result is the same
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape1(sim, obs)
5.871915694397428
>>> he.smape1(obs, sim)
5.871915694397428
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 100 / simulated_array.size
b = np.abs(simulated_array - observed_array)
c = np.abs(simulated_array) + np.abs(observed_array)
return a * np.sum(b / c)
def smape2(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (2) (SMAPE2).
.. image:: /pictures/SMAPE2.png
**Range:** 0 ≤ SMAPE1 < 200%, does not indicate bias, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE with only positive metric values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (2).
Examples
--------
Note that switching the simulated and observed arrays yields the same results
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape2(sim, obs)
11.743831388794856
>>> he.smape2(obs, sim)
11.743831388794856
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = (simulated_array + observed_array) / 2
c = 100 / simulated_array.size
return c * np.sum(np.abs(a / b))
def d(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d).
.. image:: /pictures/d.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d(sim, obs)
0.978477353035657
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (observed_array - simulated_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
return 1 - (np.sum(a) / np.sum((b + c) ** 2))
def d1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d1).
.. image:: /pictures/d1.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric. Compared
to the other index of agreement (d) it has a reduced impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (d1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1(sim, obs)
0.8434782608695652
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
obs_mean = np.mean(observed_array)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.abs(simulated_array - obs_mean)
c = np.abs(observed_array - obs_mean)
return 1 - np.sum(a) / np.sum(b + c)
def dr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the refined index of agreement (dr).
.. image:: /pictures/dr.png
**Range:** -1 ≤ dr < 1, does not indicate bias, larger is better.
**Notes:** Reformulation of Willmott’s index of agreement. This metric was created to address
issues in the index of agreement and the Nash-Sutcliffe efficiency metric. Meant to be a
flexible metric for use in climatology.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The refined index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dr(sim, obs)
0.847457627118644
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = 2 * np.sum(np.abs(observed_array - observed_array.mean()))
if a <= b:
return 1 - (a / b)
else:
return (b / a) - 1
def drel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the relative index of agreement (drel).
.. image:: /pictures/drel.png
**Range:** 0 ≤ drel < 1, does not indicate bias, larger is better.
**Notes:** Instead of absolute differences, this metric uses relative differences.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.drel(sim, obs)
0.9740868625579597
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = ((simulated_array - observed_array) / observed_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = ((b + c) / np.mean(observed_array)) ** 2
return 1 - (np.sum(a) / np.sum(e))
def dmod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the modified index of agreement (dmod).
.. image:: /pictures/dmod.png
**Range:** 0 ≤ dmod < 1, does not indicate bias, larger is better.
**Notes:** When j=1, this metric is the same as d1. As j becomes larger, outliers have a larger
impact on the value.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
Optional input indicating the j values desired. A higher j places more emphasis on
outliers. j is 1 by default.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified index of agreement.
Examples
--------
Note that using the default is the same as calculating the d1 metric. Changing the value of j
modification of the metric.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dmod(sim, obs) # Same as d1
0.8434782608695652
>>> he.dmod(sim, obs, j=1.5)
0.9413310986805733
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = (b + c) ** j
return 1 - (np.sum(a) / np.sum(e))
def watt_m(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute Watterson's M (M).
.. image:: /pictures/M.png
**Range:** -1 ≤ M < 1, does not indicate bias, larger is better.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
Watterson's M value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.watt_m(sim, obs)
0.8307913876595929
References
----------
- Watterson, I.G., 1996. Non‐dimensional measures of climate model performance. International
Journal of Climatology 16(4) 379-391.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 2 / np.pi
b = np.mean((simulated_array - observed_array) ** 2) # MSE
c = np.std(observed_array, ddof=1) ** 2 + np.std(simulated_array, ddof=1) ** 2
e = (np.mean(simulated_array) - np.mean(observed_array)) ** 2
f = c + e
return a * np.arcsin(1 - (b / f))
def mb_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute Mielke-Berry R value (MB R).
.. image:: /pictures/MB_R.png
**Range:** 0 ≤ MB R < 1, does not indicate bias, larger is better.
**Notes:** Compares prediction to probability it arose by chance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Mielke-Berry R value.
Notes
-----
If a more optimized version is desired, the `numba package <http://numba.pydata.org/doc.html>`_ can be implemented
for a much more optimized performance when computing this metric. An example is given below.
>>> from numba import njit, prange
>>> @njit(parallel=True, fastmath=True)
>>> def mb_par_fastmath(pred, obs): # uses LLVM compiler
>>> assert pred.size == obs.size
>>> n = pred.size
>>> tot = 0.0
>>> mae = 0.0
>>> for i in range(n):
>>> for j in prange(n):
>>> tot += abs(pred[i] - obs[j])
>>> mae += abs(pred[i] - obs[i])
>>> mae = mae / n
>>> mb = 1 - ((n ** 2) * mae / tot)
>>>
>>> return mb
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mb_r(sim, obs)
0.7726315789473684
References
----------
- Berry, K.J., Mielke, P.W., 1988. A Generalization of Cohen's Kappa Agreement Measure to
Interval Measurement and Multiple Raters. Educational and Psychological Measurement 48(4)
921-933.
- Mielke, P.W., Berry, K.J., 2007. Permutation methods: a distance function approach.
Springer Science & Business Media.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Calculate metric
n = simulated_array.size
tot = 0.0
for i in range(n):
tot = tot + np.sum(np.abs(simulated_array - observed_array[i]))
mae_val = np.sum(np.abs(simulated_array - observed_array)) / n
mb = 1 - ((n ** 2) * mae_val / tot)
return mb
def nse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Nash-Sutcliffe Efficiency.
.. image:: /pictures/NSE.png
**Range:** -inf < NSE < 1, does not indicate bias, larger is better.
**Notes:** The Nash-Sutcliffe efficiency metric compares prediction values to naive predictions
(i.e. average value). One major flaw of this metric is that it punishes a higher variance in
the observed values (denominator). This metric is analogous to the mean absolute error skill
score (MAESS) using the mean flow as a benchmark.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Nash-Sutcliffe Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse(sim, obs)
0.922093023255814
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
- McCuen, R.H., Knight, Z., Cutter, A.G., 2006. Evaluation of the Nash-Sutcliffe Efficiency
Index. Journal of Hydraulic Engineering.
- Nash, J.E., Sutcliffe, J.V., 1970. River flow forecasting through conceptual models part
I — A discussion of principles. Journal of Hydrology 282-290.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** 2
b = (np.abs(observed_array - np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def nse_mod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the modified Nash-Sutcliffe efficiency (NSE mod).
.. image:: /pictures/NSEmod.png
**Range:** -inf < NSE (mod) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
If given, sets the value of j to the input. j is 1 by default. A higher j gives more
emphasis to outliers
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_mod(sim, obs)
0.6949152542372882
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = (np.abs(observed_array - np.mean(observed_array))) ** j
return 1 - (np.sum(a) / np.sum(b))
def nse_rel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the relative Nash-Sutcliffe efficiency (NSE rel).
.. image:: /pictures/NSErel.png
**Range:** -inf < NSE (rel) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_rel(sim, obs)
0.9062004687708474
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs((simulated_array - observed_array) / observed_array)) ** 2
b = (np.abs((observed_array - np.mean(observed_array)) / np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def kge_2009(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""Compute the Kling-Gupta efficiency (2009).
.. image:: /pictures/KGE_2009.png
**Range:** -inf < KGE (2009) < 1, larger is better.
**Notes:** Gupta et al. (2009) created this metric to demonstrate the relative importance of
the three components of the NSE, which are correlation, bias and variability. This was done
with hydrologic modeling as the context. This metric is meant to address issues with the NSE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), Alpha, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, alpha, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2009) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2009(sim, obs)
0.912223072345668
>>> he.kge_2009(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.927910707932087, 1.0058823529411764, 0.9181073779138655)
References
----------
- Gupta, H. V., Kling, H., Yilmaz, K. K., & Martinez, G. F. (2009). Decomposition of the mean
squared error and NSE performance criteria: Implications for improving hydrological modelling.
Journal of Hydrology, 377(1-2), 80-91.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array, ddof=1)
obs_sigma = np.std(observed_array, ddof=1)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
if obs_mean != 0:
beta = sim_mean / obs_mean
else:
beta = np.nan
# Relative variability between simulated and observed values
if obs_sigma != 0:
alpha = sim_sigma / obs_sigma
else:
alpha = np.nan
if not np.isnan(beta) and not np.isnan(alpha):
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (alpha - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Alpha is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, alpha, beta, kge
else:
return kge
def kge_2012(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""
Compute the Kling-Gupta efficiency (2012).
.. image:: /pictures/KGE_2012.png
**Range:** -inf < KGE (2012) < 1, does not indicate bias, larger is better.
**Notes:** The modified version of the KGE (2009). Kling proposed this version to avoid
cross-correlation between bias and variability ratios.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), gamma, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, gamma, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2012) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2012(sim, obs)
0.9122230723456678
>>> he.kge_2012(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.9224843295231272, 1.0058823529411764, 0.9132923608280753)
References
----------
- Kling, H., Fuchs, M., & Paulin, M. (2012). Runoff conditions in the upper Danube basin under
an ensemble of climate change scenarios. Journal of Hydrology, 424, 264-277.
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array)
obs_sigma = np.std(observed_array)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
beta = sim_mean / obs_mean
# CV is the coefficient of variation (standard deviation / mean)
sim_cv = sim_sigma / sim_mean
obs_cv = obs_sigma / obs_mean
# Variability Ratio, or the ratio of simulated CV to observed CV
gam = sim_cv / obs_cv
if obs_mean != 0 and obs_sigma != 0 and sim_mean != 0:
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (gam - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
if sim_mean == 0:
warnings.warn(
'Warning: The simulated data mean is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, gam, beta, kge
else:
return kge
def lm_index(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""
Compute the Legate-McCabe Efficiency Index.
.. image:: /pictures/E1p.png
**Range:** 0 ≤ E1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.lm_index(sim, obs)
0.6949152542372882
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
mean_obs = np.mean(observed_array)
if obs_bar_p is not None:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def d1_p(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""Compute the Legate-McCabe Index of Agreement.
.. image:: /pictures/D1p.png
**Range:** 0 ≤ d1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1_p(sim, obs)
0.8434782608695652
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
if obs_bar_p is not None:
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - obs_bar_p) + np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
mean_obs = np.mean(observed_array)
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - mean_obs) + np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def ve(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Volumetric Efficiency (VE).
.. image:: /pictures/VE.png
**Range:** 0 ≤ VE < 1 smaller is better, does not indicate bias.
**Notes:** Represents the error as a percentage of flow.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Volumetric Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ve(sim, obs)
0.8947368421052632
References
----------
- Criss, R.E., Winston, W.E., 2008. Do Nash values have value? Discussion and alternate
proposals. Hydrological Processes 22(14) 2723.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(observed_array)
return 1 - (a / b)
def sa(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Angle (SA).
.. image:: /pictures/SA.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral angle metric measures the angle between the two vectors in hyperspace.
It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Angle value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sa(sim, obs)
0.10816831366492945
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(simulated_array, observed_array)
b = np.linalg.norm(simulated_array) * np.linalg.norm(observed_array)
return np.arccos(a / b)
def sc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Correlation (SC).
.. image:: /pictures/SC.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral correlation metric measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Correlation value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sc(sim, obs)
0.27991341383646606
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(observed_array - np.mean(observed_array), simulated_array - np.mean(simulated_array))
b = np.linalg.norm(observed_array - np.mean(observed_array))
c = np.linalg.norm(simulated_array - np.mean(simulated_array))
e = b * c
return np.arccos(a / e)
def sid(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Information Divergence (SID).
.. image:: /pictures/SID.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral information divergence measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral information divergence value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sid(sim, obs)
0.03517616895318012
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
first = (observed_array / np.mean(observed_array)) - (
simulated_array / np.mean(simulated_array))
second1 = np.log10(observed_array) - np.log10(np.mean(observed_array))
second2 = np.log10(simulated_array) - np.log10(np.mean(simulated_array))
return np.dot(first, second1 - second2)
def sga(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Gradient Angle (SGA).
.. image:: /pictures/SGA.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral gradient angle measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
SG is the gradient of the simulated or observed time series.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Gradient Angle.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sga(sim, obs)
0.26764286472739834
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sgx = observed_array[1:] - observed_array[:observed_array.size - 1]
sgy = simulated_array[1:] - simulated_array[:simulated_array.size - 1]
a = np.dot(sgx, sgy)
b = np.linalg.norm(sgx) * np.linalg.norm(sgy)
return np.arccos(a / b)
####################################################################################################
# H Metrics: Methods from Tornqvist L, Vartia P, and Vartia YO. (1985) #
####################################################################################################
def h1_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H1 absolute error.
.. image:: /pictures/H1.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The H1 absolute error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mahe(sim, obs)
0.11639226612630865
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(np.abs(h))
def h1_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H1 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean squared H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_rmshe(sim, obs)
0.12865571253672756
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.sqrt(np.mean(h ** 2))
def h2_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean error.
.. image:: /pictures/H2.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mhe(sim, obs)
-0.015319829424307036
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(h)
def h2_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean absolute error.
.. image:: /pictures/H2.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mahe(sim, obs)
0.11997591408039167
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(np.abs(h))
def h2_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_rmshe(sim, obs)
0.1373586680669673
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.sqrt(np.mean(h ** 2))
def h3_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 mean error.
.. image:: /pictures/H3.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mhe(sim, obs)
-0.006322019630356533
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(h)
def h3_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H3 mean absolute error.
.. image:: /pictures/H3.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mahe(sim, obs)
0.11743831388794855
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(np.abs(h))
def h3_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 root mean square error.
.. image:: /pictures/H3.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.sqrt(np.mean(h ** 2))
def h4_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mhe(sim, obs)
-0.0064637371129817
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(h)
def h4_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H4 mean absolute error.
.. image:: /pictures/H4.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mahe(sim, obs)
0.11781032209144082
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(np.abs(h))
def h4_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_rmshe(sim, obs)
0.13200901963465006
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.sqrt(np.mean(h ** 2))
def h5_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean error.
.. image:: /pictures/H5.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mhe(sim, obs)
-0.006606638791856322
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(h)
def h5_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean absolute error.
.. image:: /pictures/H5.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mahe(sim, obs)
0.11818409010335018
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(np.abs(h))
def h5_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 root mean square error.
.. image:: /pictures/H5.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_rmshe(sim, obs)
0.13254476469410933
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h6_mhe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H6 mean error.
.. image:: /pictures/H6.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mhe(sim, obs)
-0.006322019630356514
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(h)
def h6_mahe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""Compute the H6 mean absolute error.
.. image:: /pictures/H6.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mahe(sim, obs)
0.11743831388794852
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(np.abs(h))
def h6_rmshe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the H6 root mean square error.
.. image:: /pictures/H6.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h7_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean error.
.. image:: /pictures/H7.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mhe(sim, obs)
0.0026331898007430263
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(h)
def h7_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean absolute error.
.. image:: /pictures/H7.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mahe(sim, obs)
0.14549033265788583
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(np.abs(h))
def h7_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 root mean square error.
.. image:: /pictures/H7.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_rmshe(sim, obs)
0.16081964067090945
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
def h8_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H8 mean error.
.. image:: /pictures/H8.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mhe(sim, obs)
0.0018056158633666466
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(h)
def h8_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 mean absolute error.
.. image:: /pictures/H8.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mahe(sim, obs)
0.099764799536836
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(np.abs(h))
def h8_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 root mean square error.
.. image:: /pictures/H8.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_rmshe(sim, obs)
0.11027632503148076
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
# def h9(simulated_array, observed_array, h_type='mhe', k=1):
# h = (simulated_array / observed_array - 1) / \
# np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
# if h_type == 'mhe':
# return h.mean()
# elif h_type == 'ahe':
# return np.abs(h).mean()
# elif h_type == 'rmshe':
# return np.sqrt((h**2).mean())
# else:
# raise RuntimeError("The three types available are 'mhe', 'ahe', and 'rmshe'.")
def h10_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean error.
.. image:: /pictures/H10.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h10_mhe(sim, obs)
-0.0012578676058971154
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(h)
def h10_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean absolute error.
.. image:: /pictures/H10.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_mahe(sim, obs), 6)
0.094636
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(np.abs(h))
def h10_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 root mean square error.
.. image:: /pictures/H10.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_rmshe(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.sqrt(np.mean(h ** 2))
###################################################################################################
# Statistical Error Metrics for Distribution Testing #
###################################################################################################
def g_mean_diff(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the geometric mean difference.
.. image:: /pictures/GMD.png
**Range:**
**Notes:** For the difference of geometric means, the geometric mean is computed for each of
two samples then their difference is taken.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The geometric mean difference value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.g_mean_diff(sim, obs)
0.988855412098022
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.exp(gmean(sim_log) - gmean(obs_log))
def mean_var(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the mean variance.
.. image:: /pictures/MV.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean variance.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.mean_var(sim, obs), 6)
0.010641
References
----------
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.var(np.log1p(observed_array) - np.log1p(simulated_array))
####################################################################################################
# HELPER FUNCTIONS AND API INFORMATION #
####################################################################################################
metric_names = [
'Mean Error', 'Mean Absolute Error', 'Mean Squared Error', 'Mean Log Error',
'Mean Absolute Log Error', 'Mean Squared Log Error', 'Median Error', 'Median Absolute Error',
'Median Squared Error', 'Eclidean Distance', 'Normalized Eclidean Distance',
'Root Mean Square Error', 'Root Mean Squared Log Error',
'Normalized Root Mean Square Error - Range', 'Normalized Root Mean Square Error - Mean',
'Normalized Root Mean Square Error - IQR', 'Inertial Root Mean Square Error',
'Mean Absolute Scaled Error', 'Coefficient of Determination', 'Pearson Correlation Coefficient',
'Spearman Rank Correlation Coefficient', 'Anomaly Correlation Coefficient',
'Mean Absolute Percentage Error', 'Mean Absolute Percentage Deviation',
'Mean Arctangent Absolute Percentage Error', 'Symmetric Mean Absolute Percentage Error (1)',
'Symmetric Mean Absolute Percentage Error (2)', 'Index of Agreement (d)',
'Index of Agreement (d1)', 'Modified Index of Agreement', 'Relative Index of Agreement',
'Index of Agreement Refined (dr)', "Watterson's M", 'Mielke-Berry R',
'Nash-Sutcliffe Efficiency', 'Modified Nash-Sutcliffe Efficiency',
'Relative Nash-Sutcliffe Efficiency', 'Kling-Gupta Efficiency (2009)',
'Kling-Gupta Efficiency (2012)', 'Legate-McCabe Efficiency Index',
'Legate-McCabe Index of Agreement', 'Volumetric Efficiency', 'Spectral Angle',
'Spectral Correlation', 'Spectral Information Divergence', 'Spectral Gradient Angle',
'Mean H1 Error', 'Mean Absolute H1 Error', 'Root Mean Square H1 Error', 'Mean H2 Error',
'Mean Absolute H2 Error', 'Root Mean Square H2 Error', 'Mean H3 Error',
'Mean Absolute H3 Error', 'Root Mean Square H3 Error', 'Mean H4 Error',
'Mean Absolute H4 Error', 'Root Mean Square H4 Error', 'Mean H5 Error',
'Mean Absolute H5 Error', 'Root Mean Square H5 Error', 'Mean H6 Error',
'Mean Absolute H6 Error', 'Root Mean Square H6 Error', 'Mean H7 Error',
'Mean Absolute H7 Error', 'Root Mean Square H7 Error', 'Mean H8 Error',
'Mean Absolute H8 Error', 'Root Mean Square H8 Error', 'Mean H10 Error',
'Mean Absolute H10 Error', 'Root Mean Square H10 Error', 'Geometric Mean Difference',
'Mean Variance'
]
metric_abbr = [
'ME', 'MAE', 'MSE', 'MLE', 'MALE', 'MSLE', 'MdE', 'MdAE', 'MdSE', 'ED', 'NED', 'RMSE', 'RMSLE',
'NRMSE (Range)', 'NRMSE (Mean)', 'NRMSE (IQR)', 'IRMSE', 'MASE', 'r2', 'R (Pearson)',
'R (Spearman)', 'ACC', 'MAPE', 'MAPD', 'MAAPE', 'SMAPE1', 'SMAPE2', 'd', 'd1', 'd (Mod.)',
'd (Rel.)', 'dr', 'M', '(MB) R', 'NSE', 'NSE (Mod.)', 'NSE (Rel.)', 'KGE (2009)', 'KGE (2012)',
"E1'", "D1'", 'VE', 'SA', 'SC', 'SID', 'SGA', 'H1 (MHE)', 'H1 (MAHE)', 'H1 (RMSHE)', 'H2 (MHE)',
'H2 (MAHE)', 'H2 (RMSHE)', 'H3 (MHE)', 'H3 (MAHE)', 'H3 (RMSHE)', 'H4 (MHE)', 'H4 (MAHE)',
'H4 (RMSHE)', 'H5 (MHE)', 'H5 (MAHE)', 'H5 (RMSHE)', 'H6 (MHE)', 'H6 (MAHE)', 'H6 (RMSHE)',
'H7 (MHE)', 'H7 (MAHE)', 'H7 (RMSHE)', 'H8 (MHE)', 'H8 (MAHE)', 'H8 (RMSHE)', 'H10 (MHE)',
'H10 (MAHE)', 'H10 (RMSHE)', 'GMD', 'MV'
]
function_list = [
me, mae, mse, mle, male, msle, mde, mdae, mdse, ed, ned, rmse, rmsle, nrmse_range, nrmse_mean,
nrmse_iqr, irmse, mase, r_squared, pearson_r, spearman_r, acc, mape, mapd, maape, smape1,
smape2, d, d1, dmod, drel, dr, watt_m, mb_r, nse, nse_mod, nse_rel, kge_2009, kge_2012,
lm_index, d1_p, ve, sa, sc, sid, sga, h1_mhe, h1_mahe, h1_rmshe, h2_mhe, h2_mahe, h2_rmshe,
h3_mhe, h3_mahe, h3_rmshe, h4_mhe, h4_mahe, h4_rmshe, h5_mhe, h5_mahe, h5_rmshe, h6_mhe,
h6_mahe, h6_rmshe, h7_mhe, h7_mahe, h7_rmshe, h8_mhe, h8_mahe, h8_rmshe, h10_mhe, h10_mahe,
h10_rmshe, g_mean_diff, mean_var,
]
# Assign some properties to each function for ease of use for users
for i in range(len(function_list)):
function_list[i].name = metric_names[i]
function_list[i].abbr = metric_abbr[i]
def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Removes the nan, negative, and inf values in two numpy arrays"""
sim_copy = np.copy(simulated_array)
obs_copy = np.copy(observed_array)
# Checking to see if the vectors are the same length
assert sim_copy.ndim == 1, "The simulated array is not one dimensional."
assert obs_copy.ndim == 1, "The observed array is not one dimensional."
if sim_copy.size != obs_copy.size:
raise RuntimeError("The two ndarrays are not the same size.")
# Treat missing data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain nan values
all_treatment_array = np.ones(obs_copy.size, dtype=bool)
if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_nan = np.isnan(sim_copy)
obs_nan = np.isnan(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_nan] = replace_nan
obs_copy[obs_nan] = replace_nan
warnings.warn("Elements(s) {} contained NaN values in the simulated array and "
"elements(s) {} contained NaN values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_nan)[0],
np.where(obs_nan)[0]),
UserWarning)
else:
# Getting the indices of the nan values, combining them, and informing user.
nan_indices_fcst = ~np.isnan(sim_copy)
nan_indices_obs = ~np.isnan(obs_copy)
all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)
warnings.warn("Row(s) {} contained NaN values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_nan_indices)[0]),
UserWarning)
if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_inf = np.isinf(sim_copy)
obs_inf = np.isinf(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_inf] = replace_inf
obs_copy[obs_inf] = replace_inf
warnings.warn("Elements(s) {} contained Inf values in the simulated array and "
"elements(s) {} contained Inf values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_inf)[0],
np.where(obs_inf)[0]),
UserWarning)
else:
inf_indices_fcst = ~(np.isinf(sim_copy))
inf_indices_obs = ~np.isinf(obs_copy)
all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)
warnings.warn(
"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows "
"are zero indexed).".format(np.where(~all_inf_indices)[0]),
UserWarning
)
# Treat zero data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain zero values
if remove_zero:
if (obs_copy == 0).any() or (sim_copy == 0).any():
zero_indices_fcst = ~(sim_copy == 0)
zero_indices_obs = ~(obs_copy == 0)
all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)
warnings.warn(
"Row(s) {} contained zero values and the row(s) have been removed (Rows are "
"zero indexed).".format(np.where(~all_zero_indices)[0]),
UserWarning
)
# Treat negative data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain negative values
# Ignore runtime warnings from comparing
if remove_neg:
with np.errstate(invalid='ignore'):
obs_copy_bool = obs_copy < 0
sim_copy_bool = sim_copy < 0
if obs_copy_bool.any() or sim_copy_bool.any():
neg_indices_fcst = ~sim_copy_bool
neg_indices_obs = ~obs_copy_bool
all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)
warnings.warn("Row(s) {} contained negative values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_neg_indices)[0]),
UserWarning)
obs_copy = obs_copy[all_treatment_array]
sim_copy = sim_copy[all_treatment_array]
return sim_copy, obs_copy
if __name__ == "__main__":
pass
|
BYU-Hydroinformatics/HydroErr | HydroErr/HydroErr.py | h6_mahe | python | def h6_mahe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(np.abs(h)) | Compute the H6 mean absolute error.
.. image:: /pictures/H6.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mahe(sim, obs)
0.11743831388794852
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46. | train | https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L5110-L5189 | [
"def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,\n remove_neg=False, remove_zero=False):\n \"\"\"Removes the nan, negative, and inf values in two numpy arrays\"\"\"\n sim_copy = np.copy(simulated_array)\n obs_copy = np.copy(observed_array)\n\n # Checking to see if the vectors are the same length\n assert sim_copy.ndim == 1, \"The simulated array is not one dimensional.\"\n assert obs_copy.ndim == 1, \"The observed array is not one dimensional.\"\n\n if sim_copy.size != obs_copy.size:\n raise RuntimeError(\"The two ndarrays are not the same size.\")\n\n # Treat missing data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain nan values\n all_treatment_array = np.ones(obs_copy.size, dtype=bool)\n\n if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_nan = np.isnan(sim_copy)\n obs_nan = np.isnan(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_nan] = replace_nan\n obs_copy[obs_nan] = replace_nan\n\n warnings.warn(\"Elements(s) {} contained NaN values in the simulated array and \"\n \"elements(s) {} contained NaN values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_nan)[0],\n np.where(obs_nan)[0]),\n UserWarning)\n else:\n # Getting the indices of the nan values, combining them, and informing user.\n nan_indices_fcst = ~np.isnan(sim_copy)\n nan_indices_obs = ~np.isnan(obs_copy)\n all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)\n\n warnings.warn(\"Row(s) {} contained NaN values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_nan_indices)[0]),\n UserWarning)\n\n if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):\n if replace_nan is not None:\n # Finding the NaNs\n sim_inf = np.isinf(sim_copy)\n obs_inf = np.isinf(obs_copy)\n # Replacing the NaNs with the input\n sim_copy[sim_inf] = replace_inf\n obs_copy[obs_inf] = replace_inf\n\n warnings.warn(\"Elements(s) {} contained Inf values in the simulated array and \"\n \"elements(s) {} contained Inf values in the observed array and have been \"\n \"replaced (Elements are zero indexed).\".format(np.where(sim_inf)[0],\n np.where(obs_inf)[0]),\n UserWarning)\n else:\n inf_indices_fcst = ~(np.isinf(sim_copy))\n inf_indices_obs = ~np.isinf(obs_copy)\n all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)\n\n warnings.warn(\n \"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows \"\n \"are zero indexed).\".format(np.where(~all_inf_indices)[0]),\n UserWarning\n )\n\n # Treat zero data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain zero values\n if remove_zero:\n if (obs_copy == 0).any() or (sim_copy == 0).any():\n zero_indices_fcst = ~(sim_copy == 0)\n zero_indices_obs = ~(obs_copy == 0)\n all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)\n\n warnings.warn(\n \"Row(s) {} contained zero values and the row(s) have been removed (Rows are \"\n \"zero indexed).\".format(np.where(~all_zero_indices)[0]),\n UserWarning\n )\n\n # Treat negative data in observed_array and simulated_array, rows in simulated_array or\n # observed_array that contain negative values\n\n # Ignore runtime warnings from comparing\n if remove_neg:\n with np.errstate(invalid='ignore'):\n obs_copy_bool = obs_copy < 0\n sim_copy_bool = sim_copy < 0\n\n if obs_copy_bool.any() or sim_copy_bool.any():\n neg_indices_fcst = ~sim_copy_bool\n neg_indices_obs = ~obs_copy_bool\n all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)\n all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)\n\n warnings.warn(\"Row(s) {} contained negative values and the row(s) have been \"\n \"removed (Rows are zero indexed).\".format(np.where(~all_neg_indices)[0]),\n UserWarning)\n\n obs_copy = obs_copy[all_treatment_array]\n sim_copy = sim_copy[all_treatment_array]\n\n return sim_copy, obs_copy\n"
] | # -*- coding: utf-8 -*-
"""
HydroErr contains a library of goodness of fit metrics that measure hydrologic skill.
Each metric is contained in function, and every function has the parameters to treat missing values as
well as remove zero and negative values from the timeseries data.
Each function contains two properties, name and abbr. These can be used in the Hydrostats package when creating tables
and adding metrics to the plots. Link to the hydrostats package: https://github.com/BYU-Hydroinformatics/Hydrostats.
An example of this functionality is shown below.
>>> import HydroErr as he
>>>
>>> he.acc.name
'Anomaly Correlation Coefficient'
>>> he.acc.abbr
'ACC'
"""
from __future__ import division
import numpy as np
from scipy.stats import gmean, rankdata
import warnings
__all__ = ['me', 'mae', 'mse', 'mle', 'male', 'msle', 'mde', 'mdae', 'mdse', 'ed', 'ned', 'rmse',
'rmsle', 'nrmse_range', 'nrmse_mean', 'nrmse_iqr', 'irmse', 'mase', 'r_squared',
'pearson_r', 'spearman_r', 'acc', 'mape', 'mapd', 'maape', 'smape1', 'smape2', 'd', 'd1',
'dmod', 'drel', 'dr', 'watt_m', 'mb_r', 'nse', 'nse_mod', 'nse_rel', 'kge_2009',
'kge_2012', 'lm_index', 'd1_p', 've', 'sa', 'sc', 'sid', 'sga', 'h1_mhe', 'h1_mahe',
'h1_rmshe', 'h2_mhe', 'h2_mahe', 'h2_rmshe', 'h3_mhe', 'h3_mahe', 'h3_rmshe', 'h4_mhe',
'h4_mahe', 'h4_rmshe', 'h5_mhe', 'h5_mahe', 'h5_rmshe', 'h6_mhe', 'h6_mahe', 'h6_rmshe',
'h7_mhe', 'h7_mahe', 'h7_rmshe', 'h8_mhe', 'h8_mahe', 'h8_rmshe', 'h10_mhe', 'h10_mahe',
'h10_rmshe', 'g_mean_diff', 'mean_var']
####################################################################################################
# General and Hydrological Error Metrics #
####################################################################################################
def me(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean error of the simulated and observed data.
.. image:: /pictures/ME.png
**Range:** -inf < MAE < inf, data units, closer to zero is better, indicates bias.
**Notes:** The mean error (ME) measures the difference between the simulated data and the
observed data. For the mean error, a smaller number indicates a better fit to the original
data. Note that if the error is in the form of random noise, the mean error will be very small,
which can skew the accuracy of this metric. ME is cumulative and will be small even if there
are large positive and negative errors that balance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean error value.
Examples
--------
Note that in this example the random noise cancels, leaving a very small ME.
>>> import HydroErr as he
>>> import numpy as np
>>> # Seed for reproducibility
>>> np.random.seed(54839)
>>> x = np.arange(100) / 20
>>> sim = np.sin(x) + 2
>>> obs = sim * (((np.random.rand(100) - 0.5) / 10) + 1)
>>> he.me(sim, obs)
-0.006832220968967168
References
----------
- Fisher, R.A., 1920. A Mathematical Examination of the Methods of Determining the Accuracy of
an Observation by the Mean Error, and by the Mean Square Error. Monthly Notices of the Royal
Astronomical Society 80 758 - 770.
"""
# Treating missing values
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero)
return np.mean(simulated_array - observed_array)
def mae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute error of the simulated and observed data.
.. image:: /pictures/MAE.png
**Range:** 0 ≤ MAE < inf, data units, smaller is better.
**Notes:** The ME measures the absolute difference between the simulated data and the observed
data. For the mean abolute error, a smaller number indicates a better fit to the original data.
Also note that random errors do not cancel. Also referred to as an L1-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute error value.
References
----------
- Willmott, Cort J., and Kenji Matsuura. “Advantages of the Mean Absolute Error (MAE) over the
Root Mean Square Error (RMSE) in Assessing Average Model Performance.” Climate Research 30,
no. 1 (2005): 79–82.
- Willmott, Cort J., and Kenji Matsuura. “On the Use of Dimensioned Measures of Error to
Evaluate the Performance of Spatial Interpolators.” International Journal of Geographical
Information Science 20, no. 1 (2006): 89–102.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mae(sim, obs)
0.5666666666666665
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean(np.absolute(simulated_array - observed_array))
def mse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared error of the simulated and observed data.
.. image:: /pictures/MSE.png
**Range:** 0 ≤ MSE < inf, data units squared, smaller is better.
**Notes:** Random errors do not cancel, highlights larger errors, also referred to as a
squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mse(sim, obs)
0.4333333333333333
References
----------
- Wang, Zhou, and Alan C. Bovik. “Mean Squared Error: Love It or Leave It? A New Look at Signal
Fidelity Measures.” IEEE Signal Processing Magazine 26, no. 1 (2009): 98–117.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean((simulated_array - observed_array) ** 2)
def mle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean log error of the simulated and observed data.
.. image:: /pictures/MLE.png
**Range:** -inf < MLE < inf, data units, closer to zero is better.
**Notes** Same as the mean erro (ME) only use log ratios as the error term. Limits the impact of outliers, more
evenly weights high and low data values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mle(sim, obs)
0.002961767058151136
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(sim_log - obs_log)
def male(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean absolute log error of the simulated and observed data.
.. image:: /pictures/MALE.png
**Range:** 0 ≤ MALE < inf, data units squared, smaller is better.
**Notes** Same as MAE only use log ratios as the error term. Limits the impact of outliers,
more evenly weights high and low flows.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.male(sim, obs), 6)
0.090417
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(np.abs(sim_log - obs_log))
def msle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared log error of the simulated and observed data.
.. image:: /pictures/MSLE.png
**Range:** 0 ≤ MSLE < inf, data units squared, smaller is better.
**Notes** Same as the mean squared error (MSE) only use log ratios as the error term. Limits
the impact of outliers, more evenly weights high and low values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.msle(sim, obs), 6)
0.010426
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean((sim_log - obs_log) ** 2)
def mde(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median error (MdE) between the simulated and observed data.
.. image:: /pictures/MdE.png
**Range** -inf < MdE < inf, closer to zero is better.
**Notes** This metric indicates bias. It is similar to the mean error (ME), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mde(sim, obs)
-0.10000000000000009
Returns
-------
float
The median error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(simulated_array - observed_array)
def mdae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median absolute error (MdAE) between the simulated and observed data.
.. image:: /pictures/MdAE.png
**Range** 0 ≤ MdAE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean absolute error (MAE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdae(sim, obs)
0.75
Returns
-------
float
The median absolute error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(np.abs(simulated_array - observed_array))
def mdse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median squared error (MdSE) between the simulated and observed data.
.. image:: /pictures/MdSE.png
**Range** 0 ≤ MdSE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean squared error (MSE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdse(sim, obs)
0.625
Returns
-------
float
The median squared error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median((simulated_array - observed_array) ** 2)
def ed(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Euclidean distance between predicted and observed values in vector space.
.. image:: /pictures/ED.png
**Range** 0 ≤ ED < inf, smaller is better.
**Notes** Also sometimes referred to as the L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ed(sim, obs)
1.63707055437449
Returns
-------
float
The euclidean distance error value.
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.linalg.norm(observed_array - simulated_array)
def ned(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the normalized Euclidian distance between the simulated and observed data in vector
space.
.. image:: /pictures/NED.png
**Range** 0 ≤ NED < inf, smaller is better.
**Notes** Also sometimes referred to as the squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The normalized euclidean distance value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ned(sim, obs)
0.2872053604165771
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array / np.mean(observed_array)
b = simulated_array / np.mean(simulated_array)
return np.linalg.norm(a - b)
def rmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square error between the simulated and observed data.
.. image:: /pictures/RMSE.png
**Range** 0 ≤ RMSE < inf, smaller is better.
**Notes:** The standard deviation of the residuals. A lower spread indicates that the points
are better concentrated around the line of best fit (linear). Random errors do not cancel.
This metric will highlights larger errors.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.rmse(sim, obs)
0.668331255192114
References
----------
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.sqrt(np.mean((simulated_array - observed_array) ** 2))
def rmsle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square log error between the simulated and observed data.
.. image:: /pictures/RMSLE.png
**Range:** 0 ≤ RMSLE < inf. Smaller is better, and it does not indicate bias.
**Notes:** Random errors do not cancel while using this metric. This metric limits the
impact of outliers by more evenly weighting high and low values. To calculate the log values,
each value in the observed and simulated array is increased by one unit in order to avoid
run-time errors and nan values (function np.log1p).
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square log error value.
Examples
--------
Notice that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.rmsle(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
"""
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf, remove_neg=remove_neg,
remove_zero=remove_zero)
return np.sqrt(np.mean(np.power(np.log1p(simulated_array) - np.log1p(observed_array), 2)))
def nrmse_range(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the range normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Range.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the range of the observed time series (x).
Normalizing allows comparison between data sets with different scales. The NRMSErange is the
most sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The range normalized root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_range(sim, obs)
0.0891108340256152
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_max = np.max(observed_array)
obs_min = np.min(observed_array)
return rmse_value / (obs_max - obs_min)
def nrmse_mean(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Mean.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the mean of the observed time series (x).
Normalizing allows comparison between data sets with different scales.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_mean(sim, obs)
0.11725109740212526
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_mean = np.mean(observed_array)
return rmse_value / obs_mean
def nrmse_iqr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the IQR normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_IQR.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the interquartile range of the observed time
series (x). Normalizing allows comparison between data sets with different scales.
The NRMSEquartile is the least sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The IQR normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_iqr(sim, obs)
0.2595461185212093
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
q1 = np.percentile(observed_array, 25)
q3 = np.percentile(observed_array, 75)
iqr = q3 - q1
return rmse_value / iqr
def irmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the inertial root mean square error (IRMSE) between the simulated and observed data.
.. image:: /pictures/IRMSE.png
**Range:** 0 ≤ IRMSE < inf, lower is better.
**Notes:** This metric is the RMSE devided by by the standard deviation of the gradient of the
observed timeseries data. This metric is meant to be help understand the ability of the model
to predict changes in observation.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The inertial root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.irmse(sim, obs)
0.14572738134831856
References
----------
- Daga, M., Deo, M.C., 2009. Alternative data-driven methods to estimate wind from waves by
inverse modeling. Natural Hazards 49(2) 293-310.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Getting the gradient of the observed data
obs_len = observed_array.size
obs_grad = observed_array[1:obs_len] - observed_array[0:obs_len - 1]
# Standard deviation of the gradient
obs_grad_std = np.std(obs_grad, ddof=1)
# Divide RMSE by the standard deviation of the gradient of the observed data
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
return rmse_value / obs_grad_std
def mase(simulated_array, observed_array, m=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute scaled error between the simulated and observed data.
.. image:: /pictures/MASE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
m: int
If given, indicates the seasonal period m. If not given, the default is 1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute scaled error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mase(sim, obs)
0.17341040462427745
References
----------
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
start = m
end = simulated_array.size - m
a = np.mean(np.abs(simulated_array - observed_array))
b = np.abs(observed_array[start:observed_array.size] - observed_array[:end])
return a / (np.sum(b) / end)
def pearson_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the pearson correlation coefficient.
.. image:: /pictures/R_pearson.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The pearson r coefficient measures linear correlation. It is sensitive to outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Pearson correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.pearson_r(sim, obs)
0.9610793632835262
References
----------
- Pearson, K. (1895). Note on regression and inheritance in the case of two parents.
Proceedings of the Royal Society of London, 58, 240-242.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
top = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1 = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2 = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
return top / (bot1 * bot2)
def spearman_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the spearman rank correlation coefficient.
.. image:: /pictures/R_spearman.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The spearman r coefficient measures the monotonic relation between simulated and
observed data. Because it uses a nonparametric measure of rank correlation, it is less sensitive
to outliers compared to the Pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spearman rank correlation coefficient.
Examples
----------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.spearman_r(sim, obs)
0.942857142857143
References
----------
- Spearman C (1904). "The proof and measurement of association between two things". American
Journal of Psychology. 15: 72–101. doi:10.2307/1412159
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rank_sim = rankdata(simulated_array)
rank_obs = rankdata(observed_array)
mean_rank_sim = np.mean(rank_sim)
mean_rank_obs = np.mean(rank_obs)
top = np.mean((rank_obs - mean_rank_obs) * (rank_sim - mean_rank_sim))
bot = np.sqrt(
np.mean((rank_obs - mean_rank_obs) ** 2) * np.mean((rank_sim - mean_rank_sim) ** 2))
return top / bot
def r_squared(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Coefficient of Determination (r2).
.. image:: /pictures/r2.png
**Range:** 0 ≤ r2 ≤ 1. 1 indicates perfect correlation, 0 indicates complete randomness.
**Notes:** The Coefficient of Determination measures the linear relation between simulated and
observed data. Because it is the pearson correlation coefficient squared, it is more heavily
affected by outliers than the pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The coefficient of determination (R^2).
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.r_squared(sim, obs)
0.9236735425294681
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array - np.mean(observed_array)
b = simulated_array - np.mean(simulated_array)
return (np.sum(a * b)) ** 2 / (np.sum(a ** 2) * np.sum(b ** 2))
def acc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the anomaly correlation coefficient (ACC).
.. image:: /pictures/ACC.png
**Range:** -1 ≤ ACC ≤ 1. -1 indicates perfect negative correlation of the variation
pattern of the anomalies, 0 indicates complete randomness of the variation patterns of the
anomalies, 1 indicates perfect correlation of the variation pattern of the anomalies.
**Notes:** Common measure in the verification of spatial fields. Measures the correlation
between the variation pattern of the simulated data compared to the observed data.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The anomaly correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.acc(sim, obs)
0.8008994694029383
References
----------
- Langland, Rolf H., and Ryan N. Maue. “Recent Northern Hemisphere Mid-Latitude Medium-Range
Deterministic Forecast Skill.” Tellus A: Dynamic Meteorology and Oceanography 64,
no. 1 (2012): 17531.
- Miyakoda, K., G. D. Hembree, R. F. Strickler, and I. Shulman. “Cumulative Results of Extended
Forecast Experiments I. Model Performance for Winter Cases.” Monthly Weather Review 100, no.
12(1972): 836–55.
- Murphy, Allan H., and Edward S. Epstein. “Skill Scores and Correlation Coefficients in Model
Verification.” Monthly Weather Review 117, no. 3 (1989): 572–82.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - np.mean(simulated_array)
b = observed_array - np.mean(observed_array)
c = np.std(observed_array, ddof=1) * np.std(simulated_array, ddof=1) * simulated_array.size
return np.dot(a, b / c)
def mape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the mean absolute percentage error (MAPE).
.. image:: /pictures/MAPE.png
**Range:** 0% ≤ MAPE ≤ inf. 0% indicates perfect correlation, a larger error indicates a
larger percent error in the data.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
c = 100 / simulated_array.size
return c * np.sum(b)
def mapd(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the mean absolute percentage deviation (MAPD).
.. image:: /pictures/MAPD.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage deviation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mapd(sim, obs)
0.10526315789473682
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(np.abs(observed_array))
return a / b
def maape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the Mean Arctangent Absolute Percentage Error (MAAPE).
.. image:: /pictures/MAAPE.png
**Range:** 0 ≤ MAAPE < π/2, does not indicate bias, smaller is better.
**Notes:** Represents the mean absolute error as a percentage of the observed values. Handles
0s in the observed data. This metric is not as biased as MAPE by under-over predictions.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean arctangent absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
- Kim, S., Kim, H., 2016. A new metric of absolute percentage error for intermittent demand
forecasts. International Journal of Forecasting 32(3) 669-679.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
return np.mean(np.arctan(b))
def smape1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (1) (SMAPE1).
.. image:: /pictures/SMAPE1.png
**Range:** 0 ≤ SMAPE1 < 100%, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (1).
Examples
--------
Note that if we switch the simulated and observed arrays the result is the same
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape1(sim, obs)
5.871915694397428
>>> he.smape1(obs, sim)
5.871915694397428
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 100 / simulated_array.size
b = np.abs(simulated_array - observed_array)
c = np.abs(simulated_array) + np.abs(observed_array)
return a * np.sum(b / c)
def smape2(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (2) (SMAPE2).
.. image:: /pictures/SMAPE2.png
**Range:** 0 ≤ SMAPE1 < 200%, does not indicate bias, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE with only positive metric values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (2).
Examples
--------
Note that switching the simulated and observed arrays yields the same results
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape2(sim, obs)
11.743831388794856
>>> he.smape2(obs, sim)
11.743831388794856
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = (simulated_array + observed_array) / 2
c = 100 / simulated_array.size
return c * np.sum(np.abs(a / b))
def d(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d).
.. image:: /pictures/d.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d(sim, obs)
0.978477353035657
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (observed_array - simulated_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
return 1 - (np.sum(a) / np.sum((b + c) ** 2))
def d1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d1).
.. image:: /pictures/d1.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric. Compared
to the other index of agreement (d) it has a reduced impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (d1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1(sim, obs)
0.8434782608695652
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
obs_mean = np.mean(observed_array)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.abs(simulated_array - obs_mean)
c = np.abs(observed_array - obs_mean)
return 1 - np.sum(a) / np.sum(b + c)
def dr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the refined index of agreement (dr).
.. image:: /pictures/dr.png
**Range:** -1 ≤ dr < 1, does not indicate bias, larger is better.
**Notes:** Reformulation of Willmott’s index of agreement. This metric was created to address
issues in the index of agreement and the Nash-Sutcliffe efficiency metric. Meant to be a
flexible metric for use in climatology.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The refined index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dr(sim, obs)
0.847457627118644
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = 2 * np.sum(np.abs(observed_array - observed_array.mean()))
if a <= b:
return 1 - (a / b)
else:
return (b / a) - 1
def drel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the relative index of agreement (drel).
.. image:: /pictures/drel.png
**Range:** 0 ≤ drel < 1, does not indicate bias, larger is better.
**Notes:** Instead of absolute differences, this metric uses relative differences.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.drel(sim, obs)
0.9740868625579597
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = ((simulated_array - observed_array) / observed_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = ((b + c) / np.mean(observed_array)) ** 2
return 1 - (np.sum(a) / np.sum(e))
def dmod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the modified index of agreement (dmod).
.. image:: /pictures/dmod.png
**Range:** 0 ≤ dmod < 1, does not indicate bias, larger is better.
**Notes:** When j=1, this metric is the same as d1. As j becomes larger, outliers have a larger
impact on the value.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
Optional input indicating the j values desired. A higher j places more emphasis on
outliers. j is 1 by default.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified index of agreement.
Examples
--------
Note that using the default is the same as calculating the d1 metric. Changing the value of j
modification of the metric.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dmod(sim, obs) # Same as d1
0.8434782608695652
>>> he.dmod(sim, obs, j=1.5)
0.9413310986805733
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = (b + c) ** j
return 1 - (np.sum(a) / np.sum(e))
def watt_m(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute Watterson's M (M).
.. image:: /pictures/M.png
**Range:** -1 ≤ M < 1, does not indicate bias, larger is better.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
Watterson's M value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.watt_m(sim, obs)
0.8307913876595929
References
----------
- Watterson, I.G., 1996. Non‐dimensional measures of climate model performance. International
Journal of Climatology 16(4) 379-391.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 2 / np.pi
b = np.mean((simulated_array - observed_array) ** 2) # MSE
c = np.std(observed_array, ddof=1) ** 2 + np.std(simulated_array, ddof=1) ** 2
e = (np.mean(simulated_array) - np.mean(observed_array)) ** 2
f = c + e
return a * np.arcsin(1 - (b / f))
def mb_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute Mielke-Berry R value (MB R).
.. image:: /pictures/MB_R.png
**Range:** 0 ≤ MB R < 1, does not indicate bias, larger is better.
**Notes:** Compares prediction to probability it arose by chance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Mielke-Berry R value.
Notes
-----
If a more optimized version is desired, the `numba package <http://numba.pydata.org/doc.html>`_ can be implemented
for a much more optimized performance when computing this metric. An example is given below.
>>> from numba import njit, prange
>>> @njit(parallel=True, fastmath=True)
>>> def mb_par_fastmath(pred, obs): # uses LLVM compiler
>>> assert pred.size == obs.size
>>> n = pred.size
>>> tot = 0.0
>>> mae = 0.0
>>> for i in range(n):
>>> for j in prange(n):
>>> tot += abs(pred[i] - obs[j])
>>> mae += abs(pred[i] - obs[i])
>>> mae = mae / n
>>> mb = 1 - ((n ** 2) * mae / tot)
>>>
>>> return mb
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mb_r(sim, obs)
0.7726315789473684
References
----------
- Berry, K.J., Mielke, P.W., 1988. A Generalization of Cohen's Kappa Agreement Measure to
Interval Measurement and Multiple Raters. Educational and Psychological Measurement 48(4)
921-933.
- Mielke, P.W., Berry, K.J., 2007. Permutation methods: a distance function approach.
Springer Science & Business Media.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Calculate metric
n = simulated_array.size
tot = 0.0
for i in range(n):
tot = tot + np.sum(np.abs(simulated_array - observed_array[i]))
mae_val = np.sum(np.abs(simulated_array - observed_array)) / n
mb = 1 - ((n ** 2) * mae_val / tot)
return mb
def nse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Nash-Sutcliffe Efficiency.
.. image:: /pictures/NSE.png
**Range:** -inf < NSE < 1, does not indicate bias, larger is better.
**Notes:** The Nash-Sutcliffe efficiency metric compares prediction values to naive predictions
(i.e. average value). One major flaw of this metric is that it punishes a higher variance in
the observed values (denominator). This metric is analogous to the mean absolute error skill
score (MAESS) using the mean flow as a benchmark.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Nash-Sutcliffe Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse(sim, obs)
0.922093023255814
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
- McCuen, R.H., Knight, Z., Cutter, A.G., 2006. Evaluation of the Nash-Sutcliffe Efficiency
Index. Journal of Hydraulic Engineering.
- Nash, J.E., Sutcliffe, J.V., 1970. River flow forecasting through conceptual models part
I — A discussion of principles. Journal of Hydrology 282-290.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** 2
b = (np.abs(observed_array - np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def nse_mod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the modified Nash-Sutcliffe efficiency (NSE mod).
.. image:: /pictures/NSEmod.png
**Range:** -inf < NSE (mod) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
If given, sets the value of j to the input. j is 1 by default. A higher j gives more
emphasis to outliers
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_mod(sim, obs)
0.6949152542372882
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = (np.abs(observed_array - np.mean(observed_array))) ** j
return 1 - (np.sum(a) / np.sum(b))
def nse_rel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the relative Nash-Sutcliffe efficiency (NSE rel).
.. image:: /pictures/NSErel.png
**Range:** -inf < NSE (rel) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_rel(sim, obs)
0.9062004687708474
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs((simulated_array - observed_array) / observed_array)) ** 2
b = (np.abs((observed_array - np.mean(observed_array)) / np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def kge_2009(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""Compute the Kling-Gupta efficiency (2009).
.. image:: /pictures/KGE_2009.png
**Range:** -inf < KGE (2009) < 1, larger is better.
**Notes:** Gupta et al. (2009) created this metric to demonstrate the relative importance of
the three components of the NSE, which are correlation, bias and variability. This was done
with hydrologic modeling as the context. This metric is meant to address issues with the NSE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), Alpha, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, alpha, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2009) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2009(sim, obs)
0.912223072345668
>>> he.kge_2009(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.927910707932087, 1.0058823529411764, 0.9181073779138655)
References
----------
- Gupta, H. V., Kling, H., Yilmaz, K. K., & Martinez, G. F. (2009). Decomposition of the mean
squared error and NSE performance criteria: Implications for improving hydrological modelling.
Journal of Hydrology, 377(1-2), 80-91.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array, ddof=1)
obs_sigma = np.std(observed_array, ddof=1)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
if obs_mean != 0:
beta = sim_mean / obs_mean
else:
beta = np.nan
# Relative variability between simulated and observed values
if obs_sigma != 0:
alpha = sim_sigma / obs_sigma
else:
alpha = np.nan
if not np.isnan(beta) and not np.isnan(alpha):
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (alpha - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Alpha is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, alpha, beta, kge
else:
return kge
def kge_2012(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""
Compute the Kling-Gupta efficiency (2012).
.. image:: /pictures/KGE_2012.png
**Range:** -inf < KGE (2012) < 1, does not indicate bias, larger is better.
**Notes:** The modified version of the KGE (2009). Kling proposed this version to avoid
cross-correlation between bias and variability ratios.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), gamma, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, gamma, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2012) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2012(sim, obs)
0.9122230723456678
>>> he.kge_2012(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.9224843295231272, 1.0058823529411764, 0.9132923608280753)
References
----------
- Kling, H., Fuchs, M., & Paulin, M. (2012). Runoff conditions in the upper Danube basin under
an ensemble of climate change scenarios. Journal of Hydrology, 424, 264-277.
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array)
obs_sigma = np.std(observed_array)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
beta = sim_mean / obs_mean
# CV is the coefficient of variation (standard deviation / mean)
sim_cv = sim_sigma / sim_mean
obs_cv = obs_sigma / obs_mean
# Variability Ratio, or the ratio of simulated CV to observed CV
gam = sim_cv / obs_cv
if obs_mean != 0 and obs_sigma != 0 and sim_mean != 0:
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (gam - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
if sim_mean == 0:
warnings.warn(
'Warning: The simulated data mean is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, gam, beta, kge
else:
return kge
def lm_index(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""
Compute the Legate-McCabe Efficiency Index.
.. image:: /pictures/E1p.png
**Range:** 0 ≤ E1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.lm_index(sim, obs)
0.6949152542372882
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
mean_obs = np.mean(observed_array)
if obs_bar_p is not None:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def d1_p(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""Compute the Legate-McCabe Index of Agreement.
.. image:: /pictures/D1p.png
**Range:** 0 ≤ d1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1_p(sim, obs)
0.8434782608695652
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
if obs_bar_p is not None:
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - obs_bar_p) + np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
mean_obs = np.mean(observed_array)
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - mean_obs) + np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def ve(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Volumetric Efficiency (VE).
.. image:: /pictures/VE.png
**Range:** 0 ≤ VE < 1 smaller is better, does not indicate bias.
**Notes:** Represents the error as a percentage of flow.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Volumetric Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ve(sim, obs)
0.8947368421052632
References
----------
- Criss, R.E., Winston, W.E., 2008. Do Nash values have value? Discussion and alternate
proposals. Hydrological Processes 22(14) 2723.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(observed_array)
return 1 - (a / b)
def sa(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Angle (SA).
.. image:: /pictures/SA.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral angle metric measures the angle between the two vectors in hyperspace.
It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Angle value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sa(sim, obs)
0.10816831366492945
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(simulated_array, observed_array)
b = np.linalg.norm(simulated_array) * np.linalg.norm(observed_array)
return np.arccos(a / b)
def sc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Correlation (SC).
.. image:: /pictures/SC.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral correlation metric measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Correlation value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sc(sim, obs)
0.27991341383646606
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(observed_array - np.mean(observed_array), simulated_array - np.mean(simulated_array))
b = np.linalg.norm(observed_array - np.mean(observed_array))
c = np.linalg.norm(simulated_array - np.mean(simulated_array))
e = b * c
return np.arccos(a / e)
def sid(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Information Divergence (SID).
.. image:: /pictures/SID.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral information divergence measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral information divergence value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sid(sim, obs)
0.03517616895318012
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
first = (observed_array / np.mean(observed_array)) - (
simulated_array / np.mean(simulated_array))
second1 = np.log10(observed_array) - np.log10(np.mean(observed_array))
second2 = np.log10(simulated_array) - np.log10(np.mean(simulated_array))
return np.dot(first, second1 - second2)
def sga(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Gradient Angle (SGA).
.. image:: /pictures/SGA.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral gradient angle measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
SG is the gradient of the simulated or observed time series.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Gradient Angle.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sga(sim, obs)
0.26764286472739834
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sgx = observed_array[1:] - observed_array[:observed_array.size - 1]
sgy = simulated_array[1:] - simulated_array[:simulated_array.size - 1]
a = np.dot(sgx, sgy)
b = np.linalg.norm(sgx) * np.linalg.norm(sgy)
return np.arccos(a / b)
####################################################################################################
# H Metrics: Methods from Tornqvist L, Vartia P, and Vartia YO. (1985) #
####################################################################################################
def h1_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the H1 mean error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mhe(sim, obs)
0.002106551840594386
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(h)
def h1_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H1 absolute error.
.. image:: /pictures/H1.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The H1 absolute error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mahe(sim, obs)
0.11639226612630865
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(np.abs(h))
def h1_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H1 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean squared H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_rmshe(sim, obs)
0.12865571253672756
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.sqrt(np.mean(h ** 2))
def h2_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean error.
.. image:: /pictures/H2.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mhe(sim, obs)
-0.015319829424307036
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(h)
def h2_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean absolute error.
.. image:: /pictures/H2.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mahe(sim, obs)
0.11997591408039167
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(np.abs(h))
def h2_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_rmshe(sim, obs)
0.1373586680669673
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.sqrt(np.mean(h ** 2))
def h3_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 mean error.
.. image:: /pictures/H3.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mhe(sim, obs)
-0.006322019630356533
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(h)
def h3_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H3 mean absolute error.
.. image:: /pictures/H3.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mahe(sim, obs)
0.11743831388794855
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(np.abs(h))
def h3_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 root mean square error.
.. image:: /pictures/H3.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.sqrt(np.mean(h ** 2))
def h4_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mhe(sim, obs)
-0.0064637371129817
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(h)
def h4_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H4 mean absolute error.
.. image:: /pictures/H4.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mahe(sim, obs)
0.11781032209144082
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(np.abs(h))
def h4_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_rmshe(sim, obs)
0.13200901963465006
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.sqrt(np.mean(h ** 2))
def h5_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean error.
.. image:: /pictures/H5.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mhe(sim, obs)
-0.006606638791856322
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(h)
def h5_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean absolute error.
.. image:: /pictures/H5.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mahe(sim, obs)
0.11818409010335018
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(np.abs(h))
def h5_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 root mean square error.
.. image:: /pictures/H5.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_rmshe(sim, obs)
0.13254476469410933
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h6_mhe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H6 mean error.
.. image:: /pictures/H6.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mhe(sim, obs)
-0.006322019630356514
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(h)
def h6_rmshe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the H6 root mean square error.
.. image:: /pictures/H6.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h7_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean error.
.. image:: /pictures/H7.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mhe(sim, obs)
0.0026331898007430263
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(h)
def h7_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean absolute error.
.. image:: /pictures/H7.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mahe(sim, obs)
0.14549033265788583
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(np.abs(h))
def h7_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 root mean square error.
.. image:: /pictures/H7.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_rmshe(sim, obs)
0.16081964067090945
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
def h8_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H8 mean error.
.. image:: /pictures/H8.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mhe(sim, obs)
0.0018056158633666466
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(h)
def h8_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 mean absolute error.
.. image:: /pictures/H8.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mahe(sim, obs)
0.099764799536836
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(np.abs(h))
def h8_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 root mean square error.
.. image:: /pictures/H8.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_rmshe(sim, obs)
0.11027632503148076
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
# def h9(simulated_array, observed_array, h_type='mhe', k=1):
# h = (simulated_array / observed_array - 1) / \
# np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
# if h_type == 'mhe':
# return h.mean()
# elif h_type == 'ahe':
# return np.abs(h).mean()
# elif h_type == 'rmshe':
# return np.sqrt((h**2).mean())
# else:
# raise RuntimeError("The three types available are 'mhe', 'ahe', and 'rmshe'.")
def h10_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean error.
.. image:: /pictures/H10.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h10_mhe(sim, obs)
-0.0012578676058971154
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(h)
def h10_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean absolute error.
.. image:: /pictures/H10.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_mahe(sim, obs), 6)
0.094636
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(np.abs(h))
def h10_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 root mean square error.
.. image:: /pictures/H10.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_rmshe(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.sqrt(np.mean(h ** 2))
###################################################################################################
# Statistical Error Metrics for Distribution Testing #
###################################################################################################
def g_mean_diff(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the geometric mean difference.
.. image:: /pictures/GMD.png
**Range:**
**Notes:** For the difference of geometric means, the geometric mean is computed for each of
two samples then their difference is taken.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The geometric mean difference value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.g_mean_diff(sim, obs)
0.988855412098022
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.exp(gmean(sim_log) - gmean(obs_log))
def mean_var(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the mean variance.
.. image:: /pictures/MV.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean variance.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.mean_var(sim, obs), 6)
0.010641
References
----------
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.var(np.log1p(observed_array) - np.log1p(simulated_array))
####################################################################################################
# HELPER FUNCTIONS AND API INFORMATION #
####################################################################################################
metric_names = [
'Mean Error', 'Mean Absolute Error', 'Mean Squared Error', 'Mean Log Error',
'Mean Absolute Log Error', 'Mean Squared Log Error', 'Median Error', 'Median Absolute Error',
'Median Squared Error', 'Eclidean Distance', 'Normalized Eclidean Distance',
'Root Mean Square Error', 'Root Mean Squared Log Error',
'Normalized Root Mean Square Error - Range', 'Normalized Root Mean Square Error - Mean',
'Normalized Root Mean Square Error - IQR', 'Inertial Root Mean Square Error',
'Mean Absolute Scaled Error', 'Coefficient of Determination', 'Pearson Correlation Coefficient',
'Spearman Rank Correlation Coefficient', 'Anomaly Correlation Coefficient',
'Mean Absolute Percentage Error', 'Mean Absolute Percentage Deviation',
'Mean Arctangent Absolute Percentage Error', 'Symmetric Mean Absolute Percentage Error (1)',
'Symmetric Mean Absolute Percentage Error (2)', 'Index of Agreement (d)',
'Index of Agreement (d1)', 'Modified Index of Agreement', 'Relative Index of Agreement',
'Index of Agreement Refined (dr)', "Watterson's M", 'Mielke-Berry R',
'Nash-Sutcliffe Efficiency', 'Modified Nash-Sutcliffe Efficiency',
'Relative Nash-Sutcliffe Efficiency', 'Kling-Gupta Efficiency (2009)',
'Kling-Gupta Efficiency (2012)', 'Legate-McCabe Efficiency Index',
'Legate-McCabe Index of Agreement', 'Volumetric Efficiency', 'Spectral Angle',
'Spectral Correlation', 'Spectral Information Divergence', 'Spectral Gradient Angle',
'Mean H1 Error', 'Mean Absolute H1 Error', 'Root Mean Square H1 Error', 'Mean H2 Error',
'Mean Absolute H2 Error', 'Root Mean Square H2 Error', 'Mean H3 Error',
'Mean Absolute H3 Error', 'Root Mean Square H3 Error', 'Mean H4 Error',
'Mean Absolute H4 Error', 'Root Mean Square H4 Error', 'Mean H5 Error',
'Mean Absolute H5 Error', 'Root Mean Square H5 Error', 'Mean H6 Error',
'Mean Absolute H6 Error', 'Root Mean Square H6 Error', 'Mean H7 Error',
'Mean Absolute H7 Error', 'Root Mean Square H7 Error', 'Mean H8 Error',
'Mean Absolute H8 Error', 'Root Mean Square H8 Error', 'Mean H10 Error',
'Mean Absolute H10 Error', 'Root Mean Square H10 Error', 'Geometric Mean Difference',
'Mean Variance'
]
metric_abbr = [
'ME', 'MAE', 'MSE', 'MLE', 'MALE', 'MSLE', 'MdE', 'MdAE', 'MdSE', 'ED', 'NED', 'RMSE', 'RMSLE',
'NRMSE (Range)', 'NRMSE (Mean)', 'NRMSE (IQR)', 'IRMSE', 'MASE', 'r2', 'R (Pearson)',
'R (Spearman)', 'ACC', 'MAPE', 'MAPD', 'MAAPE', 'SMAPE1', 'SMAPE2', 'd', 'd1', 'd (Mod.)',
'd (Rel.)', 'dr', 'M', '(MB) R', 'NSE', 'NSE (Mod.)', 'NSE (Rel.)', 'KGE (2009)', 'KGE (2012)',
"E1'", "D1'", 'VE', 'SA', 'SC', 'SID', 'SGA', 'H1 (MHE)', 'H1 (MAHE)', 'H1 (RMSHE)', 'H2 (MHE)',
'H2 (MAHE)', 'H2 (RMSHE)', 'H3 (MHE)', 'H3 (MAHE)', 'H3 (RMSHE)', 'H4 (MHE)', 'H4 (MAHE)',
'H4 (RMSHE)', 'H5 (MHE)', 'H5 (MAHE)', 'H5 (RMSHE)', 'H6 (MHE)', 'H6 (MAHE)', 'H6 (RMSHE)',
'H7 (MHE)', 'H7 (MAHE)', 'H7 (RMSHE)', 'H8 (MHE)', 'H8 (MAHE)', 'H8 (RMSHE)', 'H10 (MHE)',
'H10 (MAHE)', 'H10 (RMSHE)', 'GMD', 'MV'
]
function_list = [
me, mae, mse, mle, male, msle, mde, mdae, mdse, ed, ned, rmse, rmsle, nrmse_range, nrmse_mean,
nrmse_iqr, irmse, mase, r_squared, pearson_r, spearman_r, acc, mape, mapd, maape, smape1,
smape2, d, d1, dmod, drel, dr, watt_m, mb_r, nse, nse_mod, nse_rel, kge_2009, kge_2012,
lm_index, d1_p, ve, sa, sc, sid, sga, h1_mhe, h1_mahe, h1_rmshe, h2_mhe, h2_mahe, h2_rmshe,
h3_mhe, h3_mahe, h3_rmshe, h4_mhe, h4_mahe, h4_rmshe, h5_mhe, h5_mahe, h5_rmshe, h6_mhe,
h6_mahe, h6_rmshe, h7_mhe, h7_mahe, h7_rmshe, h8_mhe, h8_mahe, h8_rmshe, h10_mhe, h10_mahe,
h10_rmshe, g_mean_diff, mean_var,
]
# Assign some properties to each function for ease of use for users
for i in range(len(function_list)):
function_list[i].name = metric_names[i]
function_list[i].abbr = metric_abbr[i]
def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Removes the nan, negative, and inf values in two numpy arrays"""
sim_copy = np.copy(simulated_array)
obs_copy = np.copy(observed_array)
# Checking to see if the vectors are the same length
assert sim_copy.ndim == 1, "The simulated array is not one dimensional."
assert obs_copy.ndim == 1, "The observed array is not one dimensional."
if sim_copy.size != obs_copy.size:
raise RuntimeError("The two ndarrays are not the same size.")
# Treat missing data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain nan values
all_treatment_array = np.ones(obs_copy.size, dtype=bool)
if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_nan = np.isnan(sim_copy)
obs_nan = np.isnan(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_nan] = replace_nan
obs_copy[obs_nan] = replace_nan
warnings.warn("Elements(s) {} contained NaN values in the simulated array and "
"elements(s) {} contained NaN values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_nan)[0],
np.where(obs_nan)[0]),
UserWarning)
else:
# Getting the indices of the nan values, combining them, and informing user.
nan_indices_fcst = ~np.isnan(sim_copy)
nan_indices_obs = ~np.isnan(obs_copy)
all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)
warnings.warn("Row(s) {} contained NaN values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_nan_indices)[0]),
UserWarning)
if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_inf = np.isinf(sim_copy)
obs_inf = np.isinf(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_inf] = replace_inf
obs_copy[obs_inf] = replace_inf
warnings.warn("Elements(s) {} contained Inf values in the simulated array and "
"elements(s) {} contained Inf values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_inf)[0],
np.where(obs_inf)[0]),
UserWarning)
else:
inf_indices_fcst = ~(np.isinf(sim_copy))
inf_indices_obs = ~np.isinf(obs_copy)
all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)
warnings.warn(
"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows "
"are zero indexed).".format(np.where(~all_inf_indices)[0]),
UserWarning
)
# Treat zero data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain zero values
if remove_zero:
if (obs_copy == 0).any() or (sim_copy == 0).any():
zero_indices_fcst = ~(sim_copy == 0)
zero_indices_obs = ~(obs_copy == 0)
all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)
warnings.warn(
"Row(s) {} contained zero values and the row(s) have been removed (Rows are "
"zero indexed).".format(np.where(~all_zero_indices)[0]),
UserWarning
)
# Treat negative data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain negative values
# Ignore runtime warnings from comparing
if remove_neg:
with np.errstate(invalid='ignore'):
obs_copy_bool = obs_copy < 0
sim_copy_bool = sim_copy < 0
if obs_copy_bool.any() or sim_copy_bool.any():
neg_indices_fcst = ~sim_copy_bool
neg_indices_obs = ~obs_copy_bool
all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)
warnings.warn("Row(s) {} contained negative values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_neg_indices)[0]),
UserWarning)
obs_copy = obs_copy[all_treatment_array]
sim_copy = sim_copy[all_treatment_array]
return sim_copy, obs_copy
if __name__ == "__main__":
pass
|
BYU-Hydroinformatics/HydroErr | HydroErr/HydroErr.py | treat_values | python | def treat_values(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
sim_copy = np.copy(simulated_array)
obs_copy = np.copy(observed_array)
# Checking to see if the vectors are the same length
assert sim_copy.ndim == 1, "The simulated array is not one dimensional."
assert obs_copy.ndim == 1, "The observed array is not one dimensional."
if sim_copy.size != obs_copy.size:
raise RuntimeError("The two ndarrays are not the same size.")
# Treat missing data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain nan values
all_treatment_array = np.ones(obs_copy.size, dtype=bool)
if np.any(np.isnan(obs_copy)) or np.any(np.isnan(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_nan = np.isnan(sim_copy)
obs_nan = np.isnan(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_nan] = replace_nan
obs_copy[obs_nan] = replace_nan
warnings.warn("Elements(s) {} contained NaN values in the simulated array and "
"elements(s) {} contained NaN values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_nan)[0],
np.where(obs_nan)[0]),
UserWarning)
else:
# Getting the indices of the nan values, combining them, and informing user.
nan_indices_fcst = ~np.isnan(sim_copy)
nan_indices_obs = ~np.isnan(obs_copy)
all_nan_indices = np.logical_and(nan_indices_fcst, nan_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_nan_indices)
warnings.warn("Row(s) {} contained NaN values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_nan_indices)[0]),
UserWarning)
if np.any(np.isinf(obs_copy)) or np.any(np.isinf(sim_copy)):
if replace_nan is not None:
# Finding the NaNs
sim_inf = np.isinf(sim_copy)
obs_inf = np.isinf(obs_copy)
# Replacing the NaNs with the input
sim_copy[sim_inf] = replace_inf
obs_copy[obs_inf] = replace_inf
warnings.warn("Elements(s) {} contained Inf values in the simulated array and "
"elements(s) {} contained Inf values in the observed array and have been "
"replaced (Elements are zero indexed).".format(np.where(sim_inf)[0],
np.where(obs_inf)[0]),
UserWarning)
else:
inf_indices_fcst = ~(np.isinf(sim_copy))
inf_indices_obs = ~np.isinf(obs_copy)
all_inf_indices = np.logical_and(inf_indices_fcst, inf_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_inf_indices)
warnings.warn(
"Row(s) {} contained Inf or -Inf values and the row(s) have been removed (Rows "
"are zero indexed).".format(np.where(~all_inf_indices)[0]),
UserWarning
)
# Treat zero data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain zero values
if remove_zero:
if (obs_copy == 0).any() or (sim_copy == 0).any():
zero_indices_fcst = ~(sim_copy == 0)
zero_indices_obs = ~(obs_copy == 0)
all_zero_indices = np.logical_and(zero_indices_fcst, zero_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_zero_indices)
warnings.warn(
"Row(s) {} contained zero values and the row(s) have been removed (Rows are "
"zero indexed).".format(np.where(~all_zero_indices)[0]),
UserWarning
)
# Treat negative data in observed_array and simulated_array, rows in simulated_array or
# observed_array that contain negative values
# Ignore runtime warnings from comparing
if remove_neg:
with np.errstate(invalid='ignore'):
obs_copy_bool = obs_copy < 0
sim_copy_bool = sim_copy < 0
if obs_copy_bool.any() or sim_copy_bool.any():
neg_indices_fcst = ~sim_copy_bool
neg_indices_obs = ~obs_copy_bool
all_neg_indices = np.logical_and(neg_indices_fcst, neg_indices_obs)
all_treatment_array = np.logical_and(all_treatment_array, all_neg_indices)
warnings.warn("Row(s) {} contained negative values and the row(s) have been "
"removed (Rows are zero indexed).".format(np.where(~all_neg_indices)[0]),
UserWarning)
obs_copy = obs_copy[all_treatment_array]
sim_copy = sim_copy[all_treatment_array]
return sim_copy, obs_copy | Removes the nan, negative, and inf values in two numpy arrays | train | https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L6210-L6315 | null | # -*- coding: utf-8 -*-
"""
HydroErr contains a library of goodness of fit metrics that measure hydrologic skill.
Each metric is contained in function, and every function has the parameters to treat missing values as
well as remove zero and negative values from the timeseries data.
Each function contains two properties, name and abbr. These can be used in the Hydrostats package when creating tables
and adding metrics to the plots. Link to the hydrostats package: https://github.com/BYU-Hydroinformatics/Hydrostats.
An example of this functionality is shown below.
>>> import HydroErr as he
>>>
>>> he.acc.name
'Anomaly Correlation Coefficient'
>>> he.acc.abbr
'ACC'
"""
from __future__ import division
import numpy as np
from scipy.stats import gmean, rankdata
import warnings
__all__ = ['me', 'mae', 'mse', 'mle', 'male', 'msle', 'mde', 'mdae', 'mdse', 'ed', 'ned', 'rmse',
'rmsle', 'nrmse_range', 'nrmse_mean', 'nrmse_iqr', 'irmse', 'mase', 'r_squared',
'pearson_r', 'spearman_r', 'acc', 'mape', 'mapd', 'maape', 'smape1', 'smape2', 'd', 'd1',
'dmod', 'drel', 'dr', 'watt_m', 'mb_r', 'nse', 'nse_mod', 'nse_rel', 'kge_2009',
'kge_2012', 'lm_index', 'd1_p', 've', 'sa', 'sc', 'sid', 'sga', 'h1_mhe', 'h1_mahe',
'h1_rmshe', 'h2_mhe', 'h2_mahe', 'h2_rmshe', 'h3_mhe', 'h3_mahe', 'h3_rmshe', 'h4_mhe',
'h4_mahe', 'h4_rmshe', 'h5_mhe', 'h5_mahe', 'h5_rmshe', 'h6_mhe', 'h6_mahe', 'h6_rmshe',
'h7_mhe', 'h7_mahe', 'h7_rmshe', 'h8_mhe', 'h8_mahe', 'h8_rmshe', 'h10_mhe', 'h10_mahe',
'h10_rmshe', 'g_mean_diff', 'mean_var']
####################################################################################################
# General and Hydrological Error Metrics #
####################################################################################################
def me(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean error of the simulated and observed data.
.. image:: /pictures/ME.png
**Range:** -inf < MAE < inf, data units, closer to zero is better, indicates bias.
**Notes:** The mean error (ME) measures the difference between the simulated data and the
observed data. For the mean error, a smaller number indicates a better fit to the original
data. Note that if the error is in the form of random noise, the mean error will be very small,
which can skew the accuracy of this metric. ME is cumulative and will be small even if there
are large positive and negative errors that balance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean error value.
Examples
--------
Note that in this example the random noise cancels, leaving a very small ME.
>>> import HydroErr as he
>>> import numpy as np
>>> # Seed for reproducibility
>>> np.random.seed(54839)
>>> x = np.arange(100) / 20
>>> sim = np.sin(x) + 2
>>> obs = sim * (((np.random.rand(100) - 0.5) / 10) + 1)
>>> he.me(sim, obs)
-0.006832220968967168
References
----------
- Fisher, R.A., 1920. A Mathematical Examination of the Methods of Determining the Accuracy of
an Observation by the Mean Error, and by the Mean Square Error. Monthly Notices of the Royal
Astronomical Society 80 758 - 770.
"""
# Treating missing values
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero)
return np.mean(simulated_array - observed_array)
def mae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute error of the simulated and observed data.
.. image:: /pictures/MAE.png
**Range:** 0 ≤ MAE < inf, data units, smaller is better.
**Notes:** The ME measures the absolute difference between the simulated data and the observed
data. For the mean abolute error, a smaller number indicates a better fit to the original data.
Also note that random errors do not cancel. Also referred to as an L1-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute error value.
References
----------
- Willmott, Cort J., and Kenji Matsuura. “Advantages of the Mean Absolute Error (MAE) over the
Root Mean Square Error (RMSE) in Assessing Average Model Performance.” Climate Research 30,
no. 1 (2005): 79–82.
- Willmott, Cort J., and Kenji Matsuura. “On the Use of Dimensioned Measures of Error to
Evaluate the Performance of Spatial Interpolators.” International Journal of Geographical
Information Science 20, no. 1 (2006): 89–102.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mae(sim, obs)
0.5666666666666665
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean(np.absolute(simulated_array - observed_array))
def mse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared error of the simulated and observed data.
.. image:: /pictures/MSE.png
**Range:** 0 ≤ MSE < inf, data units squared, smaller is better.
**Notes:** Random errors do not cancel, highlights larger errors, also referred to as a
squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mse(sim, obs)
0.4333333333333333
References
----------
- Wang, Zhou, and Alan C. Bovik. “Mean Squared Error: Love It or Leave It? A New Look at Signal
Fidelity Measures.” IEEE Signal Processing Magazine 26, no. 1 (2009): 98–117.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.mean((simulated_array - observed_array) ** 2)
def mle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean log error of the simulated and observed data.
.. image:: /pictures/MLE.png
**Range:** -inf < MLE < inf, data units, closer to zero is better.
**Notes** Same as the mean erro (ME) only use log ratios as the error term. Limits the impact of outliers, more
evenly weights high and low data values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.mle(sim, obs)
0.002961767058151136
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(sim_log - obs_log)
def male(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean absolute log error of the simulated and observed data.
.. image:: /pictures/MALE.png
**Range:** 0 ≤ MALE < inf, data units squared, smaller is better.
**Notes** Same as MAE only use log ratios as the error term. Limits the impact of outliers,
more evenly weights high and low flows.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.male(sim, obs), 6)
0.090417
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean(np.abs(sim_log - obs_log))
def msle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the mean squared log error of the simulated and observed data.
.. image:: /pictures/MSLE.png
**Range:** 0 ≤ MSLE < inf, data units squared, smaller is better.
**Notes** Same as the mean squared error (MSE) only use log ratios as the error term. Limits
the impact of outliers, more evenly weights high and low values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean squared log error value.
Examples
--------
Note that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> np.round(he.msle(sim, obs), 6)
0.010426
References
----------
- Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?”
The American Statistician 39, no. 1 (1985): 43–46.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.mean((sim_log - obs_log) ** 2)
def mde(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median error (MdE) between the simulated and observed data.
.. image:: /pictures/MdE.png
**Range** -inf < MdE < inf, closer to zero is better.
**Notes** This metric indicates bias. It is similar to the mean error (ME), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mde(sim, obs)
-0.10000000000000009
Returns
-------
float
The median error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(simulated_array - observed_array)
def mdae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median absolute error (MdAE) between the simulated and observed data.
.. image:: /pictures/MdAE.png
**Range** 0 ≤ MdAE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean absolute error (MAE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdae(sim, obs)
0.75
Returns
-------
float
The median absolute error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median(np.abs(simulated_array - observed_array))
def mdse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the median squared error (MdSE) between the simulated and observed data.
.. image:: /pictures/MdSE.png
**Range** 0 ≤ MdSE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean squared error (MSE), only it takes the
median rather than the mean. Median measures reduces the impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
Note that the last outlier residual in the time series is negated using the median.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 100])
>>> he.mdse(sim, obs)
0.625
Returns
-------
float
The median squared error value.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.median((simulated_array - observed_array) ** 2)
def ed(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Euclidean distance between predicted and observed values in vector space.
.. image:: /pictures/ED.png
**Range** 0 ≤ ED < inf, smaller is better.
**Notes** Also sometimes referred to as the L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ed(sim, obs)
1.63707055437449
Returns
-------
float
The euclidean distance error value.
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.linalg.norm(observed_array - simulated_array)
def ned(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the normalized Euclidian distance between the simulated and observed data in vector
space.
.. image:: /pictures/NED.png
**Range** 0 ≤ NED < inf, smaller is better.
**Notes** Also sometimes referred to as the squared L2-norm.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The normalized euclidean distance value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ned(sim, obs)
0.2872053604165771
References
----------
- Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying
uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research
and Applications, 26(2), 137-156.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array / np.mean(observed_array)
b = simulated_array / np.mean(simulated_array)
return np.linalg.norm(a - b)
def rmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square error between the simulated and observed data.
.. image:: /pictures/RMSE.png
**Range** 0 ≤ RMSE < inf, smaller is better.
**Notes:** The standard deviation of the residuals. A lower spread indicates that the points
are better concentrated around the line of best fit (linear). Random errors do not cancel.
This metric will highlights larger errors.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.rmse(sim, obs)
0.668331255192114
References
----------
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.sqrt(np.mean((simulated_array - observed_array) ** 2))
def rmsle(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the root mean square log error between the simulated and observed data.
.. image:: /pictures/RMSLE.png
**Range:** 0 ≤ RMSLE < inf. Smaller is better, and it does not indicate bias.
**Notes:** Random errors do not cancel while using this metric. This metric limits the
impact of outliers by more evenly weighting high and low values. To calculate the log values,
each value in the observed and simulated array is increased by one unit in order to avoid
run-time errors and nan values (function np.log1p).
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square log error value.
Examples
--------
Notice that the value is very small because it is in log space.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.rmsle(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
- Willmott, C.J., Matsuura, K., 2005. Advantages of the mean absolute error (MAE) over the
root mean square error (RMSE) in assessing average model performance.
Climate Research 30(1) 79-82.
"""
simulated_array, observed_array = treat_values(simulated_array, observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf, remove_neg=remove_neg,
remove_zero=remove_zero)
return np.sqrt(np.mean(np.power(np.log1p(simulated_array) - np.log1p(observed_array), 2)))
def nrmse_range(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the range normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Range.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the range of the observed time series (x).
Normalizing allows comparison between data sets with different scales. The NRMSErange is the
most sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The range normalized root mean square error value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_range(sim, obs)
0.0891108340256152
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_max = np.max(observed_array)
obs_min = np.min(observed_array)
return rmse_value / (obs_max - obs_min)
def nrmse_mean(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_Mean.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the mean of the observed time series (x).
Normalizing allows comparison between data sets with different scales.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_mean(sim, obs)
0.11725109740212526
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
obs_mean = np.mean(observed_array)
return rmse_value / obs_mean
def nrmse_iqr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the IQR normalized root mean square error between the simulated and observed data.
.. image:: /pictures/NRMSE_IQR.png
**Range:** 0 ≤ NRMSE < inf.
**Notes:** This metric is the RMSE normalized by the interquartile range of the observed time
series (x). Normalizing allows comparison between data sets with different scales.
The NRMSEquartile is the least sensitive to outliers of the three normalized rmse metrics.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The IQR normalized root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nrmse_iqr(sim, obs)
0.2595461185212093
References
----------
- Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple
resolution comparison between maps that share a real variable. Environmental and Ecological
Statistics 15(2) 111-142.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
q1 = np.percentile(observed_array, 25)
q3 = np.percentile(observed_array, 75)
iqr = q3 - q1
return rmse_value / iqr
def irmse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the inertial root mean square error (IRMSE) between the simulated and observed data.
.. image:: /pictures/IRMSE.png
**Range:** 0 ≤ IRMSE < inf, lower is better.
**Notes:** This metric is the RMSE devided by by the standard deviation of the gradient of the
observed timeseries data. This metric is meant to be help understand the ability of the model
to predict changes in observation.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The inertial root mean square error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.irmse(sim, obs)
0.14572738134831856
References
----------
- Daga, M., Deo, M.C., 2009. Alternative data-driven methods to estimate wind from waves by
inverse modeling. Natural Hazards 49(2) 293-310.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Getting the gradient of the observed data
obs_len = observed_array.size
obs_grad = observed_array[1:obs_len] - observed_array[0:obs_len - 1]
# Standard deviation of the gradient
obs_grad_std = np.std(obs_grad, ddof=1)
# Divide RMSE by the standard deviation of the gradient of the observed data
rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2))
return rmse_value / obs_grad_std
def mase(simulated_array, observed_array, m=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the mean absolute scaled error between the simulated and observed data.
.. image:: /pictures/MASE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
m: int
If given, indicates the seasonal period m. If not given, the default is 1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute scaled error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mase(sim, obs)
0.17341040462427745
References
----------
- Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy.
International Journal of Forecasting 22(4) 679-688.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
start = m
end = simulated_array.size - m
a = np.mean(np.abs(simulated_array - observed_array))
b = np.abs(observed_array[start:observed_array.size] - observed_array[:end])
return a / (np.sum(b) / end)
def pearson_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the pearson correlation coefficient.
.. image:: /pictures/R_pearson.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The pearson r coefficient measures linear correlation. It is sensitive to outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Pearson correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.pearson_r(sim, obs)
0.9610793632835262
References
----------
- Pearson, K. (1895). Note on regression and inheritance in the case of two parents.
Proceedings of the Royal Society of London, 58, 240-242.
"""
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
top = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1 = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2 = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
return top / (bot1 * bot2)
def spearman_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the spearman rank correlation coefficient.
.. image:: /pictures/R_spearman.png
**Range:** -1 ≤ R (Pearson) ≤ 1. 1 indicates perfect postive correlation, 0 indicates
complete randomness, -1 indicate perfect negative correlation.
**Notes:** The spearman r coefficient measures the monotonic relation between simulated and
observed data. Because it uses a nonparametric measure of rank correlation, it is less sensitive
to outliers compared to the Pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spearman rank correlation coefficient.
Examples
----------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.spearman_r(sim, obs)
0.942857142857143
References
----------
- Spearman C (1904). "The proof and measurement of association between two things". American
Journal of Psychology. 15: 72–101. doi:10.2307/1412159
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
rank_sim = rankdata(simulated_array)
rank_obs = rankdata(observed_array)
mean_rank_sim = np.mean(rank_sim)
mean_rank_obs = np.mean(rank_obs)
top = np.mean((rank_obs - mean_rank_obs) * (rank_sim - mean_rank_sim))
bot = np.sqrt(
np.mean((rank_obs - mean_rank_obs) ** 2) * np.mean((rank_sim - mean_rank_sim) ** 2))
return top / bot
def r_squared(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Coefficient of Determination (r2).
.. image:: /pictures/r2.png
**Range:** 0 ≤ r2 ≤ 1. 1 indicates perfect correlation, 0 indicates complete randomness.
**Notes:** The Coefficient of Determination measures the linear relation between simulated and
observed data. Because it is the pearson correlation coefficient squared, it is more heavily
affected by outliers than the pearson correlation coefficient.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The coefficient of determination (R^2).
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.r_squared(sim, obs)
0.9236735425294681
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = observed_array - np.mean(observed_array)
b = simulated_array - np.mean(simulated_array)
return (np.sum(a * b)) ** 2 / (np.sum(a ** 2) * np.sum(b ** 2))
def acc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the anomaly correlation coefficient (ACC).
.. image:: /pictures/ACC.png
**Range:** -1 ≤ ACC ≤ 1. -1 indicates perfect negative correlation of the variation
pattern of the anomalies, 0 indicates complete randomness of the variation patterns of the
anomalies, 1 indicates perfect correlation of the variation pattern of the anomalies.
**Notes:** Common measure in the verification of spatial fields. Measures the correlation
between the variation pattern of the simulated data compared to the observed data.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The anomaly correlation coefficient.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.acc(sim, obs)
0.8008994694029383
References
----------
- Langland, Rolf H., and Ryan N. Maue. “Recent Northern Hemisphere Mid-Latitude Medium-Range
Deterministic Forecast Skill.” Tellus A: Dynamic Meteorology and Oceanography 64,
no. 1 (2012): 17531.
- Miyakoda, K., G. D. Hembree, R. F. Strickler, and I. Shulman. “Cumulative Results of Extended
Forecast Experiments I. Model Performance for Winter Cases.” Monthly Weather Review 100, no.
12(1972): 836–55.
- Murphy, Allan H., and Edward S. Epstein. “Skill Scores and Correlation Coefficients in Model
Verification.” Monthly Weather Review 117, no. 3 (1989): 572–82.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - np.mean(simulated_array)
b = observed_array - np.mean(observed_array)
c = np.std(observed_array, ddof=1) * np.std(simulated_array, ddof=1) * simulated_array.size
return np.dot(a, b / c)
def mape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the mean absolute percentage error (MAPE).
.. image:: /pictures/MAPE.png
**Range:** 0% ≤ MAPE ≤ inf. 0% indicates perfect correlation, a larger error indicates a
larger percent error in the data.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
c = 100 / simulated_array.size
return c * np.sum(b)
def mapd(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the mean absolute percentage deviation (MAPD).
.. image:: /pictures/MAPD.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute percentage deviation.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mapd(sim, obs)
0.10526315789473682
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(np.abs(observed_array))
return a / b
def maape(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the Mean Arctangent Absolute Percentage Error (MAAPE).
.. image:: /pictures/MAAPE.png
**Range:** 0 ≤ MAAPE < π/2, does not indicate bias, smaller is better.
**Notes:** Represents the mean absolute error as a percentage of the observed values. Handles
0s in the observed data. This metric is not as biased as MAPE by under-over predictions.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean arctangent absolute percentage error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mape(sim, obs)
11.639226612630866
References
----------
- Kim, S., Kim, H., 2016. A new metric of absolute percentage error for intermittent demand
forecasts. International Journal of Forecasting 32(3) 669-679.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = np.abs(a / observed_array)
return np.mean(np.arctan(b))
def smape1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (1) (SMAPE1).
.. image:: /pictures/SMAPE1.png
**Range:** 0 ≤ SMAPE1 < 100%, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (1).
Examples
--------
Note that if we switch the simulated and observed arrays the result is the same
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape1(sim, obs)
5.871915694397428
>>> he.smape1(obs, sim)
5.871915694397428
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 100 / simulated_array.size
b = np.abs(simulated_array - observed_array)
c = np.abs(simulated_array) + np.abs(observed_array)
return a * np.sum(b / c)
def smape2(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the Symmetric Mean Absolute Percentage Error (2) (SMAPE2).
.. image:: /pictures/SMAPE2.png
**Range:** 0 ≤ SMAPE1 < 200%, does not indicate bias, smaller is better, symmetrical.
**Notes:** This metric is an adjusted version of the MAPE with only positive metric values.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The symmetric mean absolute percentage error (2).
Examples
--------
Note that switching the simulated and observed arrays yields the same results
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.smape2(sim, obs)
11.743831388794856
>>> he.smape2(obs, sim)
11.743831388794856
References
----------
- Flores, B.E., 1986. A pragmatic view of accuracy measurement in forecasting. Omega 14(2)
93-98.
- Goodwin, P., Lawton, R., 1999. On the asymmetry of the symmetric MAPE. International Journal
of Forecasting 15(4) 405-408.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = simulated_array - observed_array
b = (simulated_array + observed_array) / 2
c = 100 / simulated_array.size
return c * np.sum(np.abs(a / b))
def d(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d).
.. image:: /pictures/d.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d(sim, obs)
0.978477353035657
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (observed_array - simulated_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
return 1 - (np.sum(a) / np.sum((b + c) ** 2))
def d1(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the index of agreement (d1).
.. image:: /pictures/d1.png
**Range:** 0 ≤ d < 1, does not indicate bias, larger is better.
**Notes:** This metric is a modified approach to the Nash-Sutcliffe Efficiency metric. Compared
to the other index of agreement (d) it has a reduced impact of outliers.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The index of agreement (d1).
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1(sim, obs)
0.8434782608695652
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
obs_mean = np.mean(observed_array)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.abs(simulated_array - obs_mean)
c = np.abs(observed_array - obs_mean)
return 1 - np.sum(a) / np.sum(b + c)
def dr(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the refined index of agreement (dr).
.. image:: /pictures/dr.png
**Range:** -1 ≤ dr < 1, does not indicate bias, larger is better.
**Notes:** Reformulation of Willmott’s index of agreement. This metric was created to address
issues in the index of agreement and the Nash-Sutcliffe efficiency metric. Meant to be a
flexible metric for use in climatology.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The refined index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dr(sim, obs)
0.847457627118644
References
----------
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = 2 * np.sum(np.abs(observed_array - observed_array.mean()))
if a <= b:
return 1 - (a / b)
else:
return (b / a) - 1
def drel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the the relative index of agreement (drel).
.. image:: /pictures/drel.png
**Range:** 0 ≤ drel < 1, does not indicate bias, larger is better.
**Notes:** Instead of absolute differences, this metric uses relative differences.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.drel(sim, obs)
0.9740868625579597
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = ((simulated_array - observed_array) / observed_array) ** 2
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = ((b + c) / np.mean(observed_array)) ** 2
return 1 - (np.sum(a) / np.sum(e))
def dmod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the the modified index of agreement (dmod).
.. image:: /pictures/dmod.png
**Range:** 0 ≤ dmod < 1, does not indicate bias, larger is better.
**Notes:** When j=1, this metric is the same as d1. As j becomes larger, outliers have a larger
impact on the value.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
Optional input indicating the j values desired. A higher j places more emphasis on
outliers. j is 1 by default.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified index of agreement.
Examples
--------
Note that using the default is the same as calculating the d1 metric. Changing the value of j
modification of the metric.
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.dmod(sim, obs) # Same as d1
0.8434782608695652
>>> he.dmod(sim, obs, j=1.5)
0.9413310986805733
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = np.abs(simulated_array - np.mean(observed_array))
c = np.abs(observed_array - np.mean(observed_array))
e = (b + c) ** j
return 1 - (np.sum(a) / np.sum(e))
def watt_m(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute Watterson's M (M).
.. image:: /pictures/M.png
**Range:** -1 ≤ M < 1, does not indicate bias, larger is better.
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
Watterson's M value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.watt_m(sim, obs)
0.8307913876595929
References
----------
- Watterson, I.G., 1996. Non‐dimensional measures of climate model performance. International
Journal of Climatology 16(4) 379-391.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = 2 / np.pi
b = np.mean((simulated_array - observed_array) ** 2) # MSE
c = np.std(observed_array, ddof=1) ** 2 + np.std(simulated_array, ddof=1) ** 2
e = (np.mean(simulated_array) - np.mean(observed_array)) ** 2
f = c + e
return a * np.arcsin(1 - (b / f))
def mb_r(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute Mielke-Berry R value (MB R).
.. image:: /pictures/MB_R.png
**Range:** 0 ≤ MB R < 1, does not indicate bias, larger is better.
**Notes:** Compares prediction to probability it arose by chance.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Mielke-Berry R value.
Notes
-----
If a more optimized version is desired, the `numba package <http://numba.pydata.org/doc.html>`_ can be implemented
for a much more optimized performance when computing this metric. An example is given below.
>>> from numba import njit, prange
>>> @njit(parallel=True, fastmath=True)
>>> def mb_par_fastmath(pred, obs): # uses LLVM compiler
>>> assert pred.size == obs.size
>>> n = pred.size
>>> tot = 0.0
>>> mae = 0.0
>>> for i in range(n):
>>> for j in prange(n):
>>> tot += abs(pred[i] - obs[j])
>>> mae += abs(pred[i] - obs[i])
>>> mae = mae / n
>>> mb = 1 - ((n ** 2) * mae / tot)
>>>
>>> return mb
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.mb_r(sim, obs)
0.7726315789473684
References
----------
- Berry, K.J., Mielke, P.W., 1988. A Generalization of Cohen's Kappa Agreement Measure to
Interval Measurement and Multiple Raters. Educational and Psychological Measurement 48(4)
921-933.
- Mielke, P.W., Berry, K.J., 2007. Permutation methods: a distance function approach.
Springer Science & Business Media.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Calculate metric
n = simulated_array.size
tot = 0.0
for i in range(n):
tot = tot + np.sum(np.abs(simulated_array - observed_array[i]))
mae_val = np.sum(np.abs(simulated_array - observed_array)) / n
mb = 1 - ((n ** 2) * mae_val / tot)
return mb
def nse(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Nash-Sutcliffe Efficiency.
.. image:: /pictures/NSE.png
**Range:** -inf < NSE < 1, does not indicate bias, larger is better.
**Notes:** The Nash-Sutcliffe efficiency metric compares prediction values to naive predictions
(i.e. average value). One major flaw of this metric is that it punishes a higher variance in
the observed values (denominator). This metric is analogous to the mean absolute error skill
score (MAESS) using the mean flow as a benchmark.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Nash-Sutcliffe Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse(sim, obs)
0.922093023255814
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
- McCuen, R.H., Knight, Z., Cutter, A.G., 2006. Evaluation of the Nash-Sutcliffe Efficiency
Index. Journal of Hydraulic Engineering.
- Nash, J.E., Sutcliffe, J.V., 1970. River flow forecasting through conceptual models part
I — A discussion of principles. Journal of Hydrology 282-290.
- Willmott, C.J., Robeson, S.M., Matsuura, K., 2012. A refined index of model performance.
International Journal of Climatology 32(13) 2088-2094.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** 2
b = (np.abs(observed_array - np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def nse_mod(simulated_array, observed_array, j=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the modified Nash-Sutcliffe efficiency (NSE mod).
.. image:: /pictures/NSEmod.png
**Range:** -inf < NSE (mod) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
j: int or float
If given, sets the value of j to the input. j is 1 by default. A higher j gives more
emphasis to outliers
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The modified Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_mod(sim, obs)
0.6949152542372882
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs(simulated_array - observed_array)) ** j
b = (np.abs(observed_array - np.mean(observed_array))) ** j
return 1 - (np.sum(a) / np.sum(b))
def nse_rel(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the relative Nash-Sutcliffe efficiency (NSE rel).
.. image:: /pictures/NSErel.png
**Range:** -inf < NSE (rel) < 1, does not indicate bias, larger is better.
**Notes:** The modified Nash-Sutcliffe efficiency metric gives less weight to outliers if j=1,
or more weight to outliers if j is higher. Generally, j=1.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The relative Nash-Sutcliffe efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.nse_rel(sim, obs)
0.9062004687708474
References
----------
- Krause, P., Boyle, D., Bäse, F., 2005. Comparison of different efficiency criteria for
hydrological model assessment. Advances in geosciences 5 89-97.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = (np.abs((simulated_array - observed_array) / observed_array)) ** 2
b = (np.abs((observed_array - np.mean(observed_array)) / np.mean(observed_array))) ** 2
return 1 - (np.sum(a) / np.sum(b))
def kge_2009(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""Compute the Kling-Gupta efficiency (2009).
.. image:: /pictures/KGE_2009.png
**Range:** -inf < KGE (2009) < 1, larger is better.
**Notes:** Gupta et al. (2009) created this metric to demonstrate the relative importance of
the three components of the NSE, which are correlation, bias and variability. This was done
with hydrologic modeling as the context. This metric is meant to address issues with the NSE.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), Alpha, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, alpha, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2009) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2009(sim, obs)
0.912223072345668
>>> he.kge_2009(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.927910707932087, 1.0058823529411764, 0.9181073779138655)
References
----------
- Gupta, H. V., Kling, H., Yilmaz, K. K., & Martinez, G. F. (2009). Decomposition of the mean
squared error and NSE performance criteria: Implications for improving hydrological modelling.
Journal of Hydrology, 377(1-2), 80-91.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array, ddof=1)
obs_sigma = np.std(observed_array, ddof=1)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
if obs_mean != 0:
beta = sim_mean / obs_mean
else:
beta = np.nan
# Relative variability between simulated and observed values
if obs_sigma != 0:
alpha = sim_sigma / obs_sigma
else:
alpha = np.nan
if not np.isnan(beta) and not np.isnan(alpha):
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (alpha - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Alpha is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, alpha, beta, kge
else:
return kge
def kge_2012(simulated_array, observed_array, s=(1, 1, 1), replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False, return_all=False):
"""
Compute the Kling-Gupta efficiency (2012).
.. image:: /pictures/KGE_2012.png
**Range:** -inf < KGE (2012) < 1, does not indicate bias, larger is better.
**Notes:** The modified version of the KGE (2009). Kling proposed this version to avoid
cross-correlation between bias and variability ratios.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
s: tuple of length three
Represents the scaling factors to be used for re-scaling the Pearson product-moment
correlation coefficient (r), gamma, and Beta, respectively.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
return_all: bool
If True, returns all of the components of the KGE metric, which are r, gamma, and beta, respectively.
Returns
-------
float (tuple of float)
The Kling-Gupta (2012) efficiency value, unless the return_all parameter is True.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8])
>>> he.kge_2012(sim, obs)
0.9122230723456678
>>> he.kge_2012(sim, obs, return_all=True) # Returns (r, alpha, beta, kge)
(0.9615951377405804, 0.9224843295231272, 1.0058823529411764, 0.9132923608280753)
References
----------
- Kling, H., Fuchs, M., & Paulin, M. (2012). Runoff conditions in the upper Danube basin under
an ensemble of climate change scenarios. Journal of Hydrology, 424, 264-277.
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
# Means
sim_mean = np.mean(simulated_array)
obs_mean = np.mean(observed_array)
# Standard Deviations
sim_sigma = np.std(simulated_array)
obs_sigma = np.std(observed_array)
# Pearson R
top_pr = np.sum((observed_array - obs_mean) * (simulated_array - sim_mean))
bot1_pr = np.sqrt(np.sum((observed_array - obs_mean) ** 2))
bot2_pr = np.sqrt(np.sum((simulated_array - sim_mean) ** 2))
pr = top_pr / (bot1_pr * bot2_pr)
# Ratio between mean of simulated and observed data
beta = sim_mean / obs_mean
# CV is the coefficient of variation (standard deviation / mean)
sim_cv = sim_sigma / sim_mean
obs_cv = obs_sigma / obs_mean
# Variability Ratio, or the ratio of simulated CV to observed CV
gam = sim_cv / obs_cv
if obs_mean != 0 and obs_sigma != 0 and sim_mean != 0:
kge = 1 - np.sqrt(
(s[0] * (pr - 1)) ** 2 + (s[1] * (gam - 1)) ** 2 + (s[2] * (beta - 1)) ** 2)
else:
if obs_mean == 0:
warnings.warn(
'Warning: The observed data mean is 0. Therefore, Beta is infinite and the KGE '
'value cannot be computed.')
if obs_sigma == 0:
warnings.warn(
'Warning: The observed data standard deviation is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
if sim_mean == 0:
warnings.warn(
'Warning: The simulated data mean is 0. Therefore, Gamma is infinite '
'and the KGE value cannot be computed.')
kge = np.nan
assert type(return_all) == bool, "expected <type 'bool'> for parameter return_all, got {}".format(type(return_all))
if return_all:
return pr, gam, beta, kge
else:
return kge
def lm_index(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""
Compute the Legate-McCabe Efficiency Index.
.. image:: /pictures/E1p.png
**Range:** 0 ≤ E1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.lm_index(sim, obs)
0.6949152542372882
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
mean_obs = np.mean(observed_array)
if obs_bar_p is not None:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
a = np.abs(simulated_array - observed_array)
b = np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def d1_p(simulated_array, observed_array, obs_bar_p=None, replace_nan=None,
replace_inf=None, remove_neg=False, remove_zero=False):
"""Compute the Legate-McCabe Index of Agreement.
.. image:: /pictures/D1p.png
**Range:** 0 ≤ d1' < 1, does not indicate bias, larger is better.
**Notes:** The obs_bar_p argument represents a seasonal or other selected average.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
obs_bar_p: float
Seasonal or other selected average. If None, the mean of the observed array will be used.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Legate-McCabe Efficiency index of agreement.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.d1_p(sim, obs)
0.8434782608695652
References
----------
- Legates, D.R., McCabe Jr, G.J., 1999. Evaluating the use of “goodness‐of‐fit” Measures in
hydrologic and hydroclimatic model validation. Water Resources Research 35(1) 233-241.
Lehmann, E.L., Casella, G., 1998. Springer Texts in Statistics. Springer-Verlag, New York.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
if obs_bar_p is not None:
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - obs_bar_p) + np.abs(observed_array - obs_bar_p)
return 1 - (np.sum(a) / np.sum(b))
else:
mean_obs = np.mean(observed_array)
a = np.abs(observed_array - simulated_array)
b = np.abs(simulated_array - mean_obs) + np.abs(observed_array - mean_obs)
return 1 - (np.sum(a) / np.sum(b))
def ve(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the Volumetric Efficiency (VE).
.. image:: /pictures/VE.png
**Range:** 0 ≤ VE < 1 smaller is better, does not indicate bias.
**Notes:** Represents the error as a percentage of flow.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Volumetric Efficiency value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.ve(sim, obs)
0.8947368421052632
References
----------
- Criss, R.E., Winston, W.E., 2008. Do Nash values have value? Discussion and alternate
proposals. Hydrological Processes 22(14) 2723.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.sum(np.abs(simulated_array - observed_array))
b = np.sum(observed_array)
return 1 - (a / b)
def sa(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Angle (SA).
.. image:: /pictures/SA.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral angle metric measures the angle between the two vectors in hyperspace.
It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Angle value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sa(sim, obs)
0.10816831366492945
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(simulated_array, observed_array)
b = np.linalg.norm(simulated_array) * np.linalg.norm(observed_array)
return np.arccos(a / b)
def sc(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Correlation (SC).
.. image:: /pictures/SC.png
**Range:** -π/2 ≤ SA < π/2, closer to 0 is better.
**Notes:** The spectral correlation metric measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Correlation value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sc(sim, obs)
0.27991341383646606
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
a = np.dot(observed_array - np.mean(observed_array), simulated_array - np.mean(simulated_array))
b = np.linalg.norm(observed_array - np.mean(observed_array))
c = np.linalg.norm(simulated_array - np.mean(simulated_array))
e = b * c
return np.arccos(a / e)
def sid(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Information Divergence (SID).
.. image:: /pictures/SID.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral information divergence measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral information divergence value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sid(sim, obs)
0.03517616895318012
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
first = (observed_array / np.mean(observed_array)) - (
simulated_array / np.mean(simulated_array))
second1 = np.log10(observed_array) - np.log10(np.mean(observed_array))
second2 = np.log10(simulated_array) - np.log10(np.mean(simulated_array))
return np.dot(first, second1 - second2)
def sga(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the Spectral Gradient Angle (SGA).
.. image:: /pictures/SGA.png
**Range:** -π/2 ≤ SID < π/2, closer to 0 is better.
**Notes:** The spectral gradient angle measures the angle between the two vectors in
hyperspace. It indicates how well the shape of the two series match – not magnitude.
SG is the gradient of the simulated or observed time series.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The Spectral Gradient Angle.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.sga(sim, obs)
0.26764286472739834
References
----------
- Robila, S.A., Gershman, A., 2005. Spectral matching accuracy in processing hyperspectral
data, Signals, Circuits and Systems, 2005. ISSCS 2005. International Symposium on. IEEE,
pp. 163-166.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sgx = observed_array[1:] - observed_array[:observed_array.size - 1]
sgy = simulated_array[1:] - simulated_array[:simulated_array.size - 1]
a = np.dot(sgx, sgy)
b = np.linalg.norm(sgx) * np.linalg.norm(sgy)
return np.arccos(a / b)
####################################################################################################
# H Metrics: Methods from Tornqvist L, Vartia P, and Vartia YO. (1985) #
####################################################################################################
def h1_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute the H1 mean error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mhe(sim, obs)
0.002106551840594386
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(h)
def h1_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H1 absolute error.
.. image:: /pictures/H1.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The H1 absolute error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_mahe(sim, obs)
0.11639226612630865
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.mean(np.abs(h))
def h1_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H1 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean squared H1 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h1_rmshe(sim, obs)
0.12865571253672756
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / observed_array
return np.sqrt(np.mean(h ** 2))
def h2_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean error.
.. image:: /pictures/H2.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mhe(sim, obs)
-0.015319829424307036
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(h)
def h2_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 mean absolute error.
.. image:: /pictures/H2.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_mahe(sim, obs)
0.11997591408039167
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.mean(np.abs(h))
def h2_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H2 root mean square error.
.. image:: /pictures/H1.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H2 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h2_rmshe(sim, obs)
0.1373586680669673
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / simulated_array
return np.sqrt(np.mean(h ** 2))
def h3_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 mean error.
.. image:: /pictures/H3.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mhe(sim, obs)
-0.006322019630356533
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(h)
def h3_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H3 mean absolute error.
.. image:: /pictures/H3.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_mahe(sim, obs)
0.11743831388794855
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.mean(np.abs(h))
def h3_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H3 root mean square error.
.. image:: /pictures/H3.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H3 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h3_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / (0.5 * (simulated_array + observed_array))
return np.sqrt(np.mean(h ** 2))
def h4_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mhe(sim, obs)
-0.0064637371129817
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(h)
def h4_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H4 mean absolute error.
.. image:: /pictures/H4.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_mahe(sim, obs)
0.11781032209144082
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.mean(np.abs(h))
def h4_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H4 mean error.
.. image:: /pictures/H4.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H4 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h4_rmshe(sim, obs)
0.13200901963465006
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array - observed_array) / np.sqrt(simulated_array * observed_array)
return np.sqrt(np.mean(h ** 2))
def h5_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean error.
.. image:: /pictures/H5.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mhe(sim, obs)
-0.006606638791856322
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(h)
def h5_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 mean absolute error.
.. image:: /pictures/H5.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_mahe(sim, obs)
0.11818409010335018
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.mean(np.abs(h))
def h5_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H5 root mean square error.
.. image:: /pictures/H5.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H5 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h5_rmshe(sim, obs)
0.13254476469410933
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array - observed_array)
bot = np.reciprocal(0.5 * (np.reciprocal(observed_array) + np.reciprocal(simulated_array)))
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h6_mhe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""
Compute the H6 mean error.
.. image:: /pictures/H6.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mhe(sim, obs)
-0.006322019630356514
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(h)
def h6_mahe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""Compute the H6 mean absolute error.
.. image:: /pictures/H6.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_mahe(sim, obs)
0.11743831388794852
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.mean(np.abs(h))
def h6_rmshe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the H6 root mean square error.
.. image:: /pictures/H6.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
k: int or float
If given, sets the value of k. If None, k=1.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H6 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h6_rmshe(sim, obs)
0.13147667616722278
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
top = (simulated_array / observed_array - 1)
bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
h = top / bot
return np.sqrt(np.mean(h ** 2))
def h7_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean error.
.. image:: /pictures/H7.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mhe(sim, obs)
0.0026331898007430263
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(h)
def h7_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 mean absolute error.
.. image:: /pictures/H7.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_mahe(sim, obs)
0.14549033265788583
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.mean(np.abs(h))
def h7_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H7 root mean square error.
.. image:: /pictures/H7.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H7 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h7_rmshe(sim, obs)
0.16081964067090945
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.min(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
def h8_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""Compute the H8 mean error.
.. image:: /pictures/H8.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mhe(sim, obs)
0.0018056158633666466
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(h)
def h8_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 mean absolute error.
.. image:: /pictures/H8.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_mahe(sim, obs)
0.099764799536836
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.mean(np.abs(h))
def h8_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H8 root mean square error.
.. image:: /pictures/H8.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H8 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h8_rmshe(sim, obs)
0.11027632503148076
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = (simulated_array / observed_array - 1) / np.max(simulated_array / observed_array)
return np.sqrt(np.mean(h ** 2))
# def h9(simulated_array, observed_array, h_type='mhe', k=1):
# h = (simulated_array / observed_array - 1) / \
# np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k)
# if h_type == 'mhe':
# return h.mean()
# elif h_type == 'ahe':
# return np.abs(h).mean()
# elif h_type == 'rmshe':
# return np.sqrt((h**2).mean())
# else:
# raise RuntimeError("The three types available are 'mhe', 'ahe', and 'rmshe'.")
def h10_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean error.
.. image:: /pictures/H10.png
.. image:: /pictures/MHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.h10_mhe(sim, obs)
-0.0012578676058971154
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(h)
def h10_mahe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 mean absolute error.
.. image:: /pictures/H10.png
.. image:: /pictures/AHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean absolute H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_mahe(sim, obs), 6)
0.094636
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.mean(np.abs(h))
def h10_rmshe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the H10 root mean square error.
.. image:: /pictures/H10.png
.. image:: /pictures/RMSHE.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The root mean square H10 error.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.h10_rmshe(sim, obs), 6)
0.103161
References
----------
- Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured?
The American Statistician 43-46.
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
h = np.log1p(simulated_array) - np.log1p(observed_array)
return np.sqrt(np.mean(h ** 2))
###################################################################################################
# Statistical Error Metrics for Distribution Testing #
###################################################################################################
def g_mean_diff(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False,
remove_zero=False):
"""
Compute the geometric mean difference.
.. image:: /pictures/GMD.png
**Range:**
**Notes:** For the difference of geometric means, the geometric mean is computed for each of
two samples then their difference is taken.
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The geometric mean difference value.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> he.g_mean_diff(sim, obs)
0.988855412098022
References
----------
"""
# Treats data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
sim_log = np.log1p(simulated_array)
obs_log = np.log1p(observed_array)
return np.exp(gmean(sim_log) - gmean(obs_log))
def mean_var(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False,
remove_zero=False):
"""
Compute the mean variance.
.. image:: /pictures/MV.png
**Range:**
**Notes:**
Parameters
----------
simulated_array: one dimensional ndarray
An array of simulated data from the time series.
observed_array: one dimensional ndarray
An array of observed data from the time series.
replace_nan: float, optional
If given, indicates which value to replace NaN values with in the two arrays. If None, when
a NaN value is found at the i-th position in the observed OR simulated array, the i-th value
of the observed and simulated array are removed before the computation.
replace_inf: float, optional
If given, indicates which value to replace Inf values with in the two arrays. If None, when
an inf value is found at the i-th position in the observed OR simulated array, the i-th
value of the observed and simulated array are removed before the computation.
remove_neg: boolean, optional
If True, when a negative value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
remove_zero: boolean, optional
If true, when a zero value is found at the i-th position in the observed OR simulated
array, the i-th value of the observed AND simulated array are removed before the
computation.
Returns
-------
float
The mean variance.
Examples
--------
>>> import HydroErr as he
>>> import numpy as np
>>> sim = np.array([5, 7, 9, 2, 4.5, 6.7])
>>> obs = np.array([4.7, 6, 10, 2.5, 4, 7])
>>> np.round(he.mean_var(sim, obs), 6)
0.010641
References
----------
"""
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remove_neg=remove_neg,
remove_zero=remove_zero
)
return np.var(np.log1p(observed_array) - np.log1p(simulated_array))
####################################################################################################
# HELPER FUNCTIONS AND API INFORMATION #
####################################################################################################
metric_names = [
'Mean Error', 'Mean Absolute Error', 'Mean Squared Error', 'Mean Log Error',
'Mean Absolute Log Error', 'Mean Squared Log Error', 'Median Error', 'Median Absolute Error',
'Median Squared Error', 'Eclidean Distance', 'Normalized Eclidean Distance',
'Root Mean Square Error', 'Root Mean Squared Log Error',
'Normalized Root Mean Square Error - Range', 'Normalized Root Mean Square Error - Mean',
'Normalized Root Mean Square Error - IQR', 'Inertial Root Mean Square Error',
'Mean Absolute Scaled Error', 'Coefficient of Determination', 'Pearson Correlation Coefficient',
'Spearman Rank Correlation Coefficient', 'Anomaly Correlation Coefficient',
'Mean Absolute Percentage Error', 'Mean Absolute Percentage Deviation',
'Mean Arctangent Absolute Percentage Error', 'Symmetric Mean Absolute Percentage Error (1)',
'Symmetric Mean Absolute Percentage Error (2)', 'Index of Agreement (d)',
'Index of Agreement (d1)', 'Modified Index of Agreement', 'Relative Index of Agreement',
'Index of Agreement Refined (dr)', "Watterson's M", 'Mielke-Berry R',
'Nash-Sutcliffe Efficiency', 'Modified Nash-Sutcliffe Efficiency',
'Relative Nash-Sutcliffe Efficiency', 'Kling-Gupta Efficiency (2009)',
'Kling-Gupta Efficiency (2012)', 'Legate-McCabe Efficiency Index',
'Legate-McCabe Index of Agreement', 'Volumetric Efficiency', 'Spectral Angle',
'Spectral Correlation', 'Spectral Information Divergence', 'Spectral Gradient Angle',
'Mean H1 Error', 'Mean Absolute H1 Error', 'Root Mean Square H1 Error', 'Mean H2 Error',
'Mean Absolute H2 Error', 'Root Mean Square H2 Error', 'Mean H3 Error',
'Mean Absolute H3 Error', 'Root Mean Square H3 Error', 'Mean H4 Error',
'Mean Absolute H4 Error', 'Root Mean Square H4 Error', 'Mean H5 Error',
'Mean Absolute H5 Error', 'Root Mean Square H5 Error', 'Mean H6 Error',
'Mean Absolute H6 Error', 'Root Mean Square H6 Error', 'Mean H7 Error',
'Mean Absolute H7 Error', 'Root Mean Square H7 Error', 'Mean H8 Error',
'Mean Absolute H8 Error', 'Root Mean Square H8 Error', 'Mean H10 Error',
'Mean Absolute H10 Error', 'Root Mean Square H10 Error', 'Geometric Mean Difference',
'Mean Variance'
]
metric_abbr = [
'ME', 'MAE', 'MSE', 'MLE', 'MALE', 'MSLE', 'MdE', 'MdAE', 'MdSE', 'ED', 'NED', 'RMSE', 'RMSLE',
'NRMSE (Range)', 'NRMSE (Mean)', 'NRMSE (IQR)', 'IRMSE', 'MASE', 'r2', 'R (Pearson)',
'R (Spearman)', 'ACC', 'MAPE', 'MAPD', 'MAAPE', 'SMAPE1', 'SMAPE2', 'd', 'd1', 'd (Mod.)',
'd (Rel.)', 'dr', 'M', '(MB) R', 'NSE', 'NSE (Mod.)', 'NSE (Rel.)', 'KGE (2009)', 'KGE (2012)',
"E1'", "D1'", 'VE', 'SA', 'SC', 'SID', 'SGA', 'H1 (MHE)', 'H1 (MAHE)', 'H1 (RMSHE)', 'H2 (MHE)',
'H2 (MAHE)', 'H2 (RMSHE)', 'H3 (MHE)', 'H3 (MAHE)', 'H3 (RMSHE)', 'H4 (MHE)', 'H4 (MAHE)',
'H4 (RMSHE)', 'H5 (MHE)', 'H5 (MAHE)', 'H5 (RMSHE)', 'H6 (MHE)', 'H6 (MAHE)', 'H6 (RMSHE)',
'H7 (MHE)', 'H7 (MAHE)', 'H7 (RMSHE)', 'H8 (MHE)', 'H8 (MAHE)', 'H8 (RMSHE)', 'H10 (MHE)',
'H10 (MAHE)', 'H10 (RMSHE)', 'GMD', 'MV'
]
function_list = [
me, mae, mse, mle, male, msle, mde, mdae, mdse, ed, ned, rmse, rmsle, nrmse_range, nrmse_mean,
nrmse_iqr, irmse, mase, r_squared, pearson_r, spearman_r, acc, mape, mapd, maape, smape1,
smape2, d, d1, dmod, drel, dr, watt_m, mb_r, nse, nse_mod, nse_rel, kge_2009, kge_2012,
lm_index, d1_p, ve, sa, sc, sid, sga, h1_mhe, h1_mahe, h1_rmshe, h2_mhe, h2_mahe, h2_rmshe,
h3_mhe, h3_mahe, h3_rmshe, h4_mhe, h4_mahe, h4_rmshe, h5_mhe, h5_mahe, h5_rmshe, h6_mhe,
h6_mahe, h6_rmshe, h7_mhe, h7_mahe, h7_rmshe, h8_mhe, h8_mahe, h8_rmshe, h10_mhe, h10_mahe,
h10_rmshe, g_mean_diff, mean_var,
]
# Assign some properties to each function for ease of use for users
for i in range(len(function_list)):
function_list[i].name = metric_names[i]
function_list[i].abbr = metric_abbr[i]
if __name__ == "__main__":
pass
|
pyoceans/python-ctd | ctd/read.py | _basename | python | def _basename(fname):
if not isinstance(fname, Path):
fname = Path(fname)
path, name, ext = fname.parent, fname.stem, fname.suffix
return path, name, ext | Return file name without path. | train | https://github.com/pyoceans/python-ctd/blob/fa9a9d02da3dfed6d1d60db0e52bbab52adfe666/ctd/read.py#L15-L20 | null | import bz2
import gzip
import linecache
import re
import warnings
import zipfile
from datetime import datetime
from io import StringIO
from pathlib import Path
import numpy as np
import pandas as pd
def _normalize_names(name):
name = name.strip()
name = name.strip("*")
return name
def _open_compressed(fname):
extension = fname.suffix.lower()
if extension in [".gzip", ".gz"]:
cfile = gzip.open(str(fname))
elif extension == ".bz2":
cfile = bz2.BZ2File(str(fname))
elif extension == ".zip":
# NOTE: Zip format may contain more than one file in the archive
# (similar to tar), here we assume that there is just one file per
# zipfile! Also, we ask for the name because it can be different from
# the zipfile file!!
zfile = zipfile.ZipFile(str(fname))
name = zfile.namelist()[0]
cfile = zfile.open(name)
else:
raise ValueError(
"Unrecognized file extension. Expected .gzip, .bz2, or .zip, got {}".format(
extension
)
)
contents = cfile.read()
cfile.close()
return contents
def _read_file(fname):
if not isinstance(fname, Path):
fname = Path(fname).resolve()
extension = fname.suffix.lower()
if extension in [".gzip", ".gz", ".bz2", ".zip"]:
contents = _open_compressed(fname)
elif extension in [".cnv", ".edf", ".txt", ".ros", ".btl"]:
contents = fname.read_bytes()
else:
raise ValueError(
f"Unrecognized file extension. Expected .cnv, .edf, .txt, .ros, or .btl got {extension}"
)
# Read as bytes but we need to return strings for the parsers.
text = contents.decode(encoding="utf-8", errors="replace")
return StringIO(text)
def _parse_seabird(lines, ftype="cnv"):
# Initialize variables.
lon = lat = time = None, None, None
skiprows = 0
metadata = {}
header, config, names = [], [], []
for k, line in enumerate(lines):
line = line.strip()
# Only cnv has columns names, for bottle files we will use the variable row.
if ftype == "cnv":
if "# name" in line:
name, unit = line.split("=")[1].split(":")
name, unit = list(map(_normalize_names, (name, unit)))
names.append(name)
# Seabird headers starts with *.
if line.startswith("*"):
header.append(line)
# Seabird configuration starts with #.
if line.startswith("#"):
config.append(line)
# NMEA position and time.
if "NMEA Latitude" in line:
hemisphere = line[-1]
lat = line.strip(hemisphere).split("=")[1].strip()
lat = np.float_(lat.split())
if hemisphere == "S":
lat = -(lat[0] + lat[1] / 60.0)
elif hemisphere == "N":
lat = lat[0] + lat[1] / 60.0
else:
raise ValueError("Latitude not recognized.")
if "NMEA Longitude" in line:
hemisphere = line[-1]
lon = line.strip(hemisphere).split("=")[1].strip()
lon = np.float_(lon.split())
if hemisphere == "W":
lon = -(lon[0] + lon[1] / 60.0)
elif hemisphere == "E":
lon = lon[0] + lon[1] / 60.0
else:
raise ValueError("Latitude not recognized.")
if "NMEA UTC (Time)" in line:
time = line.split("=")[-1].strip()
# Should use some fuzzy datetime parser to make this more robust.
time = datetime.strptime(time, "%b %d %Y %H:%M:%S")
# cnv file header ends with *END* while
if ftype == "cnv":
if line == "*END*":
skiprows = k + 1
break
else: # btl.
# There is no *END* like in a .cnv file, skip two after header info.
if not (line.startswith("*") | line.startswith("#")):
# Fix commonly occurring problem when Sbeox.* exists in the file
# the name is concatenated to previous parameter
# example:
# CStarAt0Sbeox0Mm/Kg to CStarAt0 Sbeox0Mm/Kg (really two different params)
line = re.sub(r"(\S)Sbeox", "\\1 Sbeox", line)
names = line.split()
skiprows = k + 2
break
if ftype == "btl":
# Capture stat names column.
names.append("Statistic")
metadata.update(
{
"header": "\n".join(header),
"config": "\n".join(config),
"names": names,
"skiprows": skiprows,
"time": time,
"lon": lon,
"lat": lat,
}
)
return metadata
def from_bl(fname):
"""Read Seabird bottle-trip (bl) file
Example
-------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> df = ctd.from_bl(str(data_path.joinpath('bl', 'bottletest.bl')))
>>> df._metadata["time_of_reset"]
datetime.datetime(2018, 6, 25, 20, 8, 55)
"""
df = pd.read_csv(
fname,
skiprows=2,
parse_dates=[1],
index_col=0,
names=["bottle_number", "time", "startscan", "endscan"],
)
df._metadata = {
"time_of_reset": pd.to_datetime(
linecache.getline(str(fname), 2)[6:-1]
).to_pydatetime()
}
return df
def from_btl(fname):
"""
DataFrame constructor to open Seabird CTD BTL-ASCII format.
Examples
--------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> bottles = ctd.from_btl(data_path.joinpath('btl', 'bottletest.btl'))
"""
f = _read_file(fname)
metadata = _parse_seabird(f.readlines(), ftype="btl")
f.seek(0)
df = pd.read_fwf(
f,
header=None,
index_col=False,
names=metadata["names"],
parse_dates=False,
skiprows=metadata["skiprows"],
)
f.close()
# At this point the data frame is not correctly lined up (multiple rows
# for avg, std, min, max or just avg, std, etc).
# Also needs date,time,and bottle number to be converted to one per line.
# Get row types, see what you have: avg, std, min, max or just avg, std.
rowtypes = df[df.columns[-1]].unique()
# Get times and dates which occur on second line of each bottle.
dates = df.iloc[:: len(rowtypes), 1].reset_index(drop=True)
times = df.iloc[1 :: len(rowtypes), 1].reset_index(drop=True)
datetimes = dates + " " + times
# Fill the Date column with datetimes.
df.loc[:: len(rowtypes), "Date"] = datetimes.values
df.loc[1 :: len(rowtypes), "Date"] = datetimes.values
# Fill missing rows.
df["Bottle"] = df["Bottle"].fillna(method="ffill")
df["Date"] = df["Date"].fillna(method="ffill")
df["Statistic"] = df["Statistic"].str.replace(r"\(|\)", "") # (avg) to avg
name = _basename(fname)[1]
dtypes = {
"bpos": int,
"pumps": bool,
"flag": bool,
"Bottle": int,
"Scan": int,
"Statistic": str,
"Date": str,
}
for column in df.columns:
if column in dtypes:
df[column] = df[column].astype(dtypes[column])
else:
try:
df[column] = df[column].astype(float)
except ValueError:
warnings.warn("Could not convert %s to float." % column)
df["Date"] = pd.to_datetime(df["Date"])
metadata["name"] = str(name)
setattr(df, "_metadata", metadata)
return df
def from_edf(fname):
"""
DataFrame constructor to open XBT EDF ASCII format.
Examples
--------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> cast = ctd.from_edf(data_path.joinpath('XBT.EDF.gz'))
>>> ax = cast['temperature'].plot_cast()
"""
f = _read_file(fname)
header, names = [], []
for k, line in enumerate(f.readlines()):
line = line.strip()
if line.startswith("Serial Number"):
serial = line.strip().split(":")[1].strip()
elif line.startswith("Latitude"):
try:
hemisphere = line[-1]
lat = line.strip(hemisphere).split(":")[1].strip()
lat = np.float_(lat.split())
if hemisphere == "S":
lat = -(lat[0] + lat[1] / 60.0)
elif hemisphere == "N":
lat = lat[0] + lat[1] / 60.0
except (IndexError, ValueError):
lat = None
elif line.startswith("Longitude"):
try:
hemisphere = line[-1]
lon = line.strip(hemisphere).split(":")[1].strip()
lon = np.float_(lon.split())
if hemisphere == "W":
lon = -(lon[0] + lon[1] / 60.0)
elif hemisphere == "E":
lon = lon[0] + lon[1] / 60.0
except (IndexError, ValueError):
lon = None
else:
header.append(line)
if line.startswith("Field"):
col, unit = [l.strip().lower() for l in line.split(":")]
names.append(unit.split()[0])
if line == "// Data":
skiprows = k + 1
break
f.seek(0)
df = pd.read_csv(
f,
header=None,
index_col=None,
names=names,
skiprows=skiprows,
delim_whitespace=True,
)
f.close()
df.set_index("depth", drop=True, inplace=True)
df.index.name = "Depth [m]"
name = _basename(fname)[1]
metadata = {
"lon": lon,
"lat": lat,
"name": str(name),
"header": "\n".join(header),
"serial": serial,
}
setattr(df, "_metadata", metadata)
return df
def from_cnv(fname):
"""
DataFrame constructor to open Seabird CTD CNV-ASCII format.
Examples
--------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> cast = ctd.from_cnv(data_path.joinpath('CTD_big.cnv.bz2'))
>>> downcast, upcast = cast.split()
>>> ax = downcast['t090C'].plot_cast()
"""
f = _read_file(fname)
metadata = _parse_seabird(f.readlines(), ftype="cnv")
f.seek(0)
df = pd.read_fwf(
f,
header=None,
index_col=None,
names=metadata["names"],
skiprows=metadata["skiprows"],
delim_whitespace=True,
widths=[11] * len(metadata["names"]),
)
f.close()
key_set = False
prkeys = ["prDM", "prdM", "pr"]
for prkey in prkeys:
try:
df.set_index(prkey, drop=True, inplace=True)
key_set = True
except KeyError:
continue
if not key_set:
raise KeyError(
f"Could not find pressure field (supported names are {prkeys})."
)
df.index.name = "Pressure [dbar]"
name = _basename(fname)[1]
dtypes = {"bpos": int, "pumps": bool, "flag": bool}
for column in df.columns:
if column in dtypes:
df[column] = df[column].astype(dtypes[column])
else:
try:
df[column] = df[column].astype(float)
except ValueError:
warnings.warn("Could not convert %s to float." % column)
metadata["name"] = str(name)
setattr(df, "_metadata", metadata)
return df
def from_fsi(fname, skiprows=9):
"""
DataFrame constructor to open Falmouth Scientific, Inc. (FSI) CTD
ASCII format.
Examples
--------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> cast = ctd.from_fsi(data_path.joinpath('FSI.txt.gz'))
>>> downcast, upcast = cast.split()
>>> ax = downcast['TEMP'].plot_cast()
"""
f = _read_file(fname)
df = pd.read_csv(
f,
header="infer",
index_col=None,
skiprows=skiprows,
dtype=float,
delim_whitespace=True,
)
f.close()
df.set_index("PRES", drop=True, inplace=True)
df.index.name = "Pressure [dbar]"
metadata = {"name": str(fname)}
setattr(df, "_metadata", metadata)
return df
def rosette_summary(fname):
"""
Make a BTL (bottle) file from a ROS (bottle log) file.
More control for the averaging process and at which step we want to
perform this averaging eliminating the need to read the data into SBE
Software again after pre-processing.
NOTE: Do not run LoopEdit on the upcast!
Examples
--------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> fname = data_path.joinpath('CTD/g01l01s01.ros')
>>> ros = ctd.rosette_summary(fname)
>>> ros = ros.groupby(ros.index).mean()
>>> ros.pressure.values.astype(int)
array([835, 806, 705, 604, 503, 404, 303, 201, 151, 100, 51, 1])
"""
ros = from_cnv(fname)
ros["pressure"] = ros.index.values.astype(float)
ros["nbf"] = ros["nbf"].astype(int)
ros.set_index("nbf", drop=True, inplace=True, verify_integrity=False)
return ros
|
pyoceans/python-ctd | ctd/read.py | from_bl | python | def from_bl(fname):
df = pd.read_csv(
fname,
skiprows=2,
parse_dates=[1],
index_col=0,
names=["bottle_number", "time", "startscan", "endscan"],
)
df._metadata = {
"time_of_reset": pd.to_datetime(
linecache.getline(str(fname), 2)[6:-1]
).to_pydatetime()
}
return df | Read Seabird bottle-trip (bl) file
Example
-------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> df = ctd.from_bl(str(data_path.joinpath('bl', 'bottletest.bl')))
>>> df._metadata["time_of_reset"]
datetime.datetime(2018, 6, 25, 20, 8, 55) | train | https://github.com/pyoceans/python-ctd/blob/fa9a9d02da3dfed6d1d60db0e52bbab52adfe666/ctd/read.py#L157-L182 | null | import bz2
import gzip
import linecache
import re
import warnings
import zipfile
from datetime import datetime
from io import StringIO
from pathlib import Path
import numpy as np
import pandas as pd
def _basename(fname):
"""Return file name without path."""
if not isinstance(fname, Path):
fname = Path(fname)
path, name, ext = fname.parent, fname.stem, fname.suffix
return path, name, ext
def _normalize_names(name):
name = name.strip()
name = name.strip("*")
return name
def _open_compressed(fname):
extension = fname.suffix.lower()
if extension in [".gzip", ".gz"]:
cfile = gzip.open(str(fname))
elif extension == ".bz2":
cfile = bz2.BZ2File(str(fname))
elif extension == ".zip":
# NOTE: Zip format may contain more than one file in the archive
# (similar to tar), here we assume that there is just one file per
# zipfile! Also, we ask for the name because it can be different from
# the zipfile file!!
zfile = zipfile.ZipFile(str(fname))
name = zfile.namelist()[0]
cfile = zfile.open(name)
else:
raise ValueError(
"Unrecognized file extension. Expected .gzip, .bz2, or .zip, got {}".format(
extension
)
)
contents = cfile.read()
cfile.close()
return contents
def _read_file(fname):
if not isinstance(fname, Path):
fname = Path(fname).resolve()
extension = fname.suffix.lower()
if extension in [".gzip", ".gz", ".bz2", ".zip"]:
contents = _open_compressed(fname)
elif extension in [".cnv", ".edf", ".txt", ".ros", ".btl"]:
contents = fname.read_bytes()
else:
raise ValueError(
f"Unrecognized file extension. Expected .cnv, .edf, .txt, .ros, or .btl got {extension}"
)
# Read as bytes but we need to return strings for the parsers.
text = contents.decode(encoding="utf-8", errors="replace")
return StringIO(text)
def _parse_seabird(lines, ftype="cnv"):
# Initialize variables.
lon = lat = time = None, None, None
skiprows = 0
metadata = {}
header, config, names = [], [], []
for k, line in enumerate(lines):
line = line.strip()
# Only cnv has columns names, for bottle files we will use the variable row.
if ftype == "cnv":
if "# name" in line:
name, unit = line.split("=")[1].split(":")
name, unit = list(map(_normalize_names, (name, unit)))
names.append(name)
# Seabird headers starts with *.
if line.startswith("*"):
header.append(line)
# Seabird configuration starts with #.
if line.startswith("#"):
config.append(line)
# NMEA position and time.
if "NMEA Latitude" in line:
hemisphere = line[-1]
lat = line.strip(hemisphere).split("=")[1].strip()
lat = np.float_(lat.split())
if hemisphere == "S":
lat = -(lat[0] + lat[1] / 60.0)
elif hemisphere == "N":
lat = lat[0] + lat[1] / 60.0
else:
raise ValueError("Latitude not recognized.")
if "NMEA Longitude" in line:
hemisphere = line[-1]
lon = line.strip(hemisphere).split("=")[1].strip()
lon = np.float_(lon.split())
if hemisphere == "W":
lon = -(lon[0] + lon[1] / 60.0)
elif hemisphere == "E":
lon = lon[0] + lon[1] / 60.0
else:
raise ValueError("Latitude not recognized.")
if "NMEA UTC (Time)" in line:
time = line.split("=")[-1].strip()
# Should use some fuzzy datetime parser to make this more robust.
time = datetime.strptime(time, "%b %d %Y %H:%M:%S")
# cnv file header ends with *END* while
if ftype == "cnv":
if line == "*END*":
skiprows = k + 1
break
else: # btl.
# There is no *END* like in a .cnv file, skip two after header info.
if not (line.startswith("*") | line.startswith("#")):
# Fix commonly occurring problem when Sbeox.* exists in the file
# the name is concatenated to previous parameter
# example:
# CStarAt0Sbeox0Mm/Kg to CStarAt0 Sbeox0Mm/Kg (really two different params)
line = re.sub(r"(\S)Sbeox", "\\1 Sbeox", line)
names = line.split()
skiprows = k + 2
break
if ftype == "btl":
# Capture stat names column.
names.append("Statistic")
metadata.update(
{
"header": "\n".join(header),
"config": "\n".join(config),
"names": names,
"skiprows": skiprows,
"time": time,
"lon": lon,
"lat": lat,
}
)
return metadata
def from_btl(fname):
"""
DataFrame constructor to open Seabird CTD BTL-ASCII format.
Examples
--------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> bottles = ctd.from_btl(data_path.joinpath('btl', 'bottletest.btl'))
"""
f = _read_file(fname)
metadata = _parse_seabird(f.readlines(), ftype="btl")
f.seek(0)
df = pd.read_fwf(
f,
header=None,
index_col=False,
names=metadata["names"],
parse_dates=False,
skiprows=metadata["skiprows"],
)
f.close()
# At this point the data frame is not correctly lined up (multiple rows
# for avg, std, min, max or just avg, std, etc).
# Also needs date,time,and bottle number to be converted to one per line.
# Get row types, see what you have: avg, std, min, max or just avg, std.
rowtypes = df[df.columns[-1]].unique()
# Get times and dates which occur on second line of each bottle.
dates = df.iloc[:: len(rowtypes), 1].reset_index(drop=True)
times = df.iloc[1 :: len(rowtypes), 1].reset_index(drop=True)
datetimes = dates + " " + times
# Fill the Date column with datetimes.
df.loc[:: len(rowtypes), "Date"] = datetimes.values
df.loc[1 :: len(rowtypes), "Date"] = datetimes.values
# Fill missing rows.
df["Bottle"] = df["Bottle"].fillna(method="ffill")
df["Date"] = df["Date"].fillna(method="ffill")
df["Statistic"] = df["Statistic"].str.replace(r"\(|\)", "") # (avg) to avg
name = _basename(fname)[1]
dtypes = {
"bpos": int,
"pumps": bool,
"flag": bool,
"Bottle": int,
"Scan": int,
"Statistic": str,
"Date": str,
}
for column in df.columns:
if column in dtypes:
df[column] = df[column].astype(dtypes[column])
else:
try:
df[column] = df[column].astype(float)
except ValueError:
warnings.warn("Could not convert %s to float." % column)
df["Date"] = pd.to_datetime(df["Date"])
metadata["name"] = str(name)
setattr(df, "_metadata", metadata)
return df
def from_edf(fname):
"""
DataFrame constructor to open XBT EDF ASCII format.
Examples
--------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> cast = ctd.from_edf(data_path.joinpath('XBT.EDF.gz'))
>>> ax = cast['temperature'].plot_cast()
"""
f = _read_file(fname)
header, names = [], []
for k, line in enumerate(f.readlines()):
line = line.strip()
if line.startswith("Serial Number"):
serial = line.strip().split(":")[1].strip()
elif line.startswith("Latitude"):
try:
hemisphere = line[-1]
lat = line.strip(hemisphere).split(":")[1].strip()
lat = np.float_(lat.split())
if hemisphere == "S":
lat = -(lat[0] + lat[1] / 60.0)
elif hemisphere == "N":
lat = lat[0] + lat[1] / 60.0
except (IndexError, ValueError):
lat = None
elif line.startswith("Longitude"):
try:
hemisphere = line[-1]
lon = line.strip(hemisphere).split(":")[1].strip()
lon = np.float_(lon.split())
if hemisphere == "W":
lon = -(lon[0] + lon[1] / 60.0)
elif hemisphere == "E":
lon = lon[0] + lon[1] / 60.0
except (IndexError, ValueError):
lon = None
else:
header.append(line)
if line.startswith("Field"):
col, unit = [l.strip().lower() for l in line.split(":")]
names.append(unit.split()[0])
if line == "// Data":
skiprows = k + 1
break
f.seek(0)
df = pd.read_csv(
f,
header=None,
index_col=None,
names=names,
skiprows=skiprows,
delim_whitespace=True,
)
f.close()
df.set_index("depth", drop=True, inplace=True)
df.index.name = "Depth [m]"
name = _basename(fname)[1]
metadata = {
"lon": lon,
"lat": lat,
"name": str(name),
"header": "\n".join(header),
"serial": serial,
}
setattr(df, "_metadata", metadata)
return df
def from_cnv(fname):
"""
DataFrame constructor to open Seabird CTD CNV-ASCII format.
Examples
--------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> cast = ctd.from_cnv(data_path.joinpath('CTD_big.cnv.bz2'))
>>> downcast, upcast = cast.split()
>>> ax = downcast['t090C'].plot_cast()
"""
f = _read_file(fname)
metadata = _parse_seabird(f.readlines(), ftype="cnv")
f.seek(0)
df = pd.read_fwf(
f,
header=None,
index_col=None,
names=metadata["names"],
skiprows=metadata["skiprows"],
delim_whitespace=True,
widths=[11] * len(metadata["names"]),
)
f.close()
key_set = False
prkeys = ["prDM", "prdM", "pr"]
for prkey in prkeys:
try:
df.set_index(prkey, drop=True, inplace=True)
key_set = True
except KeyError:
continue
if not key_set:
raise KeyError(
f"Could not find pressure field (supported names are {prkeys})."
)
df.index.name = "Pressure [dbar]"
name = _basename(fname)[1]
dtypes = {"bpos": int, "pumps": bool, "flag": bool}
for column in df.columns:
if column in dtypes:
df[column] = df[column].astype(dtypes[column])
else:
try:
df[column] = df[column].astype(float)
except ValueError:
warnings.warn("Could not convert %s to float." % column)
metadata["name"] = str(name)
setattr(df, "_metadata", metadata)
return df
def from_fsi(fname, skiprows=9):
"""
DataFrame constructor to open Falmouth Scientific, Inc. (FSI) CTD
ASCII format.
Examples
--------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> cast = ctd.from_fsi(data_path.joinpath('FSI.txt.gz'))
>>> downcast, upcast = cast.split()
>>> ax = downcast['TEMP'].plot_cast()
"""
f = _read_file(fname)
df = pd.read_csv(
f,
header="infer",
index_col=None,
skiprows=skiprows,
dtype=float,
delim_whitespace=True,
)
f.close()
df.set_index("PRES", drop=True, inplace=True)
df.index.name = "Pressure [dbar]"
metadata = {"name": str(fname)}
setattr(df, "_metadata", metadata)
return df
def rosette_summary(fname):
"""
Make a BTL (bottle) file from a ROS (bottle log) file.
More control for the averaging process and at which step we want to
perform this averaging eliminating the need to read the data into SBE
Software again after pre-processing.
NOTE: Do not run LoopEdit on the upcast!
Examples
--------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> fname = data_path.joinpath('CTD/g01l01s01.ros')
>>> ros = ctd.rosette_summary(fname)
>>> ros = ros.groupby(ros.index).mean()
>>> ros.pressure.values.astype(int)
array([835, 806, 705, 604, 503, 404, 303, 201, 151, 100, 51, 1])
"""
ros = from_cnv(fname)
ros["pressure"] = ros.index.values.astype(float)
ros["nbf"] = ros["nbf"].astype(int)
ros.set_index("nbf", drop=True, inplace=True, verify_integrity=False)
return ros
|
pyoceans/python-ctd | ctd/read.py | from_btl | python | def from_btl(fname):
f = _read_file(fname)
metadata = _parse_seabird(f.readlines(), ftype="btl")
f.seek(0)
df = pd.read_fwf(
f,
header=None,
index_col=False,
names=metadata["names"],
parse_dates=False,
skiprows=metadata["skiprows"],
)
f.close()
# At this point the data frame is not correctly lined up (multiple rows
# for avg, std, min, max or just avg, std, etc).
# Also needs date,time,and bottle number to be converted to one per line.
# Get row types, see what you have: avg, std, min, max or just avg, std.
rowtypes = df[df.columns[-1]].unique()
# Get times and dates which occur on second line of each bottle.
dates = df.iloc[:: len(rowtypes), 1].reset_index(drop=True)
times = df.iloc[1 :: len(rowtypes), 1].reset_index(drop=True)
datetimes = dates + " " + times
# Fill the Date column with datetimes.
df.loc[:: len(rowtypes), "Date"] = datetimes.values
df.loc[1 :: len(rowtypes), "Date"] = datetimes.values
# Fill missing rows.
df["Bottle"] = df["Bottle"].fillna(method="ffill")
df["Date"] = df["Date"].fillna(method="ffill")
df["Statistic"] = df["Statistic"].str.replace(r"\(|\)", "") # (avg) to avg
name = _basename(fname)[1]
dtypes = {
"bpos": int,
"pumps": bool,
"flag": bool,
"Bottle": int,
"Scan": int,
"Statistic": str,
"Date": str,
}
for column in df.columns:
if column in dtypes:
df[column] = df[column].astype(dtypes[column])
else:
try:
df[column] = df[column].astype(float)
except ValueError:
warnings.warn("Could not convert %s to float." % column)
df["Date"] = pd.to_datetime(df["Date"])
metadata["name"] = str(name)
setattr(df, "_metadata", metadata)
return df | DataFrame constructor to open Seabird CTD BTL-ASCII format.
Examples
--------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> bottles = ctd.from_btl(data_path.joinpath('btl', 'bottletest.btl')) | train | https://github.com/pyoceans/python-ctd/blob/fa9a9d02da3dfed6d1d60db0e52bbab52adfe666/ctd/read.py#L185-L256 | [
"def _basename(fname):\n \"\"\"Return file name without path.\"\"\"\n if not isinstance(fname, Path):\n fname = Path(fname)\n path, name, ext = fname.parent, fname.stem, fname.suffix\n return path, name, ext\n",
"def _read_file(fname):\n if not isinstance(fname, Path):\n fname = Path(fname).resolve()\n\n extension = fname.suffix.lower()\n if extension in [\".gzip\", \".gz\", \".bz2\", \".zip\"]:\n contents = _open_compressed(fname)\n elif extension in [\".cnv\", \".edf\", \".txt\", \".ros\", \".btl\"]:\n contents = fname.read_bytes()\n else:\n raise ValueError(\n f\"Unrecognized file extension. Expected .cnv, .edf, .txt, .ros, or .btl got {extension}\"\n )\n # Read as bytes but we need to return strings for the parsers.\n text = contents.decode(encoding=\"utf-8\", errors=\"replace\")\n return StringIO(text)\n",
"def _parse_seabird(lines, ftype=\"cnv\"):\n # Initialize variables.\n lon = lat = time = None, None, None\n skiprows = 0\n\n metadata = {}\n header, config, names = [], [], []\n for k, line in enumerate(lines):\n line = line.strip()\n\n # Only cnv has columns names, for bottle files we will use the variable row.\n if ftype == \"cnv\":\n if \"# name\" in line:\n name, unit = line.split(\"=\")[1].split(\":\")\n name, unit = list(map(_normalize_names, (name, unit)))\n names.append(name)\n\n # Seabird headers starts with *.\n if line.startswith(\"*\"):\n header.append(line)\n\n # Seabird configuration starts with #.\n if line.startswith(\"#\"):\n config.append(line)\n\n # NMEA position and time.\n if \"NMEA Latitude\" in line:\n hemisphere = line[-1]\n lat = line.strip(hemisphere).split(\"=\")[1].strip()\n lat = np.float_(lat.split())\n if hemisphere == \"S\":\n lat = -(lat[0] + lat[1] / 60.0)\n elif hemisphere == \"N\":\n lat = lat[0] + lat[1] / 60.0\n else:\n raise ValueError(\"Latitude not recognized.\")\n if \"NMEA Longitude\" in line:\n hemisphere = line[-1]\n lon = line.strip(hemisphere).split(\"=\")[1].strip()\n lon = np.float_(lon.split())\n if hemisphere == \"W\":\n lon = -(lon[0] + lon[1] / 60.0)\n elif hemisphere == \"E\":\n lon = lon[0] + lon[1] / 60.0\n else:\n raise ValueError(\"Latitude not recognized.\")\n if \"NMEA UTC (Time)\" in line:\n time = line.split(\"=\")[-1].strip()\n # Should use some fuzzy datetime parser to make this more robust.\n time = datetime.strptime(time, \"%b %d %Y %H:%M:%S\")\n\n # cnv file header ends with *END* while\n if ftype == \"cnv\":\n if line == \"*END*\":\n skiprows = k + 1\n break\n else: # btl.\n # There is no *END* like in a .cnv file, skip two after header info.\n if not (line.startswith(\"*\") | line.startswith(\"#\")):\n # Fix commonly occurring problem when Sbeox.* exists in the file\n # the name is concatenated to previous parameter\n # example:\n # CStarAt0Sbeox0Mm/Kg to CStarAt0 Sbeox0Mm/Kg (really two different params)\n line = re.sub(r\"(\\S)Sbeox\", \"\\\\1 Sbeox\", line)\n\n names = line.split()\n skiprows = k + 2\n break\n if ftype == \"btl\":\n # Capture stat names column.\n names.append(\"Statistic\")\n metadata.update(\n {\n \"header\": \"\\n\".join(header),\n \"config\": \"\\n\".join(config),\n \"names\": names,\n \"skiprows\": skiprows,\n \"time\": time,\n \"lon\": lon,\n \"lat\": lat,\n }\n )\n return metadata\n"
] | import bz2
import gzip
import linecache
import re
import warnings
import zipfile
from datetime import datetime
from io import StringIO
from pathlib import Path
import numpy as np
import pandas as pd
def _basename(fname):
"""Return file name without path."""
if not isinstance(fname, Path):
fname = Path(fname)
path, name, ext = fname.parent, fname.stem, fname.suffix
return path, name, ext
def _normalize_names(name):
name = name.strip()
name = name.strip("*")
return name
def _open_compressed(fname):
extension = fname.suffix.lower()
if extension in [".gzip", ".gz"]:
cfile = gzip.open(str(fname))
elif extension == ".bz2":
cfile = bz2.BZ2File(str(fname))
elif extension == ".zip":
# NOTE: Zip format may contain more than one file in the archive
# (similar to tar), here we assume that there is just one file per
# zipfile! Also, we ask for the name because it can be different from
# the zipfile file!!
zfile = zipfile.ZipFile(str(fname))
name = zfile.namelist()[0]
cfile = zfile.open(name)
else:
raise ValueError(
"Unrecognized file extension. Expected .gzip, .bz2, or .zip, got {}".format(
extension
)
)
contents = cfile.read()
cfile.close()
return contents
def _read_file(fname):
if not isinstance(fname, Path):
fname = Path(fname).resolve()
extension = fname.suffix.lower()
if extension in [".gzip", ".gz", ".bz2", ".zip"]:
contents = _open_compressed(fname)
elif extension in [".cnv", ".edf", ".txt", ".ros", ".btl"]:
contents = fname.read_bytes()
else:
raise ValueError(
f"Unrecognized file extension. Expected .cnv, .edf, .txt, .ros, or .btl got {extension}"
)
# Read as bytes but we need to return strings for the parsers.
text = contents.decode(encoding="utf-8", errors="replace")
return StringIO(text)
def _parse_seabird(lines, ftype="cnv"):
# Initialize variables.
lon = lat = time = None, None, None
skiprows = 0
metadata = {}
header, config, names = [], [], []
for k, line in enumerate(lines):
line = line.strip()
# Only cnv has columns names, for bottle files we will use the variable row.
if ftype == "cnv":
if "# name" in line:
name, unit = line.split("=")[1].split(":")
name, unit = list(map(_normalize_names, (name, unit)))
names.append(name)
# Seabird headers starts with *.
if line.startswith("*"):
header.append(line)
# Seabird configuration starts with #.
if line.startswith("#"):
config.append(line)
# NMEA position and time.
if "NMEA Latitude" in line:
hemisphere = line[-1]
lat = line.strip(hemisphere).split("=")[1].strip()
lat = np.float_(lat.split())
if hemisphere == "S":
lat = -(lat[0] + lat[1] / 60.0)
elif hemisphere == "N":
lat = lat[0] + lat[1] / 60.0
else:
raise ValueError("Latitude not recognized.")
if "NMEA Longitude" in line:
hemisphere = line[-1]
lon = line.strip(hemisphere).split("=")[1].strip()
lon = np.float_(lon.split())
if hemisphere == "W":
lon = -(lon[0] + lon[1] / 60.0)
elif hemisphere == "E":
lon = lon[0] + lon[1] / 60.0
else:
raise ValueError("Latitude not recognized.")
if "NMEA UTC (Time)" in line:
time = line.split("=")[-1].strip()
# Should use some fuzzy datetime parser to make this more robust.
time = datetime.strptime(time, "%b %d %Y %H:%M:%S")
# cnv file header ends with *END* while
if ftype == "cnv":
if line == "*END*":
skiprows = k + 1
break
else: # btl.
# There is no *END* like in a .cnv file, skip two after header info.
if not (line.startswith("*") | line.startswith("#")):
# Fix commonly occurring problem when Sbeox.* exists in the file
# the name is concatenated to previous parameter
# example:
# CStarAt0Sbeox0Mm/Kg to CStarAt0 Sbeox0Mm/Kg (really two different params)
line = re.sub(r"(\S)Sbeox", "\\1 Sbeox", line)
names = line.split()
skiprows = k + 2
break
if ftype == "btl":
# Capture stat names column.
names.append("Statistic")
metadata.update(
{
"header": "\n".join(header),
"config": "\n".join(config),
"names": names,
"skiprows": skiprows,
"time": time,
"lon": lon,
"lat": lat,
}
)
return metadata
def from_bl(fname):
"""Read Seabird bottle-trip (bl) file
Example
-------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> df = ctd.from_bl(str(data_path.joinpath('bl', 'bottletest.bl')))
>>> df._metadata["time_of_reset"]
datetime.datetime(2018, 6, 25, 20, 8, 55)
"""
df = pd.read_csv(
fname,
skiprows=2,
parse_dates=[1],
index_col=0,
names=["bottle_number", "time", "startscan", "endscan"],
)
df._metadata = {
"time_of_reset": pd.to_datetime(
linecache.getline(str(fname), 2)[6:-1]
).to_pydatetime()
}
return df
def from_edf(fname):
"""
DataFrame constructor to open XBT EDF ASCII format.
Examples
--------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> cast = ctd.from_edf(data_path.joinpath('XBT.EDF.gz'))
>>> ax = cast['temperature'].plot_cast()
"""
f = _read_file(fname)
header, names = [], []
for k, line in enumerate(f.readlines()):
line = line.strip()
if line.startswith("Serial Number"):
serial = line.strip().split(":")[1].strip()
elif line.startswith("Latitude"):
try:
hemisphere = line[-1]
lat = line.strip(hemisphere).split(":")[1].strip()
lat = np.float_(lat.split())
if hemisphere == "S":
lat = -(lat[0] + lat[1] / 60.0)
elif hemisphere == "N":
lat = lat[0] + lat[1] / 60.0
except (IndexError, ValueError):
lat = None
elif line.startswith("Longitude"):
try:
hemisphere = line[-1]
lon = line.strip(hemisphere).split(":")[1].strip()
lon = np.float_(lon.split())
if hemisphere == "W":
lon = -(lon[0] + lon[1] / 60.0)
elif hemisphere == "E":
lon = lon[0] + lon[1] / 60.0
except (IndexError, ValueError):
lon = None
else:
header.append(line)
if line.startswith("Field"):
col, unit = [l.strip().lower() for l in line.split(":")]
names.append(unit.split()[0])
if line == "// Data":
skiprows = k + 1
break
f.seek(0)
df = pd.read_csv(
f,
header=None,
index_col=None,
names=names,
skiprows=skiprows,
delim_whitespace=True,
)
f.close()
df.set_index("depth", drop=True, inplace=True)
df.index.name = "Depth [m]"
name = _basename(fname)[1]
metadata = {
"lon": lon,
"lat": lat,
"name": str(name),
"header": "\n".join(header),
"serial": serial,
}
setattr(df, "_metadata", metadata)
return df
def from_cnv(fname):
"""
DataFrame constructor to open Seabird CTD CNV-ASCII format.
Examples
--------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> cast = ctd.from_cnv(data_path.joinpath('CTD_big.cnv.bz2'))
>>> downcast, upcast = cast.split()
>>> ax = downcast['t090C'].plot_cast()
"""
f = _read_file(fname)
metadata = _parse_seabird(f.readlines(), ftype="cnv")
f.seek(0)
df = pd.read_fwf(
f,
header=None,
index_col=None,
names=metadata["names"],
skiprows=metadata["skiprows"],
delim_whitespace=True,
widths=[11] * len(metadata["names"]),
)
f.close()
key_set = False
prkeys = ["prDM", "prdM", "pr"]
for prkey in prkeys:
try:
df.set_index(prkey, drop=True, inplace=True)
key_set = True
except KeyError:
continue
if not key_set:
raise KeyError(
f"Could not find pressure field (supported names are {prkeys})."
)
df.index.name = "Pressure [dbar]"
name = _basename(fname)[1]
dtypes = {"bpos": int, "pumps": bool, "flag": bool}
for column in df.columns:
if column in dtypes:
df[column] = df[column].astype(dtypes[column])
else:
try:
df[column] = df[column].astype(float)
except ValueError:
warnings.warn("Could not convert %s to float." % column)
metadata["name"] = str(name)
setattr(df, "_metadata", metadata)
return df
def from_fsi(fname, skiprows=9):
"""
DataFrame constructor to open Falmouth Scientific, Inc. (FSI) CTD
ASCII format.
Examples
--------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> cast = ctd.from_fsi(data_path.joinpath('FSI.txt.gz'))
>>> downcast, upcast = cast.split()
>>> ax = downcast['TEMP'].plot_cast()
"""
f = _read_file(fname)
df = pd.read_csv(
f,
header="infer",
index_col=None,
skiprows=skiprows,
dtype=float,
delim_whitespace=True,
)
f.close()
df.set_index("PRES", drop=True, inplace=True)
df.index.name = "Pressure [dbar]"
metadata = {"name": str(fname)}
setattr(df, "_metadata", metadata)
return df
def rosette_summary(fname):
"""
Make a BTL (bottle) file from a ROS (bottle log) file.
More control for the averaging process and at which step we want to
perform this averaging eliminating the need to read the data into SBE
Software again after pre-processing.
NOTE: Do not run LoopEdit on the upcast!
Examples
--------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> fname = data_path.joinpath('CTD/g01l01s01.ros')
>>> ros = ctd.rosette_summary(fname)
>>> ros = ros.groupby(ros.index).mean()
>>> ros.pressure.values.astype(int)
array([835, 806, 705, 604, 503, 404, 303, 201, 151, 100, 51, 1])
"""
ros = from_cnv(fname)
ros["pressure"] = ros.index.values.astype(float)
ros["nbf"] = ros["nbf"].astype(int)
ros.set_index("nbf", drop=True, inplace=True, verify_integrity=False)
return ros
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.