code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if not dtime:
dtime = datetime.now()
if not isinstance(dtime, datetime):
raise TypeError('dtime should be datetime, but we got {}'.format(type(dtime)))
return time.mktime(dtime.timetuple()) | def transform_datetime_to_unix(dtime=None) | 将 datetime 类型转换成 unix 时间戳
:param:
* dtime: (datetime) datetime 类型实例,默认为当前时间
:return:
* data_type: (datetime) datetime 类型实例
举例如下::
print('--- transform_datetime_to_unix demo ---')
dtime = datetime.datetime.now()
ans_time = transform_datetime_to_unix(dtime)
p... | 2.472938 | 3.241449 | 0.762911 |
now = datetime.now()
this_month_start = now.replace(
day=1, hour=0, minute=0, second=0, microsecond=0)
this_month_days = calendar.monthrange(now.year, now.month)
random_seconds = random.randint(0, this_month_days[1]*A_DAY_SECONDS)
return this_month_start + t... | def date_time_this_month() | 获取当前月的随机时间
:return:
* date_this_month: (datetime) 当前月份的随机时间
举例如下::
print('--- GetRandomTime.date_time_this_month demo ---')
print(GetRandomTime.date_time_this_month())
print('---')
执行结果::
--- GetRandomTime.date_time_this_month ... | 2.549463 | 2.621211 | 0.972628 |
now = datetime.now()
this_year_start = now.replace(
month=1, day=1, hour=0, minute=0, second=0, microsecond=0)
this_year_days = sum(calendar.mdays)
random_seconds = random.randint(0, this_year_days*A_DAY_SECONDS)
return this_year_start + timedelta(seconds=ra... | def date_time_this_year() | 获取当前年的随机时间字符串
:return:
* date_this_year: (datetime) 当前月份的随机时间
举例如下::
print('--- GetRandomTime.date_time_this_year demo ---')
print(GetRandomTime.date_time_this_year())
print('---')
执行结果::
--- GetRandomTime.date_time_thi... | 3.11154 | 3.36329 | 0.925148 |
if isinstance(year, int) and len(str(year)) != 4:
raise ValueError("year should be int year like 2018, but we got {}, {}".
format(year, type(year)))
if isinstance(year, str) and len(year) != 4:
raise ValueError("year should be string year lik... | def gen_date_by_year(year) | 获取当前年的随机时间字符串
:param:
* year: (string) 长度为 4 位的年份字符串
:return:
* date_str: (string) 传入年份的随机合法的日期
举例如下::
print('--- GetRandomTime.gen_date_by_year demo ---')
print(GetRandomTime.gen_date_by_year("2010"))
print('---')
... | 2.735556 | 2.49913 | 1.094603 |
if not date_time:
datetime_now = datetime.now()
else:
datetime_now = date_time
if not time_format:
time_format = '%Y/%m/%d %H:%M:%S'
return datetime.strftime(datetime_now, time_format) | def strftime(date_time=None, time_format=None) | 将 datetime 对象转换为 str
:param:
* date_time: (obj) datetime 对象
* time_format: (sting) 日期格式字符串
:return:
* date_time_str: (string) 日期字符串 | 1.904186 | 2.092056 | 0.910198 |
try:
datetime_obj = datetime.strptime(time_str, time_format)
return datetime_obj
except ValueError as ex:
raise ValueError(ex) | def strptime(time_str, time_format) | 将 str 转换为 datetime 对象
:param:
* time_str: (string) 日期字符串
* time_format: (sting) 日期格式字符串
:return:
* datetime_obj: (obj) datetime 对象 | 2.660292 | 2.736398 | 0.972188 |
if os.path.isfile(project_config):
project_config = open(project_config)
try:
yml_data = yaml.load(project_config)
project_name = yml_data['project']
project_tree = yml_data['tree']
except Exception as e:
raise KeyError('project config format Error: {}'.format(e)... | def init_project_by_yml(project_config=None, dist=None) | 通过配置文件初始化一个 project
:param:
* project_config: (string) 用来生成 project 的配置文件
* dist: (string) project 位置
举例如下::
print('--- init_project_by_yml demo ---')
# define yml string
package_yml = '''
project: hellopackage
tree:
... | 3.091022 | 2.862667 | 1.07977 |
try:
cur_path = pathlib.Path.cwd()
abs_filename = cur_path / pathlib.Path(sub_path) / filename
flag = pathlib.Path.is_file(abs_filename)
# 将 path 对象转换成字符串
return flag, str(abs_filename)
except:
flag = False
return flag, None | def get_abs_filename_with_sub_path(sub_path, filename) | 生成当前路径下一级路径某文件的完整文件名;
:param:
* sub_path: (string) 下一级的某路径名称
* filename: (string) 下一级路径的某个文件名
:returns:
* 返回类型 (tuple),有两个值,第一个为 flag,第二个为文件名,说明见下
* flag: (bool) 如果文件存在,返回 True,文件不存在,返回 False
* abs_filename: (string) 指定 filename 的包含路径的长文件名
... | 4.094023 | 3.751352 | 1.091346 |
# 获得当前路径
temp_path = pathlib.Path()
cur_path = temp_path.resolve()
# 生成 带有 sub_path_name 的路径
path = cur_path / pathlib.Path(sub_path)
# 判断是否存在带有 sub_path 路径
if path.exists():
# 返回 True: 路径存在, False: 不需要创建
return True, False
else:
path.mkdir(parents=True)
... | def check_sub_path_create(sub_path) | 检查当前路径下的某个子路径是否存在, 不存在则创建;
:param:
* sub_path: (string) 下一级的某路径名称
:return:
* 返回类型 (tuple),有两个值
* True: 路径存在,False: 不需要创建
* False: 路径不存在,True: 创建成功
举例如下::
print('--- check_sub_path_create demo ---')
# 定义子路径名称
sub_path = 'demo_sub_dir'
... | 4.657884 | 3.839832 | 1.213044 |
# 判断长度,如果不是 17 位,直接返回失败
if len(id_number_str) != 17:
return False, -1
id_regex = '[1-9][0-9]{14}([0-9]{2}[0-9X])?'
if not re.match(id_regex, id_number_str):
return False, -1
items = [int(item) for item in id_number_str]
# 加权因子表
... | def get_checkcode(cls, id_number_str) | 计算身份证号码的校验位;
:param:
* id_number_str: (string) 身份证号的前17位,比如 3201241987010100
:returns:
* 返回类型 (tuple)
* flag: (bool) 如果身份证号格式正确,返回 True;格式错误,返回 False
* checkcode: 计算身份证前17位的校验码
举例如下::
from fishbase.fish_data import *
pri... | 2.305424 | 2.22068 | 1.038161 |
if isinstance(id_number, int):
id_number = str(id_number)
# 调用函数计算身份证前面17位的 checkcode
result = IdCard.get_checkcode(id_number[0:17])
# 返回第一个 flag 是错误的话,表示身份证格式错误,直接透传返回,第二个为获得的校验码
flag = result[0]
checkcode = result[1]
if not flag:
... | def check_number(cls, id_number) | 检查身份证号码是否符合校验规则;
:param:
* id_number: (string) 身份证号,比如 32012419870101001
:returns:
* 返回类型 (tuple),当前有一个值,第一个为 flag,以后第二个值会返回具体校验不通过的详细错误
* flag: (bool) 如果身份证号码校验通过,返回 True;如果身份证校验不通过,返回 False
举例如下::
from fishbase.fish_data import *
... | 6.212594 | 5.960371 | 1.042317 |
values = []
if match_type == 'EXACT':
values = sqlite_query('fish_data.sqlite',
'select zone, areanote from cn_idcard where areanote = :area', {"area": area_str})
if match_type == 'FUZZY':
values = sqlite_query('fish_data.sqlite... | def get_zone_info(cls, area_str, match_type='EXACT', result_type='LIST') | 输入包含省份、城市、地区信息的内容,返回地区编号;
:param:
* area_str: (string) 要查询的区域,省份、城市、地区信息,比如 北京市
* match_type: (string) 查询匹配模式,默认值 'EXACT',表示精确匹配,可选 'FUZZY',表示模糊查询
* result_type: (string) 返回结果数量类型,默认值 'LIST',表示返回列表,可选 'SINGLE_STR',返回结果的第一个地区编号字符串
:returns:
* 返回类型 根据 resu... | 3.822183 | 3.112392 | 1.228053 |
total = 0
even = True
for item in card_number_str[-1::-1]:
item = int(item)
if even:
item <<= 1
if item > 9:
item -= 9
total += item
even = not even
checkcode = (10 - (total % 10)) % 10... | def get_checkcode(cls, card_number_str) | 计算银行卡校验位;
:param:
* card_number_str: (string) 要查询的银行卡号
:returns:
checkcode: (string) 银行卡的校验位
举例如下::
from fishbase.fish_data import *
print('--- fish_data get_checkcode demo ---')
# 不能放真的卡信息,有风险
print(CardBin.get_checkco... | 2.798734 | 3.586907 | 0.780264 |
if isinstance(card_number_str, int):
card_number_str = str(card_number_str)
checkcode = card_number_str[-1]
result = CardBin.get_checkcode(card_number_str[0:-1])
return checkcode == result | def check_bankcard(cls, card_number_str) | 检查银行卡校验位是否正确;
:param:
* card_number_str: (string) 要查询的银行卡号
:returns:
返回结果:(bool) True or False
举例如下::
from fishbase.fish_data import *
print('--- fish_data check_bankcard demo ---')
# 不能放真的卡信息,有风险
print(CardBin.check_ba... | 3.188143 | 3.057638 | 1.042682 |
flag = False
# 检查文件是否存在
if not pathlib.Path(conf_filename).is_file():
return flag,
# 判断是否对大小写敏感
cf = configparser.ConfigParser() if not case_sensitive else MyConfigParser()
# 读入 config 文件
try:
if sys.version > '3':
cf.read(conf_filename, encodi... | def conf_as_dict(conf_filename, encoding=None, case_sensitive=False) | 读入 ini 配置文件,返回根据配置文件内容生成的字典类型变量;
:param:
* conf_filename: (string) 需要读入的 ini 配置文件长文件名
* encoding: (string) 文件编码
* case_sensitive: (bool) 是否大小写敏感,默认为 False
:return:
* flag: (bool) 读取配置文件是否正确,正确返回 True,错误返回 False
* d: (dict) 如果读取配置文件正确返回的包含配置文件内容的字典,字典内容顺序与配置文件顺序保持一致
... | 3.298531 | 3.301706 | 0.999038 |
obj_dict = {'__classname__': type(obj).__name__}
obj_dict.update(obj.__dict__)
for key, value in obj_dict.items():
if not isinstance(value, commonDataType):
sub_dict = serialize_instance(value)
obj_dict.update({key: sub_dict})
else:
continue
retur... | def serialize_instance(obj) | 对象序列化
:param:
* obj: (object) 对象实例
:return:
* obj_dict: (dict) 对象序列化字典
举例如下::
print('--- serialize_instance demo ---')
# 定义两个对象
class Obj(object):
def __init__(self, a, b):
self.a = a
self.b = b
class ObjB(objec... | 3.095309 | 3.138893 | 0.986115 |
if kind == udTime:
return str(uuid.uuid1())
elif kind == udRandom:
return str(uuid.uuid4())
else:
return str(uuid.uuid4()) | def get_uuid(kind) | 获得不重复的 uuid,可以是包含时间戳的 uuid,也可以是完全随机的;基于 Python 的 uuid 类进行封装和扩展;
支持 get_time_uuid() 这样的写法,不需要参数,也可以表示生成包含时间戳的 uuid,兼容 v1.0.12 以及之前版本;
:param:
* kind: (int) uuid 类型,整形常量 udTime 表示基于时间戳, udRandom 表示完全随机
:return:
* result: (string) 返回类似 66b438e3-200d-4fe3-8c9e-2bc431bb3000 的 uuid
举例如下::
... | 4.143817 | 2.377209 | 1.743144 |
if isinstance(source, dict):
check_list = list(source.values())
elif isinstance(source, list) or isinstance(source, tuple):
check_list = list(source)
else:
raise TypeError('source except list, tuple or dict, but got {}'.format(type(source)))
for i in check_list:
if i... | def has_space_element(source) | 判断对象中的元素,如果存在 None 或空字符串,则返回 True, 否则返回 False, 支持字典、列表和元组
:param:
* source: (list, set, dict) 需要检查的对象
:return:
* result: (bool) 存在 None 或空字符串或空格字符串返回 True, 否则返回 False
举例如下::
print('--- has_space_element demo---')
print(has_space_element([1, 2, 'test_str']))
print(... | 3.080719 | 2.831915 | 1.087857 |
key_list = left_json.keys()
if op == 'strict':
for key in key_list:
if not right_json.get(key) == left_json.get(key):
return False
return True | def if_json_contain(left_json, right_json, op='strict') | 判断一个 json 是否包含另外一个 json 的 key,并且 value 相等;
:param:
* left_json: (dict) 需要判断的 json,我们称之为 left
* right_json: (dict) 需要判断的 json,我们称之为 right,目前是判断 left 是否包含在 right 中
* op: (string) 判断操作符,目前只有一种,默认为 strict,向后兼容
:return:
* result: (bool) right json 包含 left json 的 key,并且 value 一样,返回 Tr... | 2.314888 | 2.919967 | 0.792779 |
od = OrderedDict(sorted(dic.items()))
url = '?'
temp_str = urlencode(od)
url = url + temp_str
return url | def join_url_params(dic) | 根据传入的键值对,拼接 url 后面 ? 的参数,比如 ?key1=value1&key2=value2
:param:
* dic: (dict) 参数键值对
:return:
* result: (string) 拼接好的参数
举例如下::
print('--- splice_url_params demo ---')
dic1 = {'key1': 'value1', 'key2': 'value2'}
print(splice_url_params(dic1))
print('---')
执... | 4.934962 | 9.936209 | 0.496664 |
o_list = sorted(value for (key, value) in p_dict.items())
if order == odASC:
return o_list
elif order == odDES:
return o_list[::-1] | def sorted_list_from_dict(p_dict, order=odASC) | 根据字典的 value 进行排序,并以列表形式返回
:param:
* p_dict: (dict) 需要排序的字典
* order: (int) 排序规则,odASC 升序,odDES 降序,默认为升序
:return:
* o_list: (list) 排序后的 list
举例如下::
print('--- sorted_list_from_dict demo ---')
# 定义待处理字典
dict1 = {'a_key': 'a_value', '1_key': '1_value', 'A_key':... | 2.639653 | 4.336557 | 0.608698 |
if check_style == charChinese:
check_pattern = re.compile(u'[\u4e00-\u9fa5]+')
elif check_style == charNum:
check_pattern = re.compile(u'[0-9]+')
else:
return False
try:
if check_pattern.search(p_str):
return True
else:
return Fal... | def has_special_char(p_str, check_style=charChinese) | 检查字符串是否含有指定类型字符
:param:
* p_str: (string) 需要判断的字符串
* check_style: (string) 需要判断的字符类型,默认为 charChinese (编码仅支持utf-8), 支持 charNum,该参数向后兼容
:return:
* True 含有指定类型字符
* False 不含有指定类型字符
举例如下::
print('--- has_special_char demo ---')
p_str1 = 'meiyouzhongwen'
... | 1.968083 | 2.181391 | 0.902214 |
files_list = []
for root, dirs, files in os.walk(path):
for name in files:
files_list.append(os.path.join(root, name))
if exts is not None:
return [file for file in files_list if pathlib.Path(file).suffix in exts]
return files_list | def find_files(path, exts=None) | 查找路径下的文件,返回指定类型的文件列表
:param:
* path: (string) 查找路径
* exts: (list) 文件类型列表,默认为空
:return:
* files_list: (list) 文件列表
举例如下::
print('--- find_files demo ---')
path1 = '/root/fishbase_issue'
all_files = find_files(path1)
print(all_files)
exts_file... | 1.934853 | 2.636232 | 0.733946 |
show_deprecation_warn('get_random_str', 'fish_random.gen_random_str')
from fishbase.fish_random import gen_random_str
return gen_random_str(length, length, has_letter=letters, has_digit=digits,
has_punctuation=punctuation) | def get_random_str(length, letters=True, digits=False, punctuation=False) | 获得指定长度,不同规则的随机字符串,可以包含数字,字母和标点符号
:param:
* length: (int) 随机字符串的长度
* letters: (bool) 随机字符串是否包含字母,默认包含
* digits: (bool) 随机字符串是否包含数字,默认不包含
* punctuation: (bool) 随机字符串是否包含特殊标点符号,默认不包含
:return:
* random_str: (string) 指定规则的随机字符串
举例如下::
print('--- get_random_str ... | 5.354962 | 5.450026 | 0.982557 |
seen = set()
for item in items:
val = item if key is None else key(item)
if val not in seen:
yield item
seen.add(val) | def get_distinct_elements(items, key=None) | 去除序列中的重复元素,使得剩下的元素仍然保持顺序不变,对于不可哈希的对象,需要指定 key ,说明去重元素
:param:
* items: (list) 需要去重的列表
* key: (hook函数) 指定一个函数,用来将序列中的元素转换成可哈希类型
:return:
* result: (generator) 去重后的结果的生成器
举例如下::
print('--- remove_duplicate_elements demo---')
list_demo = remove_duplicate_elements([1,... | 2.079911 | 3.003526 | 0.69249 |
if len(objs) == 0:
return []
if not hasattr(objs[0], key):
raise AttributeError('{0} object has no attribute {1}'.format(type(objs[0]), key))
result = sorted(objs, key=attrgetter(key), reverse=reverse)
return result | def sort_objs_by_attr(objs, key, reverse=False) | 对原生不支持比较操作的对象根据属性排序
:param:
* objs: (list) 需要排序的对象列表
* key: (string) 需要进行排序的对象属性
* reverse: (bool) 排序结果是否进行反转,默认为 False,不进行反转
:return:
* result: (list) 排序后的对象列表
举例如下::
print('--- sorted_objs_by_attr demo---')
class User(object):
def __init__(... | 2.099205 | 2.584466 | 0.812239 |
url_obj = urlsplit(url)
query_dict = parse_qs(url_obj.query)
return OrderedDict(query_dict) | def get_query_param_from_url(url) | 从 url 中获取 query 参数字典
:param:
* url: (string) 需要获取参数字典的 url
:return:
* query_dict: (dict) query 参数的有序字典,字典的值为 query 值组成的列表
举例如下::
print('--- get_query_param_from_url demo---')
url = 'http://localhost:8811/mytest?page_number=1&page_size=10'
query_dict = get_query_pa... | 3.477975 | 6.938097 | 0.501287 |
if not isinstance(data_list, list):
raise TypeError('data_list should be a list, but we got {}'.format(type(data_list)))
if not isinstance(group_number, int) or not isinstance(group_size, int):
raise TypeError('group_number and group_size should be int, but we got group_number: {0}, '
... | def paging(data_list, group_number=1, group_size=10) | 获取分组列表数据
:param:
* data_list: (list) 需要获取分组的数据列表
* group_number: (int) 分组信息,默认为 1
* group_size: (int) 分组大小,默认为 10
:return:
* group_data: (list) 分组数据
举例如下::
print('--- paging demo---')
all_records = [1, 2, 3, 4, 5]
print(get_group_list_data(all_reco... | 1.555727 | 1.675239 | 0.928659 |
if not isinstance(data_dict, dict):
raise TypeError('data_dict should be dict, but we got {}'.format(type(data_dict)))
if not isinstance(key_list, list):
raise TypeError('key_list should be list, but we got {}'.format(type(key_list)))
sub_dict = dict()
for item in key_list... | def get_sub_dict(data_dict, key_list, default_value='default_value') | 从字典中提取子集
:param:
* data_dict: (dict) 需要提取子集的字典
* key_list: (list) 需要获取子集的键列表
* default_value: (string) 当键不存在时的默认值,默认为 default_value
:return:
* sub_dict: (dict) 子集字典
举例如下::
print('--- get_sub_dict demo---')
dict1 = {'a': 1, 'b': 2, 'list1': [1,2,3]}
... | 1.7519 | 1.912913 | 0.915828 |
temp_dict = copy.deepcopy(param_dict)
# 正则
hump_to_underline = re.compile(r'([a-z]|\d)([A-Z])')
for key in list(param_dict.keys()):
# 将驼峰值替换为下划线
underline_sub = re.sub(hump_to_underline, r'\1_\2', key).lower()
temp_dict[underline_sub] = temp_dict.pop(key)
return tem... | def camelcase_to_underline(param_dict) | 将驼峰命名的参数字典键转换为下划线参数
:param:
* param_dict: (dict) 请求参数字典
:return:
* temp_dict: (dict) 转换后的参数字典
举例如下::
print('--- transform_hump_to_underline demo---')
hump_param_dict = {'firstName': 'Python', 'Second_Name': 'san', 'right_name': 'name'}
underline_param_dict = trans... | 2.669169 | 2.792355 | 0.955885 |
Same_info = namedtuple('Same_info', ['item', 'key', 'value'])
same_info = Same_info(set(dict1.items()) & set(dict2.items()),
set(dict1.keys()) & set(dict2.keys()),
set(dict1.values()) & set(dict2.values()))
return same_info | def find_same_between_dicts(dict1, dict2) | 查找两个字典中的相同点,包括键、值、项,仅支持 hashable 对象
:param:
* dict1: (dict) 比较的字典 1
* dict2: (dict) 比较的字典 2
:return:
* dup_info: (namedtuple) 返回两个字典中相同的信息组成的具名元组
举例如下::
print('--- find_same_between_dicts demo---')
dict1 = {'x':1, 'y':2, 'z':3}
dict2 = {'w':10, 'x':1, 'y':... | 2.683362 | 2.357773 | 1.138092 |
if not pathlib.Path(file_path).is_file():
return False, {}, 'File not exist'
try:
if sys.version > '3':
with open(file_path, 'r', encoding=encoding) as f:
d = OrderedDict(yaml.load(f.read()))
return True, d, 'Success'
else:
... | def yaml_conf_as_dict(file_path, encoding=None) | 读入 yaml 配置文件,返回根据配置文件内容生成的字典类型变量
:param:
* file_path: (string) 需要读入的 yaml 配置文件长文件名
* encoding: (string) 文件编码
* msg: (string) 读取配置信息
:return:
* flag: (bool) 读取配置文件是否正确,正确返回 True,错误返回 False
* d: (dict) 如果读取配置文件正确返回的包含配置文件内容的字典,字典内容顺序与配置文件顺序保持一致
举例如下::
print(... | 2.299685 | 2.449943 | 0.938669 |
with open(csv_filename, encoding=encoding) as csv_file:
csv_list = list(csv.reader(csv_file, delimiter=deli))
# 如果设置为要删除空行
if del_blank_row:
csv_list = [s for s in csv_list if len(s) != 0]
return csv_list | def csv2list(csv_filename, deli=',', del_blank_row=True, encoding=None) | 将指定的 csv 文件转换为 list 返回;
:param:
* csv_filename: (string) csv 文件的长文件名
* deli: (string) csv 文件分隔符,默认为逗号
* del_blank_row: (string) 是否要删除空行,默认为删除
* encode: (string) 文件编码
:return:
* csv_list: (list) 转换后的 list
举例如下::
from fishbase.fish_file import *
from ... | 2.226238 | 2.379616 | 0.935545 |
with open(csv_filename, "w") as csv_file:
csv_writer = csv.writer(csv_file)
for data in data_list:
csv_writer.writerow(data)
return csv_filename | def list2csv(data_list, csv_filename='./list2csv.csv') | 将字典写入到指定的 csv 文件,并返回文件的长文件名;
:param:
* data_list: (list) 需要写入 csv 的数据字典
* csv_filename: (string) csv 文件的长文件名
:return:
* csv_filename: (string) csv 文件的长文件名
举例如下::
from fishbase.fish_csv import *
def test_list2csv():
data_list = ['a', 'b', 'c']
... | 1.712846 | 2.32771 | 0.73585 |
with open(csv_filename, encoding=encoding) as csv_file:
if key_is_header:
reader = csv.reader(csv_file, delimiter=deli)
# 读取字典 key
fieldnames = next(reader)
reader = csv.DictReader(csv_file, fieldnames=fieldnames, delimiter=deli)
return [dict... | def csv2dict(csv_filename, deli=',', encoding=None, key_is_header=False) | 将指定的 csv 文件转换为 list 返回;
:param:
* csv_filename: (string) csv 文件的长文件名
* deli: (string) csv 文件分隔符,默认为逗号
* del_blank_row: (string) 是否要删除空行,默认为删除
* encode: (string) 文件编码
:return:
* csv_data: (dict) 读取后的数据
举例如下::
from fishbase.fish_file import *
from fis... | 2.049069 | 2.320434 | 0.883054 |
with open(csv_filename, "w") as csv_file:
csv_writer = csv.writer(csv_file)
if key_is_header:
if isinstance(data_dict, dict):
csv_writer.writerow(list(data_dict.keys()))
csv_writer.writerow(list(data_dict.values()))
elif isinstance(data_d... | def dict2csv(data_dict, csv_filename='./dict2csv.csv', key_is_header=False) | 将字典写入到指定的 csv 文件,并返回文件的长文件名;
:param:
* data_dict: (dict) 需要写入 csv 的数据字典
* csv_filename: (string) csv 文件的长文件名
* key_is_header: (bool) csv 文件第一行是否全为字典 key
:return:
* csv_filename: (string) csv 文件的长文件名
举例如下::
from fishbase.fish_csv import *
def test_dict2csv(... | 1.819627 | 1.914139 | 0.950625 |
next_approvals = self._get_next_approvals().exclude(
status=PENDING).exclude(cloned=True)
for ta in next_approvals:
clone_transition_approval, c = TransitionApproval.objects.get_or_create(
source_state=ta.source_state,
destination_state=ta... | def _cycle_proceedings(self) | Finds next proceedings and clone them for cycling if it exists. | 3.405116 | 3.154807 | 1.079342 |
file_name = request.POST['name']
file_type = request.POST['type']
file_size = int(request.POST['size'])
dest = get_s3direct_destinations().get(
request.POST.get('dest', None), None)
if not dest:
resp = json.dumps({'error': 'File destination does not exist.'})
return Htt... | def get_upload_params(request) | Authorises user and validates given file properties. | 1.881735 | 1.860589 | 1.011365 |
subscription_data = post_data.pop("subscription", {})
# As our database saves the auth and p256dh key in separate field,
# we need to refactor it and insert the auth and p256dh keys in the same dictionary
keys = subscription_data.pop("keys", {})
subscription_data.update(keys)
# Insert the b... | def process_subscription_data(post_data) | Process the subscription data according to out model | 6.35241 | 6.191185 | 1.026041 |
serializer_class = self.get_serializer_class_in()
kwargs['context'] = self.get_serializer_context()
return serializer_class(*args, **kwargs) | def get_serializer_in(self, *args, **kwargs) | Return the serializer instance that should be used for validating and
deserializing input, and for serializing output. | 2.465171 | 2.391225 | 1.030924 |
if user:
backend_name = kwargs['backend'].__class__.__name__.lower()
response = kwargs.get('response', {})
social_thumb = None
if 'facebook' in backend_name:
if 'id' in response:
social_thumb = (
'http://graph.facebook.com/{0}/pict... | def save_avatar(strategy, details, user=None, *args, **kwargs) | Get user avatar from social provider. | 2.359428 | 2.295348 | 1.027917 |
def load(rect=None, flags=None):
return filename, rect, flags
return load | def default_image_loader(filename, flags, **kwargs) | This default image loader just returns filename, rect, and any flags | 11.816803 | 5.882901 | 2.008669 |
flags = TileFlags(
raw_gid & GID_TRANS_FLIPX == GID_TRANS_FLIPX,
raw_gid & GID_TRANS_FLIPY == GID_TRANS_FLIPY,
raw_gid & GID_TRANS_ROT == GID_TRANS_ROT)
gid = raw_gid & ~(GID_TRANS_FLIPX | GID_TRANS_FLIPY | GID_TRANS_ROT)
return gid, flags | def decode_gid(raw_gid) | Decode a GID from TMX data
as of 0.7.0 it determines if the tile should be flipped when rendered
as of 0.8.0 bit 30 determines if GID is rotated
:param raw_gid: 32-bit number from TMX layer data
:return: gid, flags | 2.497246 | 2.201823 | 1.134172 |
# handle "1" and "0"
try:
return bool(int(text))
except:
pass
text = str(text).lower()
if text == "true":
return True
if text == "yes":
return True
if text == "false":
return False
if text == "no":
return False
raise ValueError | def convert_to_bool(text) | Convert a few common variations of "true" and "false" to boolean
:param text: string to test
:return: boolean
:raises: ValueError | 2.36236 | 2.582594 | 0.914724 |
d = dict()
for child in node.findall('properties'):
for subnode in child.findall('property'):
cls = None
try:
if "type" in subnode.keys():
module = importlib.import_module('builtins')
cls = getattr(module, subnode.get("... | def parse_properties(node) | Parse a Tiled xml node and return a dict that represents a tiled "property"
:param node: etree element
:return: dict | 4.113509 | 4.239068 | 0.970381 |
self._cast_and_set_attributes_from_node_items(node.items())
properties = parse_properties(node)
if (not self.allow_duplicate_names and
self._contains_invalid_property_name(properties.items())):
self._log_property_error_message()
raise ValueError("... | def _set_properties(self, node) | Create dict containing Tiled object attributes from xml data
read the xml attributes and tiled "properties" from a xml node and fill
in the values into the object's dictionary. Names will be checked to
make sure that they do not conflict with reserved names.
:param node: etree element... | 9.197065 | 9.436881 | 0.974587 |
self._set_properties(node)
self.background_color = node.get('backgroundcolor',
self.background_color)
# *** do not change this load order! *** #
# *** gid mapping errors will occur if changed *** #
for subno... | def parse_xml(self, node) | Parse a map from ElementTree xml node
:param node: ElementTree xml node
:return: self | 6.007519 | 5.977413 | 1.005037 |
self.images = [None] * self.maxgid
# iterate through tilesets to get source images
for ts in self.tilesets:
# skip tilesets without a source
if ts.source is None:
continue
path = os.path.join(os.path.dirname(self.filename), ts.sourc... | def reload_images(self) | Load the map images from disk
This method will use the image loader passed in the constructor
to do the loading or will use a generic default, in which case no
images will be loaded.
:return: None | 3.350155 | 3.328912 | 1.006381 |
try:
assert (x >= 0 and y >= 0)
except AssertionError:
raise ValueError
try:
layer = self.layers[layer]
except IndexError:
raise ValueError
assert (isinstance(layer, TiledTileLayer))
try:
gid = layer.... | def get_tile_image(self, x, y, layer) | Return the tile image for this location
:param x: x coordinate
:param y: y coordinate
:param layer: layer number
:rtype: surface if found, otherwise 0 | 3.373045 | 3.537508 | 0.953509 |
try:
assert (int(gid) >= 0)
return self.images[gid]
except TypeError:
msg = "GIDs must be expressed as a number. Got: {0}"
logger.debug(msg.format(gid))
raise TypeError
except (AssertionError, IndexError):
msg = "C... | def get_tile_image_by_gid(self, gid) | Return the tile image for this location
:param gid: GID of image
:rtype: surface if found, otherwise ValueError | 4.438398 | 4.356389 | 1.018825 |
try:
assert (x >= 0 and y >= 0 and layer >= 0)
except AssertionError:
raise ValueError
try:
return self.layers[int(layer)].data[int(y)][int(x)]
except (IndexError, ValueError):
msg = "Coords: ({0},{1}) in layer {2} is invalid"
... | def get_tile_gid(self, x, y, layer) | Return the tile image GID for this location
:param x: x coordinate
:param y: y coordinate
:param layer: layer number
:rtype: surface if found, otherwise ValueError | 3.32155 | 3.241972 | 1.024546 |
try:
assert (x >= 0 and y >= 0 and layer >= 0)
except AssertionError:
raise ValueError
try:
gid = self.layers[int(layer)].data[int(y)][int(x)]
except (IndexError, ValueError):
msg = "Coords: ({0},{1}) in layer {2} is invalid."
... | def get_tile_properties(self, x, y, layer) | Return the tile image GID for this location
:param x: x coordinate
:param y: y coordinate
:param layer: layer number
:rtype: python dict if found, otherwise None | 2.576244 | 2.536347 | 1.01573 |
for l in self.visible_tile_layers:
for x, y, _gid in [i for i in self.layers[l].iter_data() if i[2] == gid]:
yield x, y, l | def get_tile_locations_by_gid(self, gid) | Search map for tile locations by the GID
Return (int, int, int) tuples, where the layer is index of
the visible tile layers.
Note: Not a fast operation. Cache results if used often.
:param gid: GID to be searched for
:rtype: generator of tile locations | 6.045205 | 4.741643 | 1.274918 |
try:
assert (int(layer) >= 0)
layer = int(layer)
except (TypeError, AssertionError):
msg = "Layer must be a positive integer. Got {0} instead."
logger.debug(msg.format(type(layer)))
raise ValueError
p = product(range(self.wid... | def get_tile_properties_by_layer(self, layer) | Get the tile properties of each GID in layer
:param layer: layer number
:rtype: iterator of (gid, properties) tuples | 3.750311 | 3.340326 | 1.122738 |
assert (
isinstance(layer,
(TiledTileLayer, TiledImageLayer, TiledObjectGroup)))
self.layers.append(layer)
self.layernames[layer.name] = layer | def add_layer(self, layer) | Add a layer (TileTileLayer, TiledImageLayer, or TiledObjectGroup)
:param layer: TileTileLayer, TiledImageLayer, TiledObjectGroup object | 5.930941 | 4.418844 | 1.342193 |
assert (isinstance(tileset, TiledTileset))
self.tilesets.append(tileset) | def add_tileset(self, tileset) | Add a tileset to the map
:param tileset: TiledTileset | 3.989005 | 4.253142 | 0.937896 |
try:
return self.layernames[name]
except KeyError:
msg = 'Layer "{0}" not found.'
logger.debug(msg.format(name))
raise ValueError | def get_layer_by_name(self, name) | Return a layer by name
:param name: Name of layer. Case-sensitive.
:rtype: Layer object if found, otherwise ValueError | 3.83354 | 4.079787 | 0.939642 |
for obj in self.objects:
if obj.name == name:
return obj
raise ValueError | def get_object_by_name(self, name) | Find an object
:param name: Name of object. Case-sensitive.
:rtype: Object if found, otherwise ValueError | 3.218561 | 3.721415 | 0.864875 |
try:
tiled_gid = self.tiledgidmap[gid]
except KeyError:
raise ValueError
for tileset in sorted(self.tilesets, key=attrgetter('firstgid'),
reverse=True):
if tiled_gid >= tileset.firstgid:
return tileset
... | def get_tileset_from_gid(self, gid) | Return tileset that owns the gid
Note: this is a slow operation, so if you are expecting to do this
often, it would be worthwhile to cache the results of this.
:param gid: gid of tile image
:rtype: TiledTileset if found, otherwise ValueError | 3.132208 | 2.911934 | 1.075645 |
return (i for (i, l) in enumerate(self.layers)
if l.visible and isinstance(l, TiledTileLayer)) | def visible_tile_layers(self) | Return iterator of layer indexes that are set 'visible'
:rtype: Iterator | 5.568382 | 5.558255 | 1.001822 |
return (i for (i, l) in enumerate(self.layers)
if l.visible and isinstance(l, TiledObjectGroup)) | def visible_object_groups(self) | Return iterator of object group indexes that are set 'visible'
:rtype: Iterator | 7.805793 | 8.557364 | 0.912173 |
if flags is None:
flags = TileFlags(0, 0, 0)
if tiled_gid:
try:
return self.imagemap[(tiled_gid, flags)][0]
except KeyError:
gid = self.maxgid
self.maxgid += 1
self.imagemap[(tiled_gid, flags)] ... | def register_gid(self, tiled_gid, flags=None) | Used to manage the mapping of GIDs between the tmx and pytmx
:param tiled_gid: GID that is found in TMX data
:rtype: GID that pytmx uses for the the GID passed | 2.755623 | 2.961443 | 0.9305 |
try:
return self.gidmap[int(tiled_gid)]
except KeyError:
return None
except TypeError:
msg = "GIDs must be an integer"
logger.debug(msg)
raise TypeError | def map_gid(self, tiled_gid) | Used to lookup a GID read from a TMX file's data
:param tiled_gid: GID that is found in TMX data
:rtype: (GID, flags) for the the GID passed, None if not found | 3.916343 | 3.852794 | 1.016494 |
tiled_gid = int(tiled_gid)
# gidmap is a default dict, so cannot trust to raise KeyError
if tiled_gid in self.gidmap:
return self.gidmap[tiled_gid]
else:
gid = self.register_gid(tiled_gid)
return [(gid, None)] | def map_gid2(self, tiled_gid) | WIP. need to refactor the gid code
:param tiled_gid:
:return: | 4.975224 | 5.171481 | 0.96205 |
import os
# if true, then node references an external tileset
source = node.get('source', None)
if source:
if source[-4:].lower() == ".tsx":
# external tilesets don't save this, store it for later
self.firstgid = int(node.get('firstg... | def parse_xml(self, node) | Parse a Tileset from ElementTree xml element
A bit of mangling is done here so that tilesets that have external
TSX files appear the same as those that don't
:param node: ElementTree element
:return: self | 3.154699 | 3.065808 | 1.028994 |
for y, row in enumerate(self.data):
for x, gid in enumerate(row):
yield x, y, gid | def iter_data(self) | Iterate over layer data
Yields X, Y, GID tuples for each tile in the layer
:return: Generator | 5.167369 | 4.266212 | 1.211231 |
images = self.parent.images
for x, y, gid in [i for i in self.iter_data() if i[2]]:
yield x, y, images[gid] | def tiles(self) | Iterate over tile images of this layer
This is an optimised generator function that returns
(tile_x, tile_y, tile_image) tuples,
:rtype: Generator
:return: (x, y, image) tuples | 7.223264 | 7.157826 | 1.009142 |
import struct
import array
self._set_properties(node)
data = None
next_gid = None
data_node = node.find('data')
encoding = data_node.get('encoding', None)
if encoding == 'base64':
from base64 import b64decode
data = b64d... | def parse_xml(self, node) | Parse a Tile Layer from ElementTree xml node
:param node: ElementTree xml node
:return: self | 3.50455 | 3.349222 | 1.046377 |
self._set_properties(node)
self.extend(TiledObject(self.parent, child)
for child in node.findall('object'))
return self | def parse_xml(self, node) | Parse an Object Group from ElementTree xml node
:param node: ElementTree xml node
:return: self | 9.309883 | 9.609859 | 0.968785 |
def read_points(text):
return tuple(tuple(map(float, i.split(','))) for i in text.split())
self._set_properties(node)
# correctly handle "tile objects" (object with gid set)
if self.gid:
self.gid = self.parent.register_gid(self.gid)
... | def parse_xml(self, node) | Parse an Object from ElementTree xml node
:param node: ElementTree xml node
:return: self | 2.784258 | 2.770708 | 1.00489 |
self._set_properties(node)
self.name = node.get('name', None)
self.opacity = node.get('opacity', self.opacity)
self.visible = node.get('visible', self.visible)
image_node = node.find('image')
self.source = image_node.get('source', None)
self.trans = image... | def parse_xml(self, node) | Parse an Image Layer from ElementTree xml node
:param node: ElementTree xml node
:return: self | 2.680839 | 2.390432 | 1.121487 |
tile_size = original.get_size()
threshold = 127 # the default
try:
# count the number of pixels in the tile that are not transparent
px = pygame.mask.from_surface(original, threshold).count()
except:
# pygame_sdl2 will fail because the mask module is not included
#... | def smart_convert(original, colorkey, pixelalpha) | this method does several tests on a surface to determine the optimal
flags and pixel format for each tile surface.
this is done for the best rendering speeds and removes the need to
convert() the images on your own | 4.520497 | 4.554132 | 0.992614 |
if colorkey:
colorkey = pygame.Color('#{0}'.format(colorkey))
pixelalpha = kwargs.get('pixelalpha', True)
image = pygame.image.load(filename)
def load_image(rect=None, flags=None):
if rect:
try:
tile = image.subsurface(rect)
except ValueErro... | def pygame_image_loader(filename, colorkey, **kwargs) | pytmx image loader for pygame
:param filename:
:param colorkey:
:param kwargs:
:return: | 4.111476 | 4.304608 | 0.955134 |
kwargs['image_loader'] = pygame_image_loader
return pytmx.TiledMap(filename, *args, **kwargs) | def load_pygame(filename, *args, **kwargs) | Load a TMX file, images, and return a TiledMap class
PYGAME USERS: Use me.
this utility has 'smart' tile loading. by default any tile without
transparent pixels will be loaded for quick blitting. if the tile has
transparent pixels, then it will be loaded with per-pixel alpha. this is
a per-tile... | 4.51927 | 5.713356 | 0.791001 |
if isinstance(tileset, int):
try:
tileset = tmxmap.tilesets[tileset]
except IndexError:
msg = "Tileset #{0} not found in map {1}."
logger.debug(msg.format(tileset, tmxmap))
raise IndexError
elif isinstance(tileset, str):
try:
... | def build_rects(tmxmap, layer, tileset=None, real_gid=None) | generate a set of non-overlapping rects that represents the distribution
of the specified gid.
useful for generating rects for use in collision detection
Use at your own risk: this is experimental...will change in future
GID Note: You will need to add 1 to the GID reported by Tiled.
:param tm... | 1.835096 | 1.883858 | 0.974116 |
def pick_rect(points, rects):
ox, oy = sorted([(sum(p), p) for p in points])[0][1]
x = ox
y = oy
ex = None
while 1:
x += 1
if not (x, y) in points:
if ex is None:
ex = x - 1
if (ox, y + 1) in ... | def simplify(all_points, tilewidth, tileheight) | Given a list of points, return list of rects that represent them
kludge:
"A kludge (or kluge) is a workaround, a quick-and-dirty solution,
a clumsy or inelegant, yet effective, solution to a problem, typically
using parts that are cobbled together."
-- wikipedia
turn a list of points into a r... | 2.793272 | 2.829484 | 0.987202 |
if colorkey:
logger.debug('colorkey not implemented')
image = pyglet.image.load(filename)
def load_image(rect=None, flags=None):
if rect:
try:
x, y, w, h = rect
y = image.height - y - h
tile = image.get_region(x, y, w, h)
... | def pyglet_image_loader(filename, colorkey, **kwargs) | basic image loading with pyglet
returns pyglet Images, not textures
This is a basic proof-of-concept and is likely to fail in some situations.
Missing:
Transparency
Tile Rotation
This is slow as well. | 3.116986 | 3.295343 | 0.945876 |
r
# Get wind efficiency curve
wind_efficiency_curve = get_wind_efficiency_curve(
curve_name=wind_efficiency_curve_name)
# Reduce wind speed by wind efficiency
reduced_wind_speed = wind_speed * np.interp(
wind_speed, wind_efficiency_curve['wind_speed'],
wind_efficiency_curve['... | def reduce_wind_speed(wind_speed, wind_efficiency_curve_name='dena_mean') | r"""
Reduces wind speed by a wind efficiency curve.
The wind efficiency curves are provided in the windpowerlib and were
calculated in the dena-Netzstudie II and in the work of Knorr
(see [1]_ and [2]_).
Parameters
----------
wind_speed : pandas.Series or numpy.array
Wind speed tim... | 2.334901 | 2.508312 | 0.930866 |
r
if 'datapath' not in kwargs:
kwargs['datapath'] = os.path.join(os.path.split(
os.path.dirname(__file__))[0], 'example')
file = os.path.join(kwargs['datapath'], filename)
# read csv file
weather_df = pd.read_csv(
file, index_col=0, header=[0, 1],
date_parser=lam... | def get_weather_data(filename='weather.csv', **kwargs) | r"""
Imports weather data from a file.
The data include wind speed at two different heights in m/s, air
temperature in two different heights in K, surface roughness length in m
and air pressure in Pa. The file is located in the example folder of the
windpowerlib. The height in m for which the data ... | 3.061115 | 2.740556 | 1.116969 |
r
# specification of own wind turbine (Note: power values and nominal power
# have to be in Watt)
my_turbine = {
'name': 'myTurbine',
'nominal_power': 3e6, # in W
'hub_height': 105, # in m
'rotor_diameter': 90, # in m
'power_curve': pd.DataFrame(
d... | def initialize_wind_turbines() | r"""
Initializes two :class:`~.wind_turbine.WindTurbine` objects.
Function shows three ways to initialize a WindTurbine object. You can
either specify your own turbine, as done below for 'my_turbine', or fetch
power and/or power coefficient curve data from the OpenEnergy Database
(oedb), as done fo... | 3.159307 | 2.665106 | 1.185434 |
r
# power output calculation for my_turbine
# initialize ModelChain with default parameters and use run_model method
# to calculate power output
mc_my_turbine = ModelChain(my_turbine).run_model(weather)
# write power output time series to WindTurbine object
my_turbine.power_output = mc_my_t... | def calculate_power_output(weather, my_turbine, e126, dummy_turbine) | r"""
Calculates power output of wind turbines using the
:class:`~.modelchain.ModelChain`.
The :class:`~.modelchain.ModelChain` is a class that provides all necessary
steps to calculate the power output of a wind turbine. You can either use
the default methods for the calculation steps, as done for ... | 2.945991 | 2.632174 | 1.119224 |
r
# plot or print turbine power output
if plt:
e126.power_output.plot(legend=True, label='Enercon E126')
my_turbine.power_output.plot(legend=True, label='myTurbine')
dummy_turbine.power_output.plot(legend=True, label='dummyTurbine')
plt.show()
else:
print(e126.po... | def plot_or_print(my_turbine, e126, dummy_turbine) | r"""
Plots or prints power output and power (coefficient) curves.
Parameters
----------
my_turbine : WindTurbine
WindTurbine object with self provided power curve.
e126 : WindTurbine
WindTurbine object with power curve from data file provided by the
windpowerlib.
dummy_t... | 1.812073 | 1.748806 | 1.036177 |
r
weather = get_weather_data('weather.csv')
my_turbine, e126, dummy_turbine = initialize_wind_turbines()
calculate_power_output(weather, my_turbine, e126, dummy_turbine)
plot_or_print(my_turbine, e126, dummy_turbine) | def run_example() | r"""
Runs the basic example. | 6.991159 | 6.408184 | 1.090974 |
r
self.hub_height = np.exp(
sum(np.log(wind_dict['wind_turbine'].hub_height) *
wind_dict['wind_turbine'].nominal_power *
wind_dict['number_of_turbines']
for wind_dict in self.wind_turbine_fleet) /
self.get_installed_power())
... | def mean_hub_height(self) | r"""
Calculates the mean hub height of the wind farm.
The mean hub height of a wind farm is necessary for power output
calculations with an aggregated wind farm power curve containing wind
turbines with different hub heights. Hub heights of wind turbines with
higher nominal powe... | 6.111319 | 4.685293 | 1.304362 |
r
if 0.7 * obstacle_height > wind_speed_height:
raise ValueError("To take an obstacle height of {0} m ".format(
obstacle_height) + "into consideration, wind " +
"speed data of a greater height is needed.")
# Return np.array if wind_speed is np.array
... | def logarithmic_profile(wind_speed, wind_speed_height, hub_height,
roughness_length, obstacle_height=0.0) | r"""
Calculates the wind speed at hub height using a logarithmic wind profile.
The logarithmic height equation is used. There is the possibility of
including the height of the surrounding obstacles in the calculation. This
function is carried out when the parameter `wind_speed_model` of an
instance... | 3.794266 | 3.510519 | 1.080828 |
r
if hellman_exponent is None:
if roughness_length is not None:
# Return np.array if wind_speed is np.array
if (isinstance(wind_speed, np.ndarray) and
isinstance(roughness_length, pd.Series)):
roughness_length = np.array(roughness_length)
... | def hellman(wind_speed, wind_speed_height, hub_height,
roughness_length=None, hellman_exponent=None) | r"""
Calculates the wind speed at hub height using the hellman equation.
It is assumed that the wind profile follows a power law. This function is
carried out when the parameter `wind_speed_model` of an instance of
the :class:`~.modelchain.ModelChain` class is 'hellman'.
Parameters
----------
... | 2.90628 | 2.587263 | 1.123303 |
r
# Create power curve DataFrame
power_curve_df = pd.DataFrame(
data=[list(power_curve_wind_speeds),
list(power_curve_values)]).transpose()
# Rename columns of DataFrame
power_curve_df.columns = ['wind_speed', 'value']
if wake_losses_model == 'constant_efficiency':
... | def wake_losses_to_power_curve(power_curve_wind_speeds, power_curve_values,
wind_farm_efficiency,
wake_losses_model='power_efficiency_curve') | r"""
Reduces the power values of a power curve by an efficiency (curve).
Parameters
----------
power_curve_wind_speeds : pandas.Series or numpy.array
Wind speeds in m/s for which the power curve values are provided in
`power_curve_values`.
power_curve_values : pandas.Series or numpy... | 2.182357 | 2.115924 | 1.031397 |
r
if self.power_plant.hub_height in weather_df['temperature']:
temperature_hub = weather_df['temperature'][
self.power_plant.hub_height]
elif self.temperature_model == 'linear_gradient':
logging.debug('Calculating temperature using temperature '
... | def temperature_hub(self, weather_df) | r"""
Calculates the temperature of air at hub height.
The temperature is calculated using the method specified by
the parameter `temperature_model`.
Parameters
----------
weather_df : pandas.DataFrame
DataFrame with time series for temperature `temperature` ... | 2.710865 | 2.693486 | 1.006452 |
r
if self.density_model != 'interpolation_extrapolation':
temperature_hub = self.temperature_hub(weather_df)
# Calculation of density in kg/m³ at hub height
if self.density_model == 'barometric':
logging.debug('Calculating density using barometric height '
... | def density_hub(self, weather_df) | r"""
Calculates the density of air at hub height.
The density is calculated using the method specified by the parameter
`density_model`. Previous to the calculation of the density the
temperature at hub height is calculated using the method specified by
the parameter `temperatur... | 2.345184 | 2.173051 | 1.079213 |
r
if self.power_plant.hub_height in weather_df['wind_speed']:
wind_speed_hub = weather_df['wind_speed'][
self.power_plant.hub_height]
elif self.wind_speed_model == 'logarithmic':
logging.debug('Calculating wind speed using logarithmic wind '
... | def wind_speed_hub(self, weather_df) | r"""
Calculates the wind speed at hub height.
The method specified by the parameter `wind_speed_model` is used.
Parameters
----------
weather_df : pandas.DataFrame
DataFrame with time series for wind speed `wind_speed` in m/s and
roughness length `roughn... | 1.926228 | 1.877354 | 1.026033 |
r
if self.power_output_model == 'power_curve':
if self.power_plant.power_curve is None:
raise TypeError("Power curve values of " +
self.power_plant.name +
" are missing.")
logging.debug('Calculating p... | def calculate_power_output(self, wind_speed_hub, density_hub) | r"""
Calculates the power output of the wind power plant.
The method specified by the parameter `power_output_model` is used.
Parameters
----------
wind_speed_hub : pandas.Series or numpy.array
Wind speed at hub height in m/s.
density_hub : pandas.Series or ... | 2.123898 | 2.166913 | 0.980149 |
r
wind_speed_hub = self.wind_speed_hub(weather_df)
density_hub = (None if (self.power_output_model == 'power_curve' and
self.density_correction is False)
else self.density_hub(weather_df))
self.power_output = self.calculate_power_out... | def run_model(self, weather_df) | r"""
Runs the model.
Parameters
----------
weather_df : pandas.DataFrame
DataFrame with time series for wind speed `wind_speed` in m/s, and
roughness length `roughness_length` in m, as well as optionally
temperature `temperature` in K, pressure `press... | 4.799331 | 4.846069 | 0.990356 |
r
# find closest heights
heights_sorted = df.columns[
sorted(range(len(df.columns)),
key=lambda i: abs(df.columns[i] - target_height))]
return ((df[heights_sorted[1]] - df[heights_sorted[0]]) /
(heights_sorted[1] - heights_sorted[0]) *
(target_height - heig... | def linear_interpolation_extrapolation(df, target_height) | r"""
Linear inter- or extrapolates between the values of a data frame.
This function can be used for the inter-/extrapolation of a parameter
(e.g wind speed) available at two or more different heights, to approximate
the value at hub height. The function is carried out when the parameter
`wind_spee... | 2.699911 | 2.83068 | 0.953803 |
r
# find closest heights
heights_sorted = df.columns[
sorted(range(len(df.columns)),
key=lambda i: abs(df.columns[i] - target_height))]
return ((np.log(target_height) *
(df[heights_sorted[1]] - df[heights_sorted[0]]) -
df[heights_sorted[1]] * np.log(heigh... | def logarithmic_interpolation_extrapolation(df, target_height) | r"""
Logarithmic inter- or extrapolates between the values of a data frame.
This function can be used for the inter-/extrapolation of the wind speed if
it is available at two or more different heights, to approximate
the value at hub height. The function is carried out when the parameter
`wind_spee... | 2.574293 | 2.34073 | 1.099782 |
r
return (1 / (standard_deviation * np.sqrt(2 * np.pi)) *
np.exp(-(function_variable - mean)**2 /
(2 * standard_deviation**2))) | def gauss_distribution(function_variable, standard_deviation, mean=0) | r"""
Gauss distribution.
The Gauss distribution is used in the function
:py:func:`~.power_curves.smooth_power_curve` for power curve smoothing.
Parameters
----------
function_variable : float
Variable of the gaussian distribution.
standard_deviation : float
Standard deviati... | 2.806112 | 3.482985 | 0.805663 |
r
# Set turbulence intensity for assigning power curve
turbulence_intensity = (
weather_df['turbulence_intensity'].values.mean() if
'turbulence_intensity' in
weather_df.columns.get_level_values(0) else None)
# Assign power curve
if (self.wake_... | def assign_power_curve(self, weather_df) | r"""
Calculates the power curve of the wind turbine cluster.
The power curve is aggregated from the wind farms' and wind turbines'
power curves by using :func:`power_plant.assign_power_curve`. Depending
on the parameters of the WindTurbineCluster power curves are smoothed
and/or... | 3.246691 | 3.003898 | 1.080826 |
r
self.assign_power_curve(weather_df)
self.power_plant.mean_hub_height()
wind_speed_hub = self.wind_speed_hub(weather_df)
density_hub = (None if (self.power_output_model == 'power_curve' and
self.density_correction is False)
... | def run_model(self, weather_df) | r"""
Runs the model.
Parameters
----------
weather_df : pandas.DataFrame
DataFrame with time series for wind speed `wind_speed` in m/s, and
roughness length `roughness_length` in m, as well as optionally
temperature `temperature` in K, pressure `press... | 4.142877 | 3.966997 | 1.044336 |
r
power_coefficient_time_series = np.interp(
wind_speed, power_coefficient_curve_wind_speeds,
power_coefficient_curve_values, left=0, right=0)
power_output = (1 / 8 * density * rotor_diameter ** 2 * np.pi *
np.power(wind_speed, 3) *
power_coefficient_t... | def power_coefficient_curve(wind_speed, power_coefficient_curve_wind_speeds,
power_coefficient_curve_values, rotor_diameter,
density) | r"""
Calculates the turbine power output using a power coefficient curve.
This function is carried out when the parameter `power_output_model` of an
instance of the :class:`~.modelchain.ModelChain` class is
'power_coefficient_curve'.
Parameters
----------
wind_speed : pandas.Series or nump... | 2.840948 | 2.696101 | 1.053725 |
r
if density_correction is False:
power_output = np.interp(wind_speed, power_curve_wind_speeds,
power_curve_values, left=0, right=0)
# Power_output as pd.Series if wind_speed is pd.Series (else: np.array)
if isinstance(wind_speed, pd.Series):
... | def power_curve(wind_speed, power_curve_wind_speeds, power_curve_values,
density=None, density_correction=False) | r"""
Calculates the turbine power output using a power curve.
This function is carried out when the parameter `power_output_model` of an
instance of the :class:`~.modelchain.ModelChain` class is 'power_curve'. If
the parameter `density_correction` is True the density corrected power
curve (See :py:... | 2.772955 | 2.779042 | 0.99781 |
r
if density is None:
raise TypeError("`density` is None. For the calculation with a " +
"density corrected power curve density at hub " +
"height is needed.")
power_output = [(np.interp(
wind_speed[i], power_curve_wind_speeds * (1.225 / densit... | def power_curve_density_correction(wind_speed, power_curve_wind_speeds,
power_curve_values, density) | r"""
Calculates the turbine power output using a density corrected power curve.
This function is carried out when the parameter `density_correction` of an
instance of the :class:`~.modelchain.ModelChain` class is True.
Parameters
----------
wind_speed : pandas.Series or numpy.array
Win... | 4.057724 | 3.611591 | 1.123528 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.