repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
bukun/TorCMS
torcms/script/tmplchecker/__init__.py
do_for_dir
def do_for_dir(inws, begin): ''' do something in the directory. ''' inws = os.path.abspath(inws) for wroot, wdirs, wfiles in os.walk(inws): for wfile in wfiles: if wfile.endswith('.html'): if 'autogen' in wroot: continue check_html(os.path.abspath(os.path.join(wroot, wfile)), begin)
python
def do_for_dir(inws, begin): ''' do something in the directory. ''' inws = os.path.abspath(inws) for wroot, wdirs, wfiles in os.walk(inws): for wfile in wfiles: if wfile.endswith('.html'): if 'autogen' in wroot: continue check_html(os.path.abspath(os.path.join(wroot, wfile)), begin)
do something in the directory.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/tmplchecker/__init__.py#L99-L109
bukun/TorCMS
torcms/script/tmplchecker/__init__.py
run_checkit
def run_checkit(srws=None): ''' do check it. ''' begin = len(os.path.abspath('templates')) + 1 inws = os.path.abspath(os.getcwd()) if srws: do_for_dir(srws[0], begin) else: do_for_dir(os.path.join(inws, 'templates'), begin) DOT_OBJ.render('xxtmpl', view=True)
python
def run_checkit(srws=None): ''' do check it. ''' begin = len(os.path.abspath('templates')) + 1 inws = os.path.abspath(os.getcwd()) if srws: do_for_dir(srws[0], begin) else: do_for_dir(os.path.join(inws, 'templates'), begin) DOT_OBJ.render('xxtmpl', view=True)
do check it.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/tmplchecker/__init__.py#L112-L123
bukun/TorCMS
torcms/model/post2catalog_model.py
MPost2Catalog.query_all
def query_all(): ''' Query all the records from TabPost2Tag. ''' recs = TabPost2Tag.select( TabPost2Tag, TabTag.kind.alias('tag_kind'), ).join( TabTag, on=(TabPost2Tag.tag_id == TabTag.uid) ) return recs
python
def query_all(): ''' Query all the records from TabPost2Tag. ''' recs = TabPost2Tag.select( TabPost2Tag, TabTag.kind.alias('tag_kind'), ).join( TabTag, on=(TabPost2Tag.tag_id == TabTag.uid) ) return recs
Query all the records from TabPost2Tag.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post2catalog_model.py#L21-L32
bukun/TorCMS
torcms/model/post2catalog_model.py
MPost2Catalog.remove_relation
def remove_relation(post_id, tag_id): ''' Delete the record of post 2 tag. ''' entry = TabPost2Tag.delete().where( (TabPost2Tag.post_id == post_id) & (TabPost2Tag.tag_id == tag_id) ) entry.execute() MCategory.update_count(tag_id)
python
def remove_relation(post_id, tag_id): ''' Delete the record of post 2 tag. ''' entry = TabPost2Tag.delete().where( (TabPost2Tag.post_id == post_id) & (TabPost2Tag.tag_id == tag_id) ) entry.execute() MCategory.update_count(tag_id)
Delete the record of post 2 tag.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post2catalog_model.py#L35-L44
bukun/TorCMS
torcms/model/post2catalog_model.py
MPost2Catalog.remove_tag
def remove_tag(tag_id): ''' Delete the records of certain tag. ''' entry = TabPost2Tag.delete().where( TabPost2Tag.tag_id == tag_id ) entry.execute()
python
def remove_tag(tag_id): ''' Delete the records of certain tag. ''' entry = TabPost2Tag.delete().where( TabPost2Tag.tag_id == tag_id ) entry.execute()
Delete the records of certain tag.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post2catalog_model.py#L47-L54
bukun/TorCMS
torcms/model/post2catalog_model.py
MPost2Catalog.query_by_post
def query_by_post(postid): ''' Query records by post. ''' return TabPost2Tag.select().where( TabPost2Tag.post_id == postid ).order_by(TabPost2Tag.order)
python
def query_by_post(postid): ''' Query records by post. ''' return TabPost2Tag.select().where( TabPost2Tag.post_id == postid ).order_by(TabPost2Tag.order)
Query records by post.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post2catalog_model.py#L78-L84
bukun/TorCMS
torcms/model/post2catalog_model.py
MPost2Catalog.__get_by_info
def __get_by_info(post_id, catalog_id): ''' Geo the record by post and catalog. ''' recs = TabPost2Tag.select().where( (TabPost2Tag.post_id == post_id) & (TabPost2Tag.tag_id == catalog_id) ) if recs.count() == 1: return recs.get() elif recs.count() > 1: # return the first one, and delete others. out_rec = None for rec in recs: if out_rec: entry = TabPost2Tag.delete().where( TabPost2Tag.uid == rec.uid ) entry.execute() else: out_rec = rec return out_rec return None
python
def __get_by_info(post_id, catalog_id): ''' Geo the record by post and catalog. ''' recs = TabPost2Tag.select().where( (TabPost2Tag.post_id == post_id) & (TabPost2Tag.tag_id == catalog_id) ) if recs.count() == 1: return recs.get() elif recs.count() > 1: # return the first one, and delete others. out_rec = None for rec in recs: if out_rec: entry = TabPost2Tag.delete().where( TabPost2Tag.uid == rec.uid ) entry.execute() else: out_rec = rec return out_rec return None
Geo the record by post and catalog.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post2catalog_model.py#L87-L110
bukun/TorCMS
torcms/model/post2catalog_model.py
MPost2Catalog.query_count
def query_count(): ''' The count of post2tag. ''' recs = TabPost2Tag.select( TabPost2Tag.tag_id, peewee.fn.COUNT(TabPost2Tag.tag_id).alias('num') ).group_by( TabPost2Tag.tag_id ) return recs
python
def query_count(): ''' The count of post2tag. ''' recs = TabPost2Tag.select( TabPost2Tag.tag_id, peewee.fn.COUNT(TabPost2Tag.tag_id).alias('num') ).group_by( TabPost2Tag.tag_id ) return recs
The count of post2tag.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post2catalog_model.py#L113-L123
bukun/TorCMS
torcms/model/post2catalog_model.py
MPost2Catalog.update_field
def update_field(uid, post_id=None, tag_id=None, par_id=None): ''' Update the field of post2tag. ''' if post_id: entry = TabPost2Tag.update( post_id=post_id ).where(TabPost2Tag.uid == uid) entry.execute() if tag_id: entry2 = TabPost2Tag.update( par_id=tag_id[:2] + '00', tag_id=tag_id, ).where(TabPost2Tag.uid == uid) entry2.execute() if par_id: entry2 = TabPost2Tag.update( par_id=par_id ).where(TabPost2Tag.uid == uid) entry2.execute()
python
def update_field(uid, post_id=None, tag_id=None, par_id=None): ''' Update the field of post2tag. ''' if post_id: entry = TabPost2Tag.update( post_id=post_id ).where(TabPost2Tag.uid == uid) entry.execute() if tag_id: entry2 = TabPost2Tag.update( par_id=tag_id[:2] + '00', tag_id=tag_id, ).where(TabPost2Tag.uid == uid) entry2.execute() if par_id: entry2 = TabPost2Tag.update( par_id=par_id ).where(TabPost2Tag.uid == uid) entry2.execute()
Update the field of post2tag.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post2catalog_model.py#L126-L146
bukun/TorCMS
torcms/model/post2catalog_model.py
MPost2Catalog.add_record
def add_record(post_id, catalog_id, order=0): ''' Create the record of post 2 tag, and update the count in g_tag. ''' rec = MPost2Catalog.__get_by_info(post_id, catalog_id) if rec: entry = TabPost2Tag.update( order=order, # For migration. the value should be added when created. par_id=rec.tag_id[:2] + '00', ).where(TabPost2Tag.uid == rec.uid) entry.execute() else: TabPost2Tag.create( uid=tools.get_uuid(), par_id=catalog_id[:2] + '00', post_id=post_id, tag_id=catalog_id, order=order, ) MCategory.update_count(catalog_id)
python
def add_record(post_id, catalog_id, order=0): ''' Create the record of post 2 tag, and update the count in g_tag. ''' rec = MPost2Catalog.__get_by_info(post_id, catalog_id) if rec: entry = TabPost2Tag.update( order=order, # For migration. the value should be added when created. par_id=rec.tag_id[:2] + '00', ).where(TabPost2Tag.uid == rec.uid) entry.execute() else: TabPost2Tag.create( uid=tools.get_uuid(), par_id=catalog_id[:2] + '00', post_id=post_id, tag_id=catalog_id, order=order, ) MCategory.update_count(catalog_id)
Create the record of post 2 tag, and update the count in g_tag.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post2catalog_model.py#L149-L171
bukun/TorCMS
torcms/model/post2catalog_model.py
MPost2Catalog.count_of_certain_category
def count_of_certain_category(cat_id, tag=''): ''' Get the count of certain category. ''' if cat_id.endswith('00'): # The first level category, using the code bellow. cat_con = TabPost2Tag.par_id == cat_id else: cat_con = TabPost2Tag.tag_id == cat_id if tag: condition = { 'def_tag_arr': [tag] } recs = TabPost2Tag.select().join( TabPost, on=((TabPost2Tag.post_id == TabPost.uid) & (TabPost.valid == 1)) ).where( cat_con & TabPost.extinfo.contains(condition) ) else: recs = TabPost2Tag.select().where( cat_con ) return recs.count()
python
def count_of_certain_category(cat_id, tag=''): ''' Get the count of certain category. ''' if cat_id.endswith('00'): # The first level category, using the code bellow. cat_con = TabPost2Tag.par_id == cat_id else: cat_con = TabPost2Tag.tag_id == cat_id if tag: condition = { 'def_tag_arr': [tag] } recs = TabPost2Tag.select().join( TabPost, on=((TabPost2Tag.post_id == TabPost.uid) & (TabPost.valid == 1)) ).where( cat_con & TabPost.extinfo.contains(condition) ) else: recs = TabPost2Tag.select().where( cat_con ) return recs.count()
Get the count of certain category.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post2catalog_model.py#L174-L200
bukun/TorCMS
torcms/model/post2catalog_model.py
MPost2Catalog.query_pager_by_slug
def query_pager_by_slug(slug, current_page_num=1, tag='', order=False): ''' Query pager via category slug. ''' cat_rec = MCategory.get_by_slug(slug) if cat_rec: cat_id = cat_rec.uid else: return None # The flowing code is valid. if cat_id.endswith('00'): # The first level category, using the code bellow. cat_con = TabPost2Tag.par_id == cat_id else: cat_con = TabPost2Tag.tag_id == cat_id if tag: condition = { 'def_tag_arr': [tag] } recs = TabPost.select().join( TabPost2Tag, on=((TabPost.uid == TabPost2Tag.post_id) & (TabPost.valid == 1)) ).where( cat_con & TabPost.extinfo.contains(condition) ).order_by( TabPost.time_update.desc() ).paginate(current_page_num, CMS_CFG['list_num']) elif order: recs = TabPost.select().join( TabPost2Tag, on=((TabPost.uid == TabPost2Tag.post_id) & (TabPost.valid == 1)) ).where( cat_con ).order_by( TabPost.order.asc() ) else: recs = TabPost.select().join( TabPost2Tag, on=((TabPost.uid == TabPost2Tag.post_id) & (TabPost.valid == 1)) ).where( cat_con ).order_by( TabPost.time_update.desc() ).paginate(current_page_num, CMS_CFG['list_num']) return recs
python
def query_pager_by_slug(slug, current_page_num=1, tag='', order=False): ''' Query pager via category slug. ''' cat_rec = MCategory.get_by_slug(slug) if cat_rec: cat_id = cat_rec.uid else: return None # The flowing code is valid. if cat_id.endswith('00'): # The first level category, using the code bellow. cat_con = TabPost2Tag.par_id == cat_id else: cat_con = TabPost2Tag.tag_id == cat_id if tag: condition = { 'def_tag_arr': [tag] } recs = TabPost.select().join( TabPost2Tag, on=((TabPost.uid == TabPost2Tag.post_id) & (TabPost.valid == 1)) ).where( cat_con & TabPost.extinfo.contains(condition) ).order_by( TabPost.time_update.desc() ).paginate(current_page_num, CMS_CFG['list_num']) elif order: recs = TabPost.select().join( TabPost2Tag, on=((TabPost.uid == TabPost2Tag.post_id) & (TabPost.valid == 1)) ).where( cat_con ).order_by( TabPost.order.asc() ) else: recs = TabPost.select().join( TabPost2Tag, on=((TabPost.uid == TabPost2Tag.post_id) & (TabPost.valid == 1)) ).where( cat_con ).order_by( TabPost.time_update.desc() ).paginate(current_page_num, CMS_CFG['list_num']) return recs
Query pager via category slug.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post2catalog_model.py#L203-L251
bukun/TorCMS
torcms/model/post2catalog_model.py
MPost2Catalog.query_by_entity_uid
def query_by_entity_uid(idd, kind=''): ''' Query post2tag by certain post. ''' if kind == '': return TabPost2Tag.select( TabPost2Tag, TabTag.slug.alias('tag_slug'), TabTag.name.alias('tag_name') ).join( TabTag, on=(TabPost2Tag.tag_id == TabTag.uid) ).where( (TabPost2Tag.post_id == idd) & (TabTag.kind != 'z') ).order_by( TabPost2Tag.order ) return TabPost2Tag.select( TabPost2Tag, TabTag.slug.alias('tag_slug'), TabTag.name.alias('tag_name') ).join(TabTag, on=(TabPost2Tag.tag_id == TabTag.uid)).where( (TabTag.kind == kind) & (TabPost2Tag.post_id == idd) ).order_by( TabPost2Tag.order )
python
def query_by_entity_uid(idd, kind=''): ''' Query post2tag by certain post. ''' if kind == '': return TabPost2Tag.select( TabPost2Tag, TabTag.slug.alias('tag_slug'), TabTag.name.alias('tag_name') ).join( TabTag, on=(TabPost2Tag.tag_id == TabTag.uid) ).where( (TabPost2Tag.post_id == idd) & (TabTag.kind != 'z') ).order_by( TabPost2Tag.order ) return TabPost2Tag.select( TabPost2Tag, TabTag.slug.alias('tag_slug'), TabTag.name.alias('tag_name') ).join(TabTag, on=(TabPost2Tag.tag_id == TabTag.uid)).where( (TabTag.kind == kind) & (TabPost2Tag.post_id == idd) ).order_by( TabPost2Tag.order )
Query post2tag by certain post.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post2catalog_model.py#L254-L281
bukun/TorCMS
torcms/model/post2catalog_model.py
MPost2Catalog.get_first_category
def get_first_category(app_uid): ''' Get the first, as the uniqe category of post. ''' recs = MPost2Catalog.query_by_entity_uid(app_uid).objects() if recs.count() > 0: return recs.get() return None
python
def get_first_category(app_uid): ''' Get the first, as the uniqe category of post. ''' recs = MPost2Catalog.query_by_entity_uid(app_uid).objects() if recs.count() > 0: return recs.get() return None
Get the first, as the uniqe category of post.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post2catalog_model.py#L291-L299
bukun/TorCMS
torcms/modules/info_modules.py
InfoCategory.render
def render(self, *args, **kwargs): ''' fun(uid_with_str) fun(uid_with_str, slug = val1, glyph = val2) ''' uid_with_str = args[0] slug = kwargs.get('slug', False) with_title = kwargs.get('with_title', False) glyph = kwargs.get('glyph', '') kwd = { 'glyph': glyph } curinfo = MCategory.get_by_uid(uid_with_str) sub_cats = MCategory.query_sub_cat(uid_with_str) if slug: tmpl = 'modules/info/catalog_slug.html' else: tmpl = 'modules/info/catalog_of.html' return self.render_string(tmpl, pcatinfo=curinfo, sub_cats=sub_cats, recs=sub_cats, with_title=with_title, kwd=kwd)
python
def render(self, *args, **kwargs): ''' fun(uid_with_str) fun(uid_with_str, slug = val1, glyph = val2) ''' uid_with_str = args[0] slug = kwargs.get('slug', False) with_title = kwargs.get('with_title', False) glyph = kwargs.get('glyph', '') kwd = { 'glyph': glyph } curinfo = MCategory.get_by_uid(uid_with_str) sub_cats = MCategory.query_sub_cat(uid_with_str) if slug: tmpl = 'modules/info/catalog_slug.html' else: tmpl = 'modules/info/catalog_of.html' return self.render_string(tmpl, pcatinfo=curinfo, sub_cats=sub_cats, recs=sub_cats, with_title=with_title, kwd=kwd)
fun(uid_with_str) fun(uid_with_str, slug = val1, glyph = val2)
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/modules/info_modules.py#L25-L56
bukun/TorCMS
torcms/modules/info_modules.py
InforUserMost.render
def render(self, *args, **kwargs): ''' fun(user_name, kind) fun(user_name, kind, num) fun(user_name, kind, num, with_tag = val1, glyph = val2) fun(user_name = vala, kind = valb, num = valc, with_tag = val1, glyph = val2) ''' user_name = kwargs.get('user_name', args[0]) kind = kwargs.get('kind', args[1]) num = kwargs.get('num', args[2] if len(args) > 2 else 6) with_tag = kwargs.get('with_tag', False) glyph = kwargs.get('glyph', '') all_cats = MUsage.query_most(user_name, kind, num).objects() kwd = { 'with_tag': with_tag, 'router': router_post[kind], 'glyph': glyph } return self.render_string('modules/info/list_user_equation.html', recs=all_cats, kwd=kwd)
python
def render(self, *args, **kwargs): ''' fun(user_name, kind) fun(user_name, kind, num) fun(user_name, kind, num, with_tag = val1, glyph = val2) fun(user_name = vala, kind = valb, num = valc, with_tag = val1, glyph = val2) ''' user_name = kwargs.get('user_name', args[0]) kind = kwargs.get('kind', args[1]) num = kwargs.get('num', args[2] if len(args) > 2 else 6) with_tag = kwargs.get('with_tag', False) glyph = kwargs.get('glyph', '') all_cats = MUsage.query_most(user_name, kind, num).objects() kwd = { 'with_tag': with_tag, 'router': router_post[kind], 'glyph': glyph } return self.render_string('modules/info/list_user_equation.html', recs=all_cats, kwd=kwd)
fun(user_name, kind) fun(user_name, kind, num) fun(user_name, kind, num, with_tag = val1, glyph = val2) fun(user_name = vala, kind = valb, num = valc, with_tag = val1, glyph = val2)
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/modules/info_modules.py#L64-L85
bukun/TorCMS
torcms/modules/info_modules.py
InfoMostUsed.render_it
def render_it(self, *args, **kwargs): ''' Render without userinfo. fun(kind, num) fun(kind, num, with_tag = val1) fun(kind, num, with_tag = val1, glyph = val2) ''' kind = kwargs.get('kind', args[0]) num = kwargs.get('num', args[1] if len(args) > 1 else 6) with_tag = kwargs.get('with_tag', False) glyph = kwargs.get('glyph', '') all_cats = MPost.query_most(kind=kind, num=num).objects() kwd = { 'with_tag': with_tag, 'router': router_post[kind], 'glyph': glyph } return self.render_string('modules/info/list_equation.html', recs=all_cats, kwd=kwd)
python
def render_it(self, *args, **kwargs): ''' Render without userinfo. fun(kind, num) fun(kind, num, with_tag = val1) fun(kind, num, with_tag = val1, glyph = val2) ''' kind = kwargs.get('kind', args[0]) num = kwargs.get('num', args[1] if len(args) > 1 else 6) with_tag = kwargs.get('with_tag', False) glyph = kwargs.get('glyph', '') all_cats = MPost.query_most(kind=kind, num=num).objects() kwd = { 'with_tag': with_tag, 'router': router_post[kind], 'glyph': glyph } return self.render_string('modules/info/list_equation.html', recs=all_cats, kwd=kwd)
Render without userinfo. fun(kind, num) fun(kind, num, with_tag = val1) fun(kind, num, with_tag = val1, glyph = val2)
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/modules/info_modules.py#L112-L132
bukun/TorCMS
torcms/modules/info_modules.py
InfoRecentUsed.render_it
def render_it(self, kind, num, with_tag=False, glyph=''): ''' render, no user logged in ''' all_cats = MPost.query_recent(num, kind=kind) kwd = { 'with_tag': with_tag, 'router': router_post[kind], 'glyph': glyph } return self.render_string('modules/info/list_equation.html', recs=all_cats, kwd=kwd)
python
def render_it(self, kind, num, with_tag=False, glyph=''): ''' render, no user logged in ''' all_cats = MPost.query_recent(num, kind=kind) kwd = { 'with_tag': with_tag, 'router': router_post[kind], 'glyph': glyph } return self.render_string('modules/info/list_equation.html', recs=all_cats, kwd=kwd)
render, no user logged in
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/modules/info_modules.py#L185-L197
bukun/TorCMS
torcms/modules/info_modules.py
InfoRecentUsed.render_user
def render_user(self, *args, **kwargs): ''' render, with userinfo fun(kind, num) fun(kind, num, with_tag = val1) fun(kind, num, with_tag = val1, user_id = val2) fun(kind, num, with_tag = val1, user_id = val2, glyph = val3) ''' kind = kwargs.get('kind', args[0]) num = kwargs.get('num', args[1] if len(args) > 1 else 6) with_tag = kwargs.get('with_tag', False) user_id = kwargs.get('user_id', '') glyph = kwargs.get('glyph', '') logger.info( 'Infor user recent, username: {user_name}, kind: {kind}, num: {num}'.format( user_name=user_id, kind=kind, num=num ) ) all_cats = MUsage.query_recent(user_id, kind, num).objects() kwd = { 'with_tag': with_tag, 'router': router_post[kind], 'glyph': glyph } return self.render_string('modules/info/list_user_equation.html', recs=all_cats, kwd=kwd)
python
def render_user(self, *args, **kwargs): ''' render, with userinfo fun(kind, num) fun(kind, num, with_tag = val1) fun(kind, num, with_tag = val1, user_id = val2) fun(kind, num, with_tag = val1, user_id = val2, glyph = val3) ''' kind = kwargs.get('kind', args[0]) num = kwargs.get('num', args[1] if len(args) > 1 else 6) with_tag = kwargs.get('with_tag', False) user_id = kwargs.get('user_id', '') glyph = kwargs.get('glyph', '') logger.info( 'Infor user recent, username: {user_name}, kind: {kind}, num: {num}'.format( user_name=user_id, kind=kind, num=num ) ) all_cats = MUsage.query_recent(user_id, kind, num).objects() kwd = { 'with_tag': with_tag, 'router': router_post[kind], 'glyph': glyph } return self.render_string('modules/info/list_user_equation.html', recs=all_cats, kwd=kwd)
render, with userinfo fun(kind, num) fun(kind, num, with_tag = val1) fun(kind, num, with_tag = val1, user_id = val2) fun(kind, num, with_tag = val1, user_id = val2, glyph = val3)
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/modules/info_modules.py#L199-L228
bukun/TorCMS
torcms/handlers/link_handler.py
LinkHandler.recent
def recent(self): ''' Recent links. ''' kwd = { 'pager': '', 'title': '最近文档', } if self.is_p: self.render('admin/link_ajax/link_list.html', kwd=kwd, view=MLink.query_link(20), format_date=tools.format_date, userinfo=self.userinfo) else: self.render('misc/link/link_list.html', kwd=kwd, view=MLink.query_link(20), format_date=tools.format_date, userinfo=self.userinfo)
python
def recent(self): ''' Recent links. ''' kwd = { 'pager': '', 'title': '最近文档', } if self.is_p: self.render('admin/link_ajax/link_list.html', kwd=kwd, view=MLink.query_link(20), format_date=tools.format_date, userinfo=self.userinfo) else: self.render('misc/link/link_list.html', kwd=kwd, view=MLink.query_link(20), format_date=tools.format_date, userinfo=self.userinfo)
Recent links.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/link_handler.py#L58-L78
bukun/TorCMS
torcms/handlers/link_handler.py
LinkHandler.to_add_link
def to_add_link(self, ): ''' To add link ''' if self.check_post_role()['ADD']: pass else: return False kwd = { 'pager': '', 'uid': '', } self.render('misc/link/link_add.html', topmenu='', kwd=kwd, userinfo=self.userinfo, )
python
def to_add_link(self, ): ''' To add link ''' if self.check_post_role()['ADD']: pass else: return False kwd = { 'pager': '', 'uid': '', } self.render('misc/link/link_add.html', topmenu='', kwd=kwd, userinfo=self.userinfo, )
To add link
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/link_handler.py#L80-L95
bukun/TorCMS
torcms/handlers/link_handler.py
LinkHandler.update
def update(self, uid): ''' Update the link. ''' if self.userinfo.role[1] >= '3': pass else: return False post_data = self.get_post_data() post_data['user_name'] = self.get_current_user() if self.is_p: if MLink.update(uid, post_data): output = { 'addinfo ': 1, } else: output = { 'addinfo ': 0, } return json.dump(output, self) else: if MLink.update(uid, post_data): self.redirect('/link/list')
python
def update(self, uid): ''' Update the link. ''' if self.userinfo.role[1] >= '3': pass else: return False post_data = self.get_post_data() post_data['user_name'] = self.get_current_user() if self.is_p: if MLink.update(uid, post_data): output = { 'addinfo ': 1, } else: output = { 'addinfo ': 0, } return json.dump(output, self) else: if MLink.update(uid, post_data): self.redirect('/link/list')
Update the link.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/link_handler.py#L98-L122
bukun/TorCMS
torcms/handlers/link_handler.py
LinkHandler.to_modify
def to_modify(self, uid): ''' Try to edit the link. ''' if self.userinfo.role[1] >= '3': pass else: return False self.render('misc/link/link_edit.html', kwd={}, postinfo=MLink.get_by_uid(uid), userinfo=self.userinfo)
python
def to_modify(self, uid): ''' Try to edit the link. ''' if self.userinfo.role[1] >= '3': pass else: return False self.render('misc/link/link_edit.html', kwd={}, postinfo=MLink.get_by_uid(uid), userinfo=self.userinfo)
Try to edit the link.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/link_handler.py#L125-L137
bukun/TorCMS
torcms/handlers/link_handler.py
LinkHandler.viewit
def viewit(self, post_id): ''' View the link. ''' rec = MLink.get_by_uid(post_id) if not rec: kwd = {'info': '您要找的分类不存在。'} self.render('misc/html/404.html', kwd=kwd) return False kwd = { 'pager': '', 'editable': self.editable(), } self.render('misc/link/link_view.html', view=rec, kwd=kwd, userinfo=self.userinfo, cfg=CMS_CFG, )
python
def viewit(self, post_id): ''' View the link. ''' rec = MLink.get_by_uid(post_id) if not rec: kwd = {'info': '您要找的分类不存在。'} self.render('misc/html/404.html', kwd=kwd) return False kwd = { 'pager': '', 'editable': self.editable(), } self.render('misc/link/link_view.html', view=rec, kwd=kwd, userinfo=self.userinfo, cfg=CMS_CFG, )
View the link.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/link_handler.py#L140-L161
bukun/TorCMS
torcms/handlers/link_handler.py
LinkHandler.p_user_add_link
def p_user_add_link(self): ''' user add link. ''' if self.check_post_role()['ADD']: pass else: return False post_data = self.get_post_data() post_data['user_name'] = self.get_current_user() cur_uid = tools.get_uudd(2) while MLink.get_by_uid(cur_uid): cur_uid = tools.get_uudd(2) if MLink.create_link(cur_uid, post_data): output = { 'addinfo ': 1, } else: output = { 'addinfo ': 0, } return json.dump(output, self)
python
def p_user_add_link(self): ''' user add link. ''' if self.check_post_role()['ADD']: pass else: return False post_data = self.get_post_data() post_data['user_name'] = self.get_current_user() cur_uid = tools.get_uudd(2) while MLink.get_by_uid(cur_uid): cur_uid = tools.get_uudd(2) if MLink.create_link(cur_uid, post_data): output = { 'addinfo ': 1, } else: output = { 'addinfo ': 0, } return json.dump(output, self)
user add link.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/link_handler.py#L164-L188
bukun/TorCMS
torcms/handlers/link_handler.py
LinkHandler.user_add_link
def user_add_link(self): ''' Create link by user. ''' if self.check_post_role()['ADD']: pass else: return False post_data = self.get_post_data() post_data['user_name'] = self.get_current_user() cur_uid = tools.get_uudd(2) while MLink.get_by_uid(cur_uid): cur_uid = tools.get_uudd(2) MLink.create_link(cur_uid, post_data) self.redirect('/link/list')
python
def user_add_link(self): ''' Create link by user. ''' if self.check_post_role()['ADD']: pass else: return False post_data = self.get_post_data() post_data['user_name'] = self.get_current_user() cur_uid = tools.get_uudd(2) while MLink.get_by_uid(cur_uid): cur_uid = tools.get_uudd(2) MLink.create_link(cur_uid, post_data) self.redirect('/link/list')
Create link by user.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/link_handler.py#L191-L209
bukun/TorCMS
torcms/handlers/link_handler.py
LinkHandler.delete_by_id
def delete_by_id(self, del_id): ''' Delete a link by id. ''' if self.check_post_role()['DELETE']: pass else: return False if self.is_p: if MLink.delete(del_id): output = {'del_link': 1} else: output = {'del_link': 0} return json.dump(output, self) else: is_deleted = MLink.delete(del_id) if is_deleted: self.redirect('/link/list')
python
def delete_by_id(self, del_id): ''' Delete a link by id. ''' if self.check_post_role()['DELETE']: pass else: return False if self.is_p: if MLink.delete(del_id): output = {'del_link': 1} else: output = {'del_link': 0} return json.dump(output, self) else: is_deleted = MLink.delete(del_id) if is_deleted: self.redirect('/link/list')
Delete a link by id.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/link_handler.py#L212-L229
bukun/TorCMS
torcms/model/rating_model.py
MRating.get_rating
def get_rating(postid, userid): ''' Get the rating of certain post and user. ''' try: recs = TabRating.select().where( (TabRating.post_id == postid) & (TabRating.user_id == userid) ) except: return False if recs.count() > 0: return recs.get().rating else: return False
python
def get_rating(postid, userid): ''' Get the rating of certain post and user. ''' try: recs = TabRating.select().where( (TabRating.post_id == postid) & (TabRating.user_id == userid) ) except: return False if recs.count() > 0: return recs.get().rating else: return False
Get the rating of certain post and user.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/rating_model.py#L31-L44
bukun/TorCMS
torcms/model/rating_model.py
MRating.update
def update(postid, userid, rating): ''' Update the rating of certain post and user. The record will be created if no record exists. ''' rating_recs = TabRating.select().where( (TabRating.post_id == postid) & (TabRating.user_id == userid) ) if rating_recs.count() > 0: MRating.__update_rating(rating_recs.get().uid, rating) else: MRating.__insert_data(postid, userid, rating)
python
def update(postid, userid, rating): ''' Update the rating of certain post and user. The record will be created if no record exists. ''' rating_recs = TabRating.select().where( (TabRating.post_id == postid) & (TabRating.user_id == userid) ) if rating_recs.count() > 0: MRating.__update_rating(rating_recs.get().uid, rating) else: MRating.__insert_data(postid, userid, rating)
Update the rating of certain post and user. The record will be created if no record exists.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/rating_model.py#L47-L58
bukun/TorCMS
torcms/model/rating_model.py
MRating.__update_rating
def __update_rating(uid, rating): ''' Update rating. ''' entry = TabRating.update( rating=rating ).where(TabRating.uid == uid) entry.execute()
python
def __update_rating(uid, rating): ''' Update rating. ''' entry = TabRating.update( rating=rating ).where(TabRating.uid == uid) entry.execute()
Update rating.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/rating_model.py#L61-L68
bukun/TorCMS
torcms/model/rating_model.py
MRating.__insert_data
def __insert_data(postid, userid, rating): ''' Inert new record. ''' uid = tools.get_uuid() TabRating.create( uid=uid, post_id=postid, user_id=userid, rating=rating, timestamp=tools.timestamp(), ) return uid
python
def __insert_data(postid, userid, rating): ''' Inert new record. ''' uid = tools.get_uuid() TabRating.create( uid=uid, post_id=postid, user_id=userid, rating=rating, timestamp=tools.timestamp(), ) return uid
Inert new record.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/rating_model.py#L71-L83
bukun/TorCMS
helper_scripts/script_meta_xlsx_import.py
update_category
def update_category(uid, postdata, kwargs): ''' Update the category of the post. ''' catid = kwargs['catid'] if ('catid' in kwargs and MCategory.get_by_uid(kwargs['catid'])) else None post_data = postdata current_infos = MPost2Catalog.query_by_entity_uid(uid, kind='').objects() new_category_arr = [] # Used to update post2category, to keep order. def_cate_arr = ['gcat{0}'.format(x) for x in range(10)] # for old page. def_cate_arr.append('def_cat_uid') # Used to update post extinfo. cat_dic = {} for key in def_cate_arr: if key not in post_data: continue if post_data[key] == '' or post_data[key] == '0': continue # 有可能选重复了。保留前面的 if post_data[key] in new_category_arr: continue new_category_arr.append(post_data[key] + ' ' * (4 - len(post_data[key]))) cat_dic[key] = post_data[key] + ' ' * (4 - len(post_data[key])) if catid: def_cat_id = catid elif new_category_arr: def_cat_id = new_category_arr[0] else: def_cat_id = None if def_cat_id: cat_dic['def_cat_uid'] = def_cat_id cat_dic['def_cat_pid'] = MCategory.get_by_uid(def_cat_id).pid print('=' * 40) print(uid) print(cat_dic) MPost.update_jsonb(uid, cat_dic) for index, catid in enumerate(new_category_arr): MPost2Catalog.add_record(uid, catid, index) # Delete the old category if not in post requests. for cur_info in current_infos: if cur_info.tag_id not in new_category_arr: MPost2Catalog.remove_relation(uid, cur_info.tag_id)
python
def update_category(uid, postdata, kwargs): ''' Update the category of the post. ''' catid = kwargs['catid'] if ('catid' in kwargs and MCategory.get_by_uid(kwargs['catid'])) else None post_data = postdata current_infos = MPost2Catalog.query_by_entity_uid(uid, kind='').objects() new_category_arr = [] # Used to update post2category, to keep order. def_cate_arr = ['gcat{0}'.format(x) for x in range(10)] # for old page. def_cate_arr.append('def_cat_uid') # Used to update post extinfo. cat_dic = {} for key in def_cate_arr: if key not in post_data: continue if post_data[key] == '' or post_data[key] == '0': continue # 有可能选重复了。保留前面的 if post_data[key] in new_category_arr: continue new_category_arr.append(post_data[key] + ' ' * (4 - len(post_data[key]))) cat_dic[key] = post_data[key] + ' ' * (4 - len(post_data[key])) if catid: def_cat_id = catid elif new_category_arr: def_cat_id = new_category_arr[0] else: def_cat_id = None if def_cat_id: cat_dic['def_cat_uid'] = def_cat_id cat_dic['def_cat_pid'] = MCategory.get_by_uid(def_cat_id).pid print('=' * 40) print(uid) print(cat_dic) MPost.update_jsonb(uid, cat_dic) for index, catid in enumerate(new_category_arr): MPost2Catalog.add_record(uid, catid, index) # Delete the old category if not in post requests. for cur_info in current_infos: if cur_info.tag_id not in new_category_arr: MPost2Catalog.remove_relation(uid, cur_info.tag_id)
Update the category of the post.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/helper_scripts/script_meta_xlsx_import.py#L19-L72
bukun/TorCMS
ext_script/command.py
entry
def entry(argv): ''' Command entry ''' command_dic = { 'init': run_init, } try: # 这里的 h 就表示该选项无参数,i:表示 i 选项后需要有参数 opts, args = getopt.getopt(argv, "hi:") except getopt.GetoptError: print('Error: helper.py -i cmd') sys.exit(2) for opt, arg in opts: if opt == "-h": print('helper.py -i cmd') print('cmd list ----------------------') print(' init: ') sys.exit() elif opt == "-i": if arg in command_dic: command_dic[arg](args) print('QED!') else: print('Wrong Command.')
python
def entry(argv): ''' Command entry ''' command_dic = { 'init': run_init, } try: # 这里的 h 就表示该选项无参数,i:表示 i 选项后需要有参数 opts, args = getopt.getopt(argv, "hi:") except getopt.GetoptError: print('Error: helper.py -i cmd') sys.exit(2) for opt, arg in opts: if opt == "-h": print('helper.py -i cmd') print('cmd list ----------------------') print(' init: ') sys.exit() elif opt == "-i": if arg in command_dic: command_dic[arg](args) print('QED!') else: print('Wrong Command.')
Command entry
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/ext_script/command.py#L16-L47
bukun/TorCMS
torcms/model/relation_model.py
MRelation.add_relation
def add_relation(app_f, app_t, weight=1): ''' Adding relation between two posts. ''' recs = TabRel.select().where( (TabRel.post_f_id == app_f) & (TabRel.post_t_id == app_t) ) if recs.count() > 1: for record in recs: MRelation.delete(record.uid) if recs.count() == 0: uid = tools.get_uuid() entry = TabRel.create( uid=uid, post_f_id=app_f, post_t_id=app_t, count=1, ) return entry.uid elif recs.count() == 1: MRelation.update_relation(app_f, app_t, weight) else: return False
python
def add_relation(app_f, app_t, weight=1): ''' Adding relation between two posts. ''' recs = TabRel.select().where( (TabRel.post_f_id == app_f) & (TabRel.post_t_id == app_t) ) if recs.count() > 1: for record in recs: MRelation.delete(record.uid) if recs.count() == 0: uid = tools.get_uuid() entry = TabRel.create( uid=uid, post_f_id=app_f, post_t_id=app_t, count=1, ) return entry.uid elif recs.count() == 1: MRelation.update_relation(app_f, app_t, weight) else: return False
Adding relation between two posts.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/relation_model.py#L15-L38
bukun/TorCMS
torcms/model/relation_model.py
MRelation.get_app_relations
def get_app_relations(app_id, num=20, kind='1'): ''' The the related infors. ''' info_tag = MInfor2Catalog.get_first_category(app_id) if info_tag: return TabPost2Tag.select( TabPost2Tag, TabPost.title.alias('post_title'), TabPost.valid.alias('post_valid') ).join( TabPost, on=(TabPost2Tag.post_id == TabPost.uid) ).where( (TabPost2Tag.tag_id == info_tag.tag_id) & (TabPost.kind == kind) ).order_by( peewee.fn.Random() ).limit(num) return TabPost2Tag.select( TabPost2Tag, TabPost.title.alias('post_title'), TabPost.valid.alias('post_valid') ).join( TabPost, on=(TabPost2Tag.post_id == TabPost.uid) ).where( TabPost.kind == kind ).order_by(peewee.fn.Random()).limit(num)
python
def get_app_relations(app_id, num=20, kind='1'): ''' The the related infors. ''' info_tag = MInfor2Catalog.get_first_category(app_id) if info_tag: return TabPost2Tag.select( TabPost2Tag, TabPost.title.alias('post_title'), TabPost.valid.alias('post_valid') ).join( TabPost, on=(TabPost2Tag.post_id == TabPost.uid) ).where( (TabPost2Tag.tag_id == info_tag.tag_id) & (TabPost.kind == kind) ).order_by( peewee.fn.Random() ).limit(num) return TabPost2Tag.select( TabPost2Tag, TabPost.title.alias('post_title'), TabPost.valid.alias('post_valid') ).join( TabPost, on=(TabPost2Tag.post_id == TabPost.uid) ).where( TabPost.kind == kind ).order_by(peewee.fn.Random()).limit(num)
The the related infors.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/relation_model.py#L63-L89
bukun/TorCMS
torcms/handlers/label_handler.py
LabelHandler.get
def get(self, *args, **kwargs): ''' /label/s/view ''' url_arr = self.parse_url(args[0]) if len(url_arr) == 2: if url_arr[0] == 'remove': self.remove_redis_keyword(url_arr[1]) else: self.list(url_arr[0], url_arr[1]) elif len(url_arr) == 3: self.list(url_arr[0], url_arr[1], url_arr[2]) else: return False
python
def get(self, *args, **kwargs): ''' /label/s/view ''' url_arr = self.parse_url(args[0]) if len(url_arr) == 2: if url_arr[0] == 'remove': self.remove_redis_keyword(url_arr[1]) else: self.list(url_arr[0], url_arr[1]) elif len(url_arr) == 3: self.list(url_arr[0], url_arr[1], url_arr[2]) else: return False
/label/s/view
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/label_handler.py#L27-L41
bukun/TorCMS
torcms/handlers/label_handler.py
LabelHandler.remove_redis_keyword
def remove_redis_keyword(self, keyword): ''' Remove the keyword for redis. ''' redisvr.srem(CMS_CFG['redis_kw'] + self.userinfo.user_name, keyword) return json.dump({}, self)
python
def remove_redis_keyword(self, keyword): ''' Remove the keyword for redis. ''' redisvr.srem(CMS_CFG['redis_kw'] + self.userinfo.user_name, keyword) return json.dump({}, self)
Remove the keyword for redis.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/label_handler.py#L44-L49
bukun/TorCMS
torcms/handlers/label_handler.py
LabelHandler.list
def list(self, kind, tag_slug, cur_p=''): ''' 根据 cat_handler.py 中的 def view_cat_new(self, cat_slug, cur_p = '') ''' # 下面用来使用关键字过滤信息,如果网站信息量不是很大不要开启 # Todo: # if self.get_current_user(): # redisvr.sadd(config.redis_kw + self.userinfo.user_name, tag_slug) if cur_p == '': current_page_number = 1 else: current_page_number = int(cur_p) current_page_number = 1 if current_page_number < 1 else current_page_number pager_num = int(MPost2Label.total_number(tag_slug, kind) / CMS_CFG['list_num']) tag_info = MLabel.get_by_slug(tag_slug) if tag_info: tag_name = tag_info.name else: tag_name = 'Label search results' kwd = {'tag_name': tag_name, 'tag_slug': tag_slug, 'title': tag_name, 'current_page': current_page_number, 'router': router_post[kind], 'kind': kind } the_list_file = './templates/list/label_{kind}.html'.format(kind=kind) if os.path.exists(the_list_file): tmpl = 'list/label_{kind}.html'.format(kind=kind) else: tmpl = 'list/label.html' self.render(tmpl, infos=MPost2Label.query_pager_by_slug( tag_slug, kind=kind, current_page_num=current_page_number ), kwd=kwd, userinfo=self.userinfo, pager=self.gen_pager(kind, tag_slug, pager_num, current_page_number), cfg=CMS_CFG)
python
def list(self, kind, tag_slug, cur_p=''): ''' 根据 cat_handler.py 中的 def view_cat_new(self, cat_slug, cur_p = '') ''' # 下面用来使用关键字过滤信息,如果网站信息量不是很大不要开启 # Todo: # if self.get_current_user(): # redisvr.sadd(config.redis_kw + self.userinfo.user_name, tag_slug) if cur_p == '': current_page_number = 1 else: current_page_number = int(cur_p) current_page_number = 1 if current_page_number < 1 else current_page_number pager_num = int(MPost2Label.total_number(tag_slug, kind) / CMS_CFG['list_num']) tag_info = MLabel.get_by_slug(tag_slug) if tag_info: tag_name = tag_info.name else: tag_name = 'Label search results' kwd = {'tag_name': tag_name, 'tag_slug': tag_slug, 'title': tag_name, 'current_page': current_page_number, 'router': router_post[kind], 'kind': kind } the_list_file = './templates/list/label_{kind}.html'.format(kind=kind) if os.path.exists(the_list_file): tmpl = 'list/label_{kind}.html'.format(kind=kind) else: tmpl = 'list/label.html' self.render(tmpl, infos=MPost2Label.query_pager_by_slug( tag_slug, kind=kind, current_page_num=current_page_number ), kwd=kwd, userinfo=self.userinfo, pager=self.gen_pager(kind, tag_slug, pager_num, current_page_number), cfg=CMS_CFG)
根据 cat_handler.py 中的 def view_cat_new(self, cat_slug, cur_p = '')
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/label_handler.py#L51-L98
bukun/TorCMS
torcms/handlers/label_handler.py
LabelHandler.gen_pager
def gen_pager(self, kind, cat_slug, page_num, current): ''' cat_slug 分类 page_num 页面总数 current 当前页面 ''' if page_num == 1: return '' pager_shouye = '''<li class="{0}"> <a href="/label/{1}/{2}">&lt;&lt; 首页</a> </li>'''.format( 'hidden' if current <= 1 else '', kind, cat_slug ) pager_pre = '''<li class="{0}"><a href="/label/{1}/{2}/{3}">&lt; 前页</a> </li>'''.format( 'hidden' if current <= 1 else '', kind, cat_slug, current - 1 ) pager_mid = '' for ind in range(0, page_num): tmp_mid = '''<li class="{0}"><a href="/label/{1}/{2}/{3}">{3}</a> </li>'''.format( 'active' if ind + 1 == current else '', kind, cat_slug, ind + 1 ) pager_mid += tmp_mid pager_next = '''<li class=" {0}"><a href="/label/{1}/{2}/{3}">后页 &gt;</a> </li>'''.format( 'hidden' if current >= page_num else '', kind, cat_slug, current + 1 ) pager_last = '''<li class=" {0}"><a href="/label/{1}/{2}/{3}">末页&gt;&gt;</a> </li>'''.format( 'hidden' if current >= page_num else '', kind, cat_slug, page_num ) pager = pager_shouye + pager_pre + pager_mid + pager_next + pager_last return pager
python
def gen_pager(self, kind, cat_slug, page_num, current): ''' cat_slug 分类 page_num 页面总数 current 当前页面 ''' if page_num == 1: return '' pager_shouye = '''<li class="{0}"> <a href="/label/{1}/{2}">&lt;&lt; 首页</a> </li>'''.format( 'hidden' if current <= 1 else '', kind, cat_slug ) pager_pre = '''<li class="{0}"><a href="/label/{1}/{2}/{3}">&lt; 前页</a> </li>'''.format( 'hidden' if current <= 1 else '', kind, cat_slug, current - 1 ) pager_mid = '' for ind in range(0, page_num): tmp_mid = '''<li class="{0}"><a href="/label/{1}/{2}/{3}">{3}</a> </li>'''.format( 'active' if ind + 1 == current else '', kind, cat_slug, ind + 1 ) pager_mid += tmp_mid pager_next = '''<li class=" {0}"><a href="/label/{1}/{2}/{3}">后页 &gt;</a> </li>'''.format( 'hidden' if current >= page_num else '', kind, cat_slug, current + 1 ) pager_last = '''<li class=" {0}"><a href="/label/{1}/{2}/{3}">末页&gt;&gt;</a> </li>'''.format( 'hidden' if current >= page_num else '', kind, cat_slug, page_num ) pager = pager_shouye + pager_pre + pager_mid + pager_next + pager_last return pager
cat_slug 分类 page_num 页面总数 current 当前页面
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/label_handler.py#L100-L134
bukun/TorCMS
torcms/script/script_funcs.py
build_directory
def build_directory(): ''' Build the directory for Whoosh database, and locale. ''' if os.path.exists('locale'): pass else: os.mkdir('locale') if os.path.exists(WHOOSH_DB_DIR): pass else: os.makedirs(WHOOSH_DB_DIR)
python
def build_directory(): ''' Build the directory for Whoosh database, and locale. ''' if os.path.exists('locale'): pass else: os.mkdir('locale') if os.path.exists(WHOOSH_DB_DIR): pass else: os.makedirs(WHOOSH_DB_DIR)
Build the directory for Whoosh database, and locale.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/script_funcs.py#L22-L33
bukun/TorCMS
torcms/script/script_funcs.py
run_check_kind
def run_check_kind(_): ''' Running the script. ''' for kindv in router_post: for rec_cat in MCategory.query_all(kind=kindv): catid = rec_cat.uid catinfo = MCategory.get_by_uid(catid) for rec_post2tag in MPost2Catalog.query_by_catid(catid): postinfo = MPost.get_by_uid(rec_post2tag.post_id) if postinfo.kind == catinfo.kind: pass else: print(postinfo.uid)
python
def run_check_kind(_): ''' Running the script. ''' for kindv in router_post: for rec_cat in MCategory.query_all(kind=kindv): catid = rec_cat.uid catinfo = MCategory.get_by_uid(catid) for rec_post2tag in MPost2Catalog.query_by_catid(catid): postinfo = MPost.get_by_uid(rec_post2tag.post_id) if postinfo.kind == catinfo.kind: pass else: print(postinfo.uid)
Running the script.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/script_funcs.py#L36-L49
bukun/TorCMS
torcms/script/script_funcs.py
run_create_admin
def run_create_admin(*args): ''' creating the default administrator. ''' post_data = { 'user_name': 'giser', 'user_email': '[email protected]', 'user_pass': '131322', 'role': '3300', } if MUser.get_by_name(post_data['user_name']): print('User {user_name} already exists.'.format(user_name='giser')) else: MUser.create_user(post_data)
python
def run_create_admin(*args): ''' creating the default administrator. ''' post_data = { 'user_name': 'giser', 'user_email': '[email protected]', 'user_pass': '131322', 'role': '3300', } if MUser.get_by_name(post_data['user_name']): print('User {user_name} already exists.'.format(user_name='giser')) else: MUser.create_user(post_data)
creating the default administrator.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/script_funcs.py#L52-L65
bukun/TorCMS
torcms/script/script_funcs.py
run_update_cat
def run_update_cat(_): ''' Update the catagery. ''' recs = MPost2Catalog.query_all().objects() for rec in recs: if rec.tag_kind != 'z': print('-' * 40) print(rec.uid) print(rec.tag_id) print(rec.par_id) MPost2Catalog.update_field(rec.uid, par_id=rec.tag_id[:2] + "00")
python
def run_update_cat(_): ''' Update the catagery. ''' recs = MPost2Catalog.query_all().objects() for rec in recs: if rec.tag_kind != 'z': print('-' * 40) print(rec.uid) print(rec.tag_id) print(rec.par_id) MPost2Catalog.update_field(rec.uid, par_id=rec.tag_id[:2] + "00")
Update the catagery.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/script_funcs.py#L75-L87
bukun/TorCMS
torcms/handlers/rating_handler.py
RatingHandler.update_post
def update_post(self, postid): ''' The rating of Post should be updaed if the count is greater than 10 ''' voted_recs = MRating.query_by_post(postid) if voted_recs.count() > 10: rating = MRating.query_average_rating(postid) else: rating = 5 logger.info('Get post rating: {rating}'.format(rating=rating)) # MPost.__update_rating(postid, rating) MPost.update_misc(postid, rating=rating)
python
def update_post(self, postid): ''' The rating of Post should be updaed if the count is greater than 10 ''' voted_recs = MRating.query_by_post(postid) if voted_recs.count() > 10: rating = MRating.query_average_rating(postid) else: rating = 5 logger.info('Get post rating: {rating}'.format(rating=rating)) # MPost.__update_rating(postid, rating) MPost.update_misc(postid, rating=rating)
The rating of Post should be updaed if the count is greater than 10
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/rating_handler.py#L35-L49
bukun/TorCMS
torcms/handlers/rating_handler.py
RatingHandler.update_rating
def update_rating(self, postid): ''' only the used who logged in would voting. ''' post_data = self.get_post_data() rating = float(post_data['rating']) postinfo = MPost.get_by_uid(postid) if postinfo and self.userinfo: MRating.update(postinfo.uid, self.userinfo.uid, rating=rating) self.update_post(postid) else: return False
python
def update_rating(self, postid): ''' only the used who logged in would voting. ''' post_data = self.get_post_data() rating = float(post_data['rating']) postinfo = MPost.get_by_uid(postid) if postinfo and self.userinfo: MRating.update(postinfo.uid, self.userinfo.uid, rating=rating) self.update_post(postid) else: return False
only the used who logged in would voting.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/rating_handler.py#L52-L63
bukun/TorCMS
torcms/script/script_review.py
__get_diff_recent
def __get_diff_recent(): ''' Generate the difference of posts. recently. ''' diff_str = '' for key in router_post: recent_posts = MPost.query_recent_edited(tools.timestamp() - TIME_LIMIT, kind=key) for recent_post in recent_posts: hist_rec = MPostHist.get_last(recent_post.uid) if hist_rec: raw_title = hist_rec.title new_title = recent_post.title infobox = diff_table(raw_title, new_title) diff_str = diff_str + ''' <h2 style="color:red;font-size:larger;font-weight:70;">TITLE: {0}</h2> '''.format(recent_post.title) + infobox infobox = diff_table(hist_rec.cnt_md, recent_post.cnt_md) diff_str = diff_str + '<h3>CONTENT:{0}</h3>'.format( recent_post.title ) + infobox + '</hr>' else: continue return diff_str
python
def __get_diff_recent(): ''' Generate the difference of posts. recently. ''' diff_str = '' for key in router_post: recent_posts = MPost.query_recent_edited(tools.timestamp() - TIME_LIMIT, kind=key) for recent_post in recent_posts: hist_rec = MPostHist.get_last(recent_post.uid) if hist_rec: raw_title = hist_rec.title new_title = recent_post.title infobox = diff_table(raw_title, new_title) diff_str = diff_str + ''' <h2 style="color:red;font-size:larger;font-weight:70;">TITLE: {0}</h2> '''.format(recent_post.title) + infobox infobox = diff_table(hist_rec.cnt_md, recent_post.cnt_md) diff_str = diff_str + '<h3>CONTENT:{0}</h3>'.format( recent_post.title ) + infobox + '</hr>' else: continue return diff_str
Generate the difference of posts. recently.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/script_review.py#L23-L50
bukun/TorCMS
torcms/script/script_review.py
__get_wiki_review
def __get_wiki_review(email_cnt, idx): ''' Review for wikis. ''' recent_posts = MWiki.query_recent_edited(tools.timestamp() - TIME_LIMIT, kind='2') for recent_post in recent_posts: hist_rec = MWikiHist.get_last(recent_post.uid) if hist_rec: foo_str = ''' <tr><td>{0}</td><td>{1}</td><td class="diff_chg">Edit</td><td>{2}</td> <td><a href="{3}">{3}</a></td></tr> '''.format(idx, recent_post.user_name, recent_post.title, os.path.join(SITE_CFG['site_url'], 'page', recent_post.uid)) email_cnt = email_cnt + foo_str else: foo_str = ''' <tr><td>{0}</td><td>{1}</td><td class="diff_add">New </td><td>{2}</td> <td><a href="{3}">{3}</a></td></tr> '''.format(idx, recent_post.user_name, recent_post.title, os.path.join(SITE_CFG['site_url'], 'page', recent_post.uid)) email_cnt = email_cnt + foo_str idx = idx + 1 email_cnt = email_cnt + '</table>' return email_cnt, idx
python
def __get_wiki_review(email_cnt, idx): ''' Review for wikis. ''' recent_posts = MWiki.query_recent_edited(tools.timestamp() - TIME_LIMIT, kind='2') for recent_post in recent_posts: hist_rec = MWikiHist.get_last(recent_post.uid) if hist_rec: foo_str = ''' <tr><td>{0}</td><td>{1}</td><td class="diff_chg">Edit</td><td>{2}</td> <td><a href="{3}">{3}</a></td></tr> '''.format(idx, recent_post.user_name, recent_post.title, os.path.join(SITE_CFG['site_url'], 'page', recent_post.uid)) email_cnt = email_cnt + foo_str else: foo_str = ''' <tr><td>{0}</td><td>{1}</td><td class="diff_add">New </td><td>{2}</td> <td><a href="{3}">{3}</a></td></tr> '''.format(idx, recent_post.user_name, recent_post.title, os.path.join(SITE_CFG['site_url'], 'page', recent_post.uid)) email_cnt = email_cnt + foo_str idx = idx + 1 email_cnt = email_cnt + '</table>' return email_cnt, idx
Review for wikis.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/script_review.py#L53-L76
bukun/TorCMS
torcms/script/script_review.py
__get_post_review
def __get_post_review(email_cnt, idx): ''' Review for posts. ''' for key in router_post: recent_posts = MPost.query_recent_edited(tools.timestamp() - TIME_LIMIT, kind=key) for recent_post in recent_posts: hist_rec = MPostHist.get_last(recent_post.uid) if hist_rec: foo_str = ''' <tr><td>{0}</td><td>{1}</td><td class="diff_chg">Edit</td><td>{2}</td> <td><a href="{3}">{3}</a></td></tr> '''.format(idx, recent_post.user_name, recent_post.title, os.path.join(SITE_CFG['site_url'], router_post[key], recent_post.uid)) email_cnt = email_cnt + foo_str else: foo_str = ''' <tr><td>{0}</td><td>{1}</td><td class="diff_add">New </td><td>{2}</td> <td><a href="{3}">{3}</a></td></tr> '''.format(idx, recent_post.user_name, recent_post.title, os.path.join(SITE_CFG['site_url'], router_post[key], recent_post.uid)) email_cnt = email_cnt + foo_str idx = idx + 1 return email_cnt, idx
python
def __get_post_review(email_cnt, idx): ''' Review for posts. ''' for key in router_post: recent_posts = MPost.query_recent_edited(tools.timestamp() - TIME_LIMIT, kind=key) for recent_post in recent_posts: hist_rec = MPostHist.get_last(recent_post.uid) if hist_rec: foo_str = ''' <tr><td>{0}</td><td>{1}</td><td class="diff_chg">Edit</td><td>{2}</td> <td><a href="{3}">{3}</a></td></tr> '''.format(idx, recent_post.user_name, recent_post.title, os.path.join(SITE_CFG['site_url'], router_post[key], recent_post.uid)) email_cnt = email_cnt + foo_str else: foo_str = ''' <tr><td>{0}</td><td>{1}</td><td class="diff_add">New </td><td>{2}</td> <td><a href="{3}">{3}</a></td></tr> '''.format(idx, recent_post.user_name, recent_post.title, os.path.join(SITE_CFG['site_url'], router_post[key], recent_post.uid)) email_cnt = email_cnt + foo_str idx = idx + 1 return email_cnt, idx
Review for posts.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/script_review.py#L105-L131
bukun/TorCMS
torcms/script/script_review.py
run_review
def run_review(*args): ''' Get the difference of recents modification, and send the Email. For: wiki, page, and post. ''' email_cnt = '''<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <style type="text/css"> table.diff {font-family:Courier; border:medium;} .diff_header {background-color:#e0e0e0} td.diff_header {text-align:right} .diff_next {background-color:#c0c0c0} .diff_add {background-color:#aaffaa} .diff_chg {background-color:#ffff77} .diff_sub {background-color:#ffaaaa} </style></head><body>''' idx = 1 email_cnt = email_cnt + '<table border=1>' email_cnt, idx = __get_post_review(email_cnt, idx) # post email_cnt, idx = __get_page_review(email_cnt, idx) # page. email_cnt, idx = __get_wiki_review(email_cnt, idx) # wiki ########################################################### diff_str = __get_diff_recent() if len(diff_str) < 20000: email_cnt = email_cnt + diff_str email_cnt = email_cnt + '''</body></html>''' if idx > 1: send_mail(post_emails, "{0}|{1}|{2}".format(SMTP_CFG['name'], '文档更新情况', DATE_STR), email_cnt)
python
def run_review(*args): ''' Get the difference of recents modification, and send the Email. For: wiki, page, and post. ''' email_cnt = '''<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <style type="text/css"> table.diff {font-family:Courier; border:medium;} .diff_header {background-color:#e0e0e0} td.diff_header {text-align:right} .diff_next {background-color:#c0c0c0} .diff_add {background-color:#aaffaa} .diff_chg {background-color:#ffff77} .diff_sub {background-color:#ffaaaa} </style></head><body>''' idx = 1 email_cnt = email_cnt + '<table border=1>' email_cnt, idx = __get_post_review(email_cnt, idx) # post email_cnt, idx = __get_page_review(email_cnt, idx) # page. email_cnt, idx = __get_wiki_review(email_cnt, idx) # wiki ########################################################### diff_str = __get_diff_recent() if len(diff_str) < 20000: email_cnt = email_cnt + diff_str email_cnt = email_cnt + '''</body></html>''' if idx > 1: send_mail(post_emails, "{0}|{1}|{2}".format(SMTP_CFG['name'], '文档更新情况', DATE_STR), email_cnt)
Get the difference of recents modification, and send the Email. For: wiki, page, and post.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/script_review.py#L134-L168
bukun/TorCMS
torcms/model/category_model.py
MCategory.get_qian2
def get_qian2(qian2): ''' 用于首页。根据前两位,找到所有的大类与小类。 :param qian2: 分类id的前两位 :return: 数组,包含了找到的分类 ''' return TabTag.select().where( TabTag.uid.startswith(qian2) ).order_by(TabTag.order)
python
def get_qian2(qian2): ''' 用于首页。根据前两位,找到所有的大类与小类。 :param qian2: 分类id的前两位 :return: 数组,包含了找到的分类 ''' return TabTag.select().where( TabTag.uid.startswith(qian2) ).order_by(TabTag.order)
用于首页。根据前两位,找到所有的大类与小类。 :param qian2: 分类id的前两位 :return: 数组,包含了找到的分类
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/category_model.py#L31-L39
bukun/TorCMS
torcms/model/category_model.py
MCategory.query_all
def query_all(kind='1', by_count=False, by_order=True): ''' Qeury all the categories, order by count or defined order. ''' if by_count: recs = TabTag.select().where(TabTag.kind == kind).order_by(TabTag.count.desc()) elif by_order: recs = TabTag.select().where(TabTag.kind == kind).order_by(TabTag.order) else: recs = TabTag.select().where(TabTag.kind == kind).order_by(TabTag.uid) return recs
python
def query_all(kind='1', by_count=False, by_order=True): ''' Qeury all the categories, order by count or defined order. ''' if by_count: recs = TabTag.select().where(TabTag.kind == kind).order_by(TabTag.count.desc()) elif by_order: recs = TabTag.select().where(TabTag.kind == kind).order_by(TabTag.order) else: recs = TabTag.select().where(TabTag.kind == kind).order_by(TabTag.uid) return recs
Qeury all the categories, order by count or defined order.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/category_model.py#L69-L79
bukun/TorCMS
torcms/model/category_model.py
MCategory.query_field_count
def query_field_count(limit_num, kind='1'): ''' Query the posts count of certain category. ''' return TabTag.select().where( TabTag.kind == kind ).order_by( TabTag.count.desc() ).limit(limit_num)
python
def query_field_count(limit_num, kind='1'): ''' Query the posts count of certain category. ''' return TabTag.select().where( TabTag.kind == kind ).order_by( TabTag.count.desc() ).limit(limit_num)
Query the posts count of certain category.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/category_model.py#L82-L90
bukun/TorCMS
torcms/model/category_model.py
MCategory.get_by_slug
def get_by_slug(slug): ''' return the category record . ''' rec = TabTag.select().where(TabTag.slug == slug) if rec.count() > 0: return rec.get() return None
python
def get_by_slug(slug): ''' return the category record . ''' rec = TabTag.select().where(TabTag.slug == slug) if rec.count() > 0: return rec.get() return None
return the category record .
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/category_model.py#L93-L100
bukun/TorCMS
torcms/model/category_model.py
MCategory.update_count
def update_count(cat_id): ''' Update the count of certain category. ''' # Todo: the record not valid should not be counted. entry2 = TabTag.update( count=TabPost2Tag.select().where( TabPost2Tag.tag_id == cat_id ).count() ).where(TabTag.uid == cat_id) entry2.execute()
python
def update_count(cat_id): ''' Update the count of certain category. ''' # Todo: the record not valid should not be counted. entry2 = TabTag.update( count=TabPost2Tag.select().where( TabPost2Tag.tag_id == cat_id ).count() ).where(TabTag.uid == cat_id) entry2.execute()
Update the count of certain category.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/category_model.py#L103-L113
bukun/TorCMS
torcms/model/category_model.py
MCategory.update
def update(uid, post_data): ''' Update the category. ''' raw_rec = TabTag.get(TabTag.uid == uid) entry = TabTag.update( name=post_data['name'] if 'name' in post_data else raw_rec.name, slug=post_data['slug'] if 'slug' in post_data else raw_rec.slug, order=post_data['order'] if 'order' in post_data else raw_rec.order, kind=post_data['kind'] if 'kind' in post_data else raw_rec.kind, pid=post_data['pid'], ).where(TabTag.uid == uid) entry.execute()
python
def update(uid, post_data): ''' Update the category. ''' raw_rec = TabTag.get(TabTag.uid == uid) entry = TabTag.update( name=post_data['name'] if 'name' in post_data else raw_rec.name, slug=post_data['slug'] if 'slug' in post_data else raw_rec.slug, order=post_data['order'] if 'order' in post_data else raw_rec.order, kind=post_data['kind'] if 'kind' in post_data else raw_rec.kind, pid=post_data['pid'], ).where(TabTag.uid == uid) entry.execute()
Update the category.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/category_model.py#L116-L128
bukun/TorCMS
torcms/model/category_model.py
MCategory.add_or_update
def add_or_update(uid, post_data): ''' Add or update the data by the given ID of post. ''' catinfo = MCategory.get_by_uid(uid) if catinfo: MCategory.update(uid, post_data) else: TabTag.create( uid=uid, name=post_data['name'], slug=post_data['slug'], order=post_data['order'], kind=post_data['kind'] if 'kind' in post_data else '1', pid=post_data['pid'], ) return uid
python
def add_or_update(uid, post_data): ''' Add or update the data by the given ID of post. ''' catinfo = MCategory.get_by_uid(uid) if catinfo: MCategory.update(uid, post_data) else: TabTag.create( uid=uid, name=post_data['name'], slug=post_data['slug'], order=post_data['order'], kind=post_data['kind'] if 'kind' in post_data else '1', pid=post_data['pid'], ) return uid
Add or update the data by the given ID of post.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/category_model.py#L131-L147
bukun/TorCMS
torcms/handlers/category_handler.py
CategoryAjaxHandler.list_catalog
def list_catalog(self, kind): ''' listing the category. ''' kwd = { 'pager': '', 'title': '最近文档', 'kind': kind, 'router': config.router_post[kind] } self.render('admin/{0}/category_list.html'.format(self.tmpl_router), kwd=kwd, view=MCategory.query_all(kind, by_order=True), format_date=tools.format_date, userinfo=self.userinfo, cfg=config.CMS_CFG)
python
def list_catalog(self, kind): ''' listing the category. ''' kwd = { 'pager': '', 'title': '最近文档', 'kind': kind, 'router': config.router_post[kind] } self.render('admin/{0}/category_list.html'.format(self.tmpl_router), kwd=kwd, view=MCategory.query_all(kind, by_order=True), format_date=tools.format_date, userinfo=self.userinfo, cfg=config.CMS_CFG)
listing the category.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/category_handler.py#L38-L53
bukun/TorCMS
torcms/handlers/post_list_handler.py
PostListHandler.recent
def recent(self, with_catalog=True, with_date=True): ''' List posts that recent edited. ''' kwd = { 'pager': '', 'title': 'Recent posts.', 'with_catalog': with_catalog, 'with_date': with_date, } self.render('list/post_list.html', kwd=kwd, view=MPost.query_recent(num=20), postrecs=MPost.query_recent(num=2), format_date=tools.format_date, userinfo=self.userinfo, cfg=CMS_CFG, )
python
def recent(self, with_catalog=True, with_date=True): ''' List posts that recent edited. ''' kwd = { 'pager': '', 'title': 'Recent posts.', 'with_catalog': with_catalog, 'with_date': with_date, } self.render('list/post_list.html', kwd=kwd, view=MPost.query_recent(num=20), postrecs=MPost.query_recent(num=2), format_date=tools.format_date, userinfo=self.userinfo, cfg=CMS_CFG, )
List posts that recent edited.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_list_handler.py#L40-L56
bukun/TorCMS
torcms/handlers/post_list_handler.py
PostListHandler.errcat
def errcat(self): ''' List the posts to be modified. ''' post_recs = MPost.query_random(limit=1000) outrecs = [] errrecs = [] idx = 0 for postinfo in post_recs: if idx > 16: break cat = MPost2Catalog.get_first_category(postinfo.uid) if cat: if 'def_cat_uid' in postinfo.extinfo: if postinfo.extinfo['def_cat_uid'] == cat.tag_id: pass else: errrecs.append(postinfo) idx += 1 else: errrecs.append(postinfo) idx += 1 else: outrecs.append(postinfo) idx += 1 self.render('list/errcat.html', kwd={}, norecs=outrecs, errrecs=errrecs, userinfo=self.userinfo)
python
def errcat(self): ''' List the posts to be modified. ''' post_recs = MPost.query_random(limit=1000) outrecs = [] errrecs = [] idx = 0 for postinfo in post_recs: if idx > 16: break cat = MPost2Catalog.get_first_category(postinfo.uid) if cat: if 'def_cat_uid' in postinfo.extinfo: if postinfo.extinfo['def_cat_uid'] == cat.tag_id: pass else: errrecs.append(postinfo) idx += 1 else: errrecs.append(postinfo) idx += 1 else: outrecs.append(postinfo) idx += 1 self.render('list/errcat.html', kwd={}, norecs=outrecs, errrecs=errrecs, userinfo=self.userinfo)
List the posts to be modified.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_list_handler.py#L58-L87
bukun/TorCMS
torcms/handlers/post_list_handler.py
PostListHandler.refresh
def refresh(self): ''' List the post of dated. ''' kwd = { 'pager': '', 'title': '', } self.render('list/post_list.html', kwd=kwd, userinfo=self.userinfo, view=MPost.query_dated(10), postrecs=MPost.query_dated(10), format_date=tools.format_date, cfg=CMS_CFG)
python
def refresh(self): ''' List the post of dated. ''' kwd = { 'pager': '', 'title': '', } self.render('list/post_list.html', kwd=kwd, userinfo=self.userinfo, view=MPost.query_dated(10), postrecs=MPost.query_dated(10), format_date=tools.format_date, cfg=CMS_CFG)
List the post of dated.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_list_handler.py#L89-L103
bukun/TorCMS
torcms/script/autocrud/base_crud.py
build_dir
def build_dir(): ''' Build the directory used for templates. ''' tag_arr = ['add', 'edit', 'view', 'list', 'infolist'] path_arr = [os.path.join(CRUD_PATH, x) for x in tag_arr] for wpath in path_arr: if os.path.exists(wpath): continue os.makedirs(wpath)
python
def build_dir(): ''' Build the directory used for templates. ''' tag_arr = ['add', 'edit', 'view', 'list', 'infolist'] path_arr = [os.path.join(CRUD_PATH, x) for x in tag_arr] for wpath in path_arr: if os.path.exists(wpath): continue os.makedirs(wpath)
Build the directory used for templates.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/autocrud/base_crud.py#L31-L40
bukun/TorCMS
torcms/model/reply_model.py
MReply.create_reply
def create_reply(post_data): ''' Create the reply. ''' uid = tools.get_uuid() TabReply.create( uid=uid, post_id=post_data['post_id'], user_name=post_data['user_name'], user_id=post_data['user_id'], timestamp=tools.timestamp(), date=datetime.datetime.now(), cnt_md=tornado.escape.xhtml_escape(post_data['cnt_reply']), cnt_html=tools.markdown2html(post_data['cnt_reply']), vote=0 ) return uid
python
def create_reply(post_data): ''' Create the reply. ''' uid = tools.get_uuid() TabReply.create( uid=uid, post_id=post_data['post_id'], user_name=post_data['user_name'], user_id=post_data['user_id'], timestamp=tools.timestamp(), date=datetime.datetime.now(), cnt_md=tornado.escape.xhtml_escape(post_data['cnt_reply']), cnt_html=tools.markdown2html(post_data['cnt_reply']), vote=0 ) return uid
Create the reply.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/reply_model.py#L33-L49
bukun/TorCMS
torcms/model/reply_model.py
MReply.query_by_post
def query_by_post(postid): ''' Get reply list of certain post. ''' return TabReply.select().where( TabReply.post_id == postid ).order_by(TabReply.timestamp.desc())
python
def query_by_post(postid): ''' Get reply list of certain post. ''' return TabReply.select().where( TabReply.post_id == postid ).order_by(TabReply.timestamp.desc())
Get reply list of certain post.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/reply_model.py#L52-L58
bukun/TorCMS
ext_script/autocrud/fetch_html_dic.py
__write_filter_dic
def __write_filter_dic(wk_sheet, column): ''' return filter dic for certain column ''' row1_val = wk_sheet['{0}1'.format(column)].value row2_val = wk_sheet['{0}2'.format(column)].value row3_val = wk_sheet['{0}3'.format(column)].value row4_val = wk_sheet['{0}4'.format(column)].value if row1_val and row1_val.strip() != '': row2_val = row2_val.strip() slug_name = row1_val.strip() c_name = row2_val.strip() tags1 = [x.strip() for x in row3_val.split(',')] tags_dic = {} # if only one tag, if len(tags1) == 1: xx_1 = row2_val.split(':') # 'text' # HTML text input control. if xx_1[0].lower() in INPUT_ARR: xx_1[0] = xx_1[0].lower() else: xx_1[0] = 'text' if len(xx_1) == 2: ctr_type, unit = xx_1 else: ctr_type = xx_1[0] unit = '' tags_dic[1] = unit else: ctr_type = 'select' # HTML selectiom control. for index, tag_val in enumerate(tags1): # the index of tags_dic starts from 1. tags_dic[index + 1] = tag_val.strip() outkey = 'html_{0}'.format(slug_name) outval = { 'en': slug_name, 'zh': c_name, 'dic': tags_dic, 'type': ctr_type, 'display': row4_val, } return (outkey, outval) else: return (None, None)
python
def __write_filter_dic(wk_sheet, column): ''' return filter dic for certain column ''' row1_val = wk_sheet['{0}1'.format(column)].value row2_val = wk_sheet['{0}2'.format(column)].value row3_val = wk_sheet['{0}3'.format(column)].value row4_val = wk_sheet['{0}4'.format(column)].value if row1_val and row1_val.strip() != '': row2_val = row2_val.strip() slug_name = row1_val.strip() c_name = row2_val.strip() tags1 = [x.strip() for x in row3_val.split(',')] tags_dic = {} # if only one tag, if len(tags1) == 1: xx_1 = row2_val.split(':') # 'text' # HTML text input control. if xx_1[0].lower() in INPUT_ARR: xx_1[0] = xx_1[0].lower() else: xx_1[0] = 'text' if len(xx_1) == 2: ctr_type, unit = xx_1 else: ctr_type = xx_1[0] unit = '' tags_dic[1] = unit else: ctr_type = 'select' # HTML selectiom control. for index, tag_val in enumerate(tags1): # the index of tags_dic starts from 1. tags_dic[index + 1] = tag_val.strip() outkey = 'html_{0}'.format(slug_name) outval = { 'en': slug_name, 'zh': c_name, 'dic': tags_dic, 'type': ctr_type, 'display': row4_val, } return (outkey, outval) else: return (None, None)
return filter dic for certain column
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/ext_script/autocrud/fetch_html_dic.py#L17-L67
bukun/TorCMS
torcms/model/wiki_hist_model.py
MWikiHist.get_last
def get_last(postid): ''' Get the last wiki in history. ''' recs = TabWikiHist.select().where( TabWikiHist.wiki_id == postid ).order_by(TabWikiHist.time_update.desc()) return None if recs.count() == 0 else recs.get()
python
def get_last(postid): ''' Get the last wiki in history. ''' recs = TabWikiHist.select().where( TabWikiHist.wiki_id == postid ).order_by(TabWikiHist.time_update.desc()) return None if recs.count() == 0 else recs.get()
Get the last wiki in history.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/wiki_hist_model.py#L11-L19
bukun/TorCMS
torcms/core/privilege.py
is_prived
def is_prived(usr_rule, def_rule): ''' Compare between two role string. ''' for iii in range(4): if def_rule[iii] == '0': continue if usr_rule[iii] >= def_rule[iii]: return True return False
python
def is_prived(usr_rule, def_rule): ''' Compare between two role string. ''' for iii in range(4): if def_rule[iii] == '0': continue if usr_rule[iii] >= def_rule[iii]: return True return False
Compare between two role string.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/core/privilege.py#L10-L20
bukun/TorCMS
torcms/core/privilege.py
auth_view
def auth_view(method): ''' role for view. ''' def wrapper(self, *args, **kwargs): ''' wrapper. ''' if ROLE_CFG['view'] == '': return method(self, *args, **kwargs) elif self.current_user: if is_prived(self.userinfo.role, ROLE_CFG['view']): return method(self, *args, **kwargs) else: kwd = { 'info': 'No role', } self.render('misc/html/404.html', kwd=kwd, userinfo=self.userinfo) else: kwd = { 'info': 'No role', } self.render('misc/html/404.html', kwd=kwd, userinfo=self.userinfo) return wrapper
python
def auth_view(method): ''' role for view. ''' def wrapper(self, *args, **kwargs): ''' wrapper. ''' if ROLE_CFG['view'] == '': return method(self, *args, **kwargs) elif self.current_user: if is_prived(self.userinfo.role, ROLE_CFG['view']): return method(self, *args, **kwargs) else: kwd = { 'info': 'No role', } self.render('misc/html/404.html', kwd=kwd, userinfo=self.userinfo) else: kwd = { 'info': 'No role', } self.render('misc/html/404.html', kwd=kwd, userinfo=self.userinfo) return wrapper
role for view.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/core/privilege.py#L23-L54
bukun/TorCMS
torcms/script/script_drop_tabels.py
run_drop_tables
def run_drop_tables(_): ''' Running the script. ''' print('--') drop_the_table(TabPost) drop_the_table(TabTag) drop_the_table(TabMember) drop_the_table(TabWiki) drop_the_table(TabLink) drop_the_table(TabEntity) drop_the_table(TabPostHist) drop_the_table(TabWikiHist) drop_the_table(TabCollect) drop_the_table(TabPost2Tag) drop_the_table(TabRel) drop_the_table(TabEvaluation) drop_the_table(TabUsage) drop_the_table(TabReply) drop_the_table(TabUser2Reply) drop_the_table(TabRating)
python
def run_drop_tables(_): ''' Running the script. ''' print('--') drop_the_table(TabPost) drop_the_table(TabTag) drop_the_table(TabMember) drop_the_table(TabWiki) drop_the_table(TabLink) drop_the_table(TabEntity) drop_the_table(TabPostHist) drop_the_table(TabWikiHist) drop_the_table(TabCollect) drop_the_table(TabPost2Tag) drop_the_table(TabRel) drop_the_table(TabEvaluation) drop_the_table(TabUsage) drop_the_table(TabReply) drop_the_table(TabUser2Reply) drop_the_table(TabRating)
Running the script.
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/script_drop_tabels.py#L22-L43
shon/httpagentparser
httpagentparser/__init__.py
detect
def detect(agent, fill_none=False): """ fill_none: if name/version is not detected respective key is still added to the result with value None """ result = dict(platform=dict(name=None, version=None)) _suggested_detectors = [] for info_type in detectorshub: detectors = _suggested_detectors or detectorshub[info_type] for detector in detectors: try: detector.detect(agent, result) except Exception as _err: pass if fill_none: for outer_key in ('os', 'browser'): outer_value = result.setdefault(outer_key, dict()) for inner_key in ('name', 'version'): outer_value.setdefault(inner_key, None) return result
python
def detect(agent, fill_none=False): """ fill_none: if name/version is not detected respective key is still added to the result with value None """ result = dict(platform=dict(name=None, version=None)) _suggested_detectors = [] for info_type in detectorshub: detectors = _suggested_detectors or detectorshub[info_type] for detector in detectors: try: detector.detect(agent, result) except Exception as _err: pass if fill_none: for outer_key in ('os', 'browser'): outer_value = result.setdefault(outer_key, dict()) for inner_key in ('name', 'version'): outer_value.setdefault(inner_key, None) return result
fill_none: if name/version is not detected respective key is still added to the result with value None
https://github.com/shon/httpagentparser/blob/c08489408a9b9e67c83eb850d15e108c5270c97f/httpagentparser/__init__.py#L637-L658
shon/httpagentparser
httpagentparser/__init__.py
simple_detect
def simple_detect(agent): """ -> (os, browser) # tuple of strings """ result = detect(agent) os_list = [] if 'flavor' in result: os_list.append(result['flavor']['name']) if 'dist' in result: os_list.append(result['dist']['name']) if 'os' in result: os_list.append(result['os']['name']) os = os_list and " ".join(os_list) or "Unknown OS" os_version = os_list and (result.get('flavor') and result['flavor'].get('version')) or \ (result.get('dist') and result['dist'].get('version')) or (result.get('os') and result['os'].get('version')) or "" browser = 'browser' in result and result['browser'].get('name') or 'Unknown Browser' browser_version = 'browser' in result and result['browser'].get('version') or "" if browser_version: browser = " ".join((browser, browser_version)) if os_version: os = " ".join((os, os_version)) return os, browser
python
def simple_detect(agent): """ -> (os, browser) # tuple of strings """ result = detect(agent) os_list = [] if 'flavor' in result: os_list.append(result['flavor']['name']) if 'dist' in result: os_list.append(result['dist']['name']) if 'os' in result: os_list.append(result['os']['name']) os = os_list and " ".join(os_list) or "Unknown OS" os_version = os_list and (result.get('flavor') and result['flavor'].get('version')) or \ (result.get('dist') and result['dist'].get('version')) or (result.get('os') and result['os'].get('version')) or "" browser = 'browser' in result and result['browser'].get('name') or 'Unknown Browser' browser_version = 'browser' in result and result['browser'].get('version') or "" if browser_version: browser = " ".join((browser, browser_version)) if os_version: os = " ".join((os, os_version)) return os, browser
-> (os, browser) # tuple of strings
https://github.com/shon/httpagentparser/blob/c08489408a9b9e67c83eb850d15e108c5270c97f/httpagentparser/__init__.py#L661-L683
shon/httpagentparser
httpagentparser/__init__.py
DetectorBase.getVersion
def getVersion(self, agent, word): """ => version string /None """ version_markers = self.version_markers if \ isinstance(self.version_markers[0], (list, tuple)) else [self.version_markers] version_part = agent.split(word, 1)[-1] for start, end in version_markers: if version_part.startswith(start) and end in version_part: version = version_part[1:] if end: # end could be empty string version = version.split(end)[0] if not self.allow_space_in_version: version = version.split()[0] return version
python
def getVersion(self, agent, word): """ => version string /None """ version_markers = self.version_markers if \ isinstance(self.version_markers[0], (list, tuple)) else [self.version_markers] version_part = agent.split(word, 1)[-1] for start, end in version_markers: if version_part.startswith(start) and end in version_part: version = version_part[1:] if end: # end could be empty string version = version.split(end)[0] if not self.allow_space_in_version: version = version.split()[0] return version
=> version string /None
https://github.com/shon/httpagentparser/blob/c08489408a9b9e67c83eb850d15e108c5270c97f/httpagentparser/__init__.py#L84-L98
ylogx/universal
universal/builder.py
compile_files
def compile_files(args, mem_test=False): ''' Copiles the files and runs memory tests if needed. PARAM args: list of files passed as CMD args to be compiled. PARAM mem_test: Weither to perform memory test ? ''' for filename in args: if not os.path.isfile(filename): print('The file doesn\'t exits') return build_and_run_file(filename) print("")
python
def compile_files(args, mem_test=False): ''' Copiles the files and runs memory tests if needed. PARAM args: list of files passed as CMD args to be compiled. PARAM mem_test: Weither to perform memory test ? ''' for filename in args: if not os.path.isfile(filename): print('The file doesn\'t exits') return build_and_run_file(filename) print("")
Copiles the files and runs memory tests if needed. PARAM args: list of files passed as CMD args to be compiled. PARAM mem_test: Weither to perform memory test ?
https://github.com/ylogx/universal/blob/1be04c2e828d9f97a94d48bff64031b14c2b8463/universal/builder.py#L41-L53
ylogx/universal
universal/builder.py
build_and_run_file
def build_and_run_file(filename): ''' Builds and runs the filename specified according to the extension PARAM filename: name of file to build and run ''' (directory, name, extension) = get_file_tuple(filename) if extension == 'c': print(" = = = = = = ", YELLOW, "GCC: Compiling " + filename + " file", \ RESET, " = = = = = =\n") compiler = Compiler(filename) out = compiler.compile() if out != 0: print('Error while compiling. Code:', out, 'Please retry.') return out print("") out = compiler.run() return out elif extension == 'cpp': print(" = = = = = = ", YELLOW, "GPP: Compiling " + filename + " file", \ RESET, " = = = = = =\n") compiler = Compiler(filename) out = compiler.compile() if out != 0: print('Error while compiling. Code:', out, 'Please retry.') return out print("") out = compiler.run() return out elif extension == 'py': print(" = = = = = = ", YELLOW, "PYTHON: Executing " + filename + " file", \ RESET, " = = = = = =\n") compiler = Compiler(filename) out = compiler.run() return out elif extension == 'java': command = EXECUTABLE_JAVAC + ' ' + filename perform_system_command(command) command_run = EXECUTABLE_JAVA + ' ' + name test_file = directory + "/" + name + ".input" if os.path.exists(test_file): command_run += " < " + test_file return perform_system_command(command_run) else: print("Language yet not supported") return -1
python
def build_and_run_file(filename): ''' Builds and runs the filename specified according to the extension PARAM filename: name of file to build and run ''' (directory, name, extension) = get_file_tuple(filename) if extension == 'c': print(" = = = = = = ", YELLOW, "GCC: Compiling " + filename + " file", \ RESET, " = = = = = =\n") compiler = Compiler(filename) out = compiler.compile() if out != 0: print('Error while compiling. Code:', out, 'Please retry.') return out print("") out = compiler.run() return out elif extension == 'cpp': print(" = = = = = = ", YELLOW, "GPP: Compiling " + filename + " file", \ RESET, " = = = = = =\n") compiler = Compiler(filename) out = compiler.compile() if out != 0: print('Error while compiling. Code:', out, 'Please retry.') return out print("") out = compiler.run() return out elif extension == 'py': print(" = = = = = = ", YELLOW, "PYTHON: Executing " + filename + " file", \ RESET, " = = = = = =\n") compiler = Compiler(filename) out = compiler.run() return out elif extension == 'java': command = EXECUTABLE_JAVAC + ' ' + filename perform_system_command(command) command_run = EXECUTABLE_JAVA + ' ' + name test_file = directory + "/" + name + ".input" if os.path.exists(test_file): command_run += " < " + test_file return perform_system_command(command_run) else: print("Language yet not supported") return -1
Builds and runs the filename specified according to the extension PARAM filename: name of file to build and run
https://github.com/ylogx/universal/blob/1be04c2e828d9f97a94d48bff64031b14c2b8463/universal/builder.py#L56-L104
ylogx/universal
universal/util.py
check_exec_installed
def check_exec_installed(exec_list): """ Check the required programs are installed. PARAM exec_list: list of programs to check RETURN: True if all installed else False """ all_installed = True for exe in exec_list: if not is_tool(exe): print("Executable: " + exe + " is not installed") all_installed = False return all_installed
python
def check_exec_installed(exec_list): """ Check the required programs are installed. PARAM exec_list: list of programs to check RETURN: True if all installed else False """ all_installed = True for exe in exec_list: if not is_tool(exe): print("Executable: " + exe + " is not installed") all_installed = False return all_installed
Check the required programs are installed. PARAM exec_list: list of programs to check RETURN: True if all installed else False
https://github.com/ylogx/universal/blob/1be04c2e828d9f97a94d48bff64031b14c2b8463/universal/util.py#L23-L34
ylogx/universal
universal/main.py
parse_known_args
def parse_known_args(): """ Parse command line arguments """ parser = ArgumentParser() parser.add_argument("-l", "--loop", type=int, help="Loop every X seconds") parser.add_argument('-V', '--version', action='store_true', dest='version', help='Print the version number and exit') parser.add_argument("-u", "--update", action='store_true', dest="update", help="Update the software from online repo") parser.add_argument("-p", "--problem", action='store_true', dest="problem", help="Report a problem") parser.add_argument("-m", "--memory", action='store_true', dest="memory", help="Run memory tests") args, otherthings = parser.parse_known_args() return args, otherthings, parser
python
def parse_known_args(): """ Parse command line arguments """ parser = ArgumentParser() parser.add_argument("-l", "--loop", type=int, help="Loop every X seconds") parser.add_argument('-V', '--version', action='store_true', dest='version', help='Print the version number and exit') parser.add_argument("-u", "--update", action='store_true', dest="update", help="Update the software from online repo") parser.add_argument("-p", "--problem", action='store_true', dest="problem", help="Report a problem") parser.add_argument("-m", "--memory", action='store_true', dest="memory", help="Run memory tests") args, otherthings = parser.parse_known_args() return args, otherthings, parser
Parse command line arguments
https://github.com/ylogx/universal/blob/1be04c2e828d9f97a94d48bff64031b14c2b8463/universal/main.py#L43-L65
xieqihui/pandas-multiprocess
pandas_multiprocess/multiprocess.py
multi_process
def multi_process(func, data, num_process=None, verbose=True, **args): '''Function to use multiprocessing to process pandas Dataframe. This function applies a function on each row of the input DataFrame by multiprocessing. Args: func (function): The function to apply on each row of the input Dataframe. The func must accept pandas.Series as the first positional argument and return a pandas.Series. data (pandas.DataFrame): A DataFrame to be processed. num_process (int, optional): The number of processes to run in parallel. Defaults to be the number of CPUs of the computer. verbose (bool, optional): Set to False to disable verbose output. args (dict): Keyword arguments to pass as keywords arguments to `func` return: A dataframe containing the results ''' # Check arguments value assert isinstance(data, pd.DataFrame), \ 'Input data must be a pandas.DataFrame instance' if num_process is None: num_process = multiprocessing.cpu_count() # Establish communication queues tasks = multiprocessing.JoinableQueue() results = multiprocessing.Queue() error_queue = multiprocessing.Queue() start_time = time.time() # Enqueue tasks num_task = len(data) for i in range(num_task): tasks.put(data.iloc[i, :]) # Add a poison pill for each consumer for i in range(num_process): tasks.put(None) logger.info('Create {} processes'.format(num_process)) consumers = [Consumer(func, tasks, results, error_queue, **args) for i in range(num_process)] for w in consumers: w.start() # Add a task tracking process task_tracker = TaskTracker(tasks, verbose) task_tracker.start() # Wait for all input data to be processed tasks.join() # If there is any error in any process, output the error messages num_error = error_queue.qsize() if num_error > 0: for i in range(num_error): logger.error(error_queue.get()) raise RuntimeError('Multi process jobs failed') else: # Collect results result_table = [] while num_task: result_table.append(results.get()) num_task -= 1 df_results = pd.DataFrame(result_table) logger.info("Jobs finished in {0:.2f}s".format( time.time()-start_time)) return df_results
python
def multi_process(func, data, num_process=None, verbose=True, **args): '''Function to use multiprocessing to process pandas Dataframe. This function applies a function on each row of the input DataFrame by multiprocessing. Args: func (function): The function to apply on each row of the input Dataframe. The func must accept pandas.Series as the first positional argument and return a pandas.Series. data (pandas.DataFrame): A DataFrame to be processed. num_process (int, optional): The number of processes to run in parallel. Defaults to be the number of CPUs of the computer. verbose (bool, optional): Set to False to disable verbose output. args (dict): Keyword arguments to pass as keywords arguments to `func` return: A dataframe containing the results ''' # Check arguments value assert isinstance(data, pd.DataFrame), \ 'Input data must be a pandas.DataFrame instance' if num_process is None: num_process = multiprocessing.cpu_count() # Establish communication queues tasks = multiprocessing.JoinableQueue() results = multiprocessing.Queue() error_queue = multiprocessing.Queue() start_time = time.time() # Enqueue tasks num_task = len(data) for i in range(num_task): tasks.put(data.iloc[i, :]) # Add a poison pill for each consumer for i in range(num_process): tasks.put(None) logger.info('Create {} processes'.format(num_process)) consumers = [Consumer(func, tasks, results, error_queue, **args) for i in range(num_process)] for w in consumers: w.start() # Add a task tracking process task_tracker = TaskTracker(tasks, verbose) task_tracker.start() # Wait for all input data to be processed tasks.join() # If there is any error in any process, output the error messages num_error = error_queue.qsize() if num_error > 0: for i in range(num_error): logger.error(error_queue.get()) raise RuntimeError('Multi process jobs failed') else: # Collect results result_table = [] while num_task: result_table.append(results.get()) num_task -= 1 df_results = pd.DataFrame(result_table) logger.info("Jobs finished in {0:.2f}s".format( time.time()-start_time)) return df_results
Function to use multiprocessing to process pandas Dataframe. This function applies a function on each row of the input DataFrame by multiprocessing. Args: func (function): The function to apply on each row of the input Dataframe. The func must accept pandas.Series as the first positional argument and return a pandas.Series. data (pandas.DataFrame): A DataFrame to be processed. num_process (int, optional): The number of processes to run in parallel. Defaults to be the number of CPUs of the computer. verbose (bool, optional): Set to False to disable verbose output. args (dict): Keyword arguments to pass as keywords arguments to `func` return: A dataframe containing the results
https://github.com/xieqihui/pandas-multiprocess/blob/b4d1b7357a446ded93183fb7b3e0d464ac7cc784/pandas_multiprocess/multiprocess.py#L125-L186
xieqihui/pandas-multiprocess
pandas_multiprocess/multiprocess.py
Consumer.run
def run(self): '''Define the job of each process to run. ''' while True: next_task = self._task_queue.get() # If there is any error, only consume data but not run the job if self._error_queue.qsize() > 0: self._task_queue.task_done() continue if next_task is None: # Poison pill means shutdown self._task_queue.task_done() break try: answer = self._func(next_task, **self._args) self._task_queue.task_done() self._result_queue.put(answer) except Exception as e: self._task_queue.task_done() self._error_queue.put((os.getpid(), e)) logger.error(e) continue
python
def run(self): '''Define the job of each process to run. ''' while True: next_task = self._task_queue.get() # If there is any error, only consume data but not run the job if self._error_queue.qsize() > 0: self._task_queue.task_done() continue if next_task is None: # Poison pill means shutdown self._task_queue.task_done() break try: answer = self._func(next_task, **self._args) self._task_queue.task_done() self._result_queue.put(answer) except Exception as e: self._task_queue.task_done() self._error_queue.put((os.getpid(), e)) logger.error(e) continue
Define the job of each process to run.
https://github.com/xieqihui/pandas-multiprocess/blob/b4d1b7357a446ded93183fb7b3e0d464ac7cc784/pandas_multiprocess/multiprocess.py#L57-L78
xieqihui/pandas-multiprocess
pandas_multiprocess/multiprocess.py
TaskTracker.run
def run(self): '''Define the job of each process to run. ''' if self.verbose: pbar = tqdm(total=100) while True: task_remain = self._task_queue.qsize() task_finished = int((float(self.total_task - task_remain) / float(self.total_task)) * 100) if task_finished % 20 == 0 and task_finished != self.current_state: self.current_state = task_finished logger.info('{0}% done'.format(task_finished)) if self.verbose and task_finished > 0: pbar.update(20) if task_remain == 0: break logger.debug('All task data cleared')
python
def run(self): '''Define the job of each process to run. ''' if self.verbose: pbar = tqdm(total=100) while True: task_remain = self._task_queue.qsize() task_finished = int((float(self.total_task - task_remain) / float(self.total_task)) * 100) if task_finished % 20 == 0 and task_finished != self.current_state: self.current_state = task_finished logger.info('{0}% done'.format(task_finished)) if self.verbose and task_finished > 0: pbar.update(20) if task_remain == 0: break logger.debug('All task data cleared')
Define the job of each process to run.
https://github.com/xieqihui/pandas-multiprocess/blob/b4d1b7357a446ded93183fb7b3e0d464ac7cc784/pandas_multiprocess/multiprocess.py#L106-L122
xieqihui/pandas-multiprocess
examples/example.py
func
def func(data_row, wait): ''' A sample function It takes 'wait' seconds to calculate the sum of each row ''' time.sleep(wait) data_row['sum'] = data_row['col_1'] + data_row['col_2'] return data_row
python
def func(data_row, wait): ''' A sample function It takes 'wait' seconds to calculate the sum of each row ''' time.sleep(wait) data_row['sum'] = data_row['col_1'] + data_row['col_2'] return data_row
A sample function It takes 'wait' seconds to calculate the sum of each row
https://github.com/xieqihui/pandas-multiprocess/blob/b4d1b7357a446ded93183fb7b3e0d464ac7cc784/examples/example.py#L7-L13
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
me
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)
python
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)
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.
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L39-L114
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
mae
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))
python
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))
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
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L117-L193
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
mle
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)
python
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)
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.
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L271-L348
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
mde
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)
python
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)
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.
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L511-L582
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
mdae
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))
python
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))
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.
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L585-L656
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
ed
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)
python
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)
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.
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L733-L805
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
ned
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)
python
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)
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.
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L808-L883
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
nrmse_range
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)
python
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)
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.
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L1044-L1121
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
nrmse_mean
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
python
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
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.
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L1124-L1200
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
nrmse_iqr
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
python
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
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.
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L1203-L1282
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
mase
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)
python
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)
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.
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L1372-L1450
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
maape
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))
python
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))
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.
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L1937-L2010
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
drel
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))
python
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))
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.
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L2425-L2499
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
watt_m
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))
python
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))
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.
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L2593-L2668
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
kge_2009
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
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): """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
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.
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L3023-L3151
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
sa
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)
python
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)
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.
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L3538-L3612
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
sc
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)
python
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)
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.
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L3615-L3691
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
sid
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)
python
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)
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.
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L3694-L3770
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
sga
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)
python
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)
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.
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L3773-L3850
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
h1_mhe
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)
python
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)
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.
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L3858-L3930
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
h6_mahe
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))
python
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))
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.
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L5110-L5189