Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ 指定数据目录,生成对应的合约行业数据 分为两种 1. 全市场数据,将部分标记上权重 2. 只对历史上成为成份股的,进行处理,由于前面已经转换了数据,这里只要跳选数据并处理即可 以前的做法是先生成数据,然后再生成合约 """ if __name__ == '__main__': # 时间和合约都已经生成了 # 只要将时间与合约对上即可 <|code_end|> , continue by predicting the next line. Consider current file imports: import os from kquant_data.config import __CONFIG_H5_STK_DIR__ from kquant_data.processing.merge import merge_weight_internal from kquant_data.api import get_datetime, all_instruments from kquant_data.xio.h5 import write_dataframe_set_dtype_remove_head and context: # Path: kquant_data/config.py # __CONFIG_H5_STK_DIR__ = r'D:\DATA_STK' # # Path: kquant_data/processing/merge.py # def merge_weight_internal(symbols, DateTime, wind_code): # """ # 合并一级文件夹 # :param rule: # :param sector_name: # :param dataset_name: # :return: # """ # tic() # path = os.path.join(__CONFIG_H5_STK_WEIGHT_DIR__, wind_code) # df = load_index_weight(path) # print("数据加载完成") # # 与行业不同,行业是全部有数据,它是有一部分有数据,所以直接用fillna会出错,需要先填充 # df.fillna(-1, inplace=True) # toc() # # # 原始数据比较简单,但与行业板块数据又不一样 # # 1.每年的约定时间会调整成份股 # # 2.每天的值都不一样 # # 约定nan表示不属于成份,0表示属于成份,但权重为0 # df = expand_dataframe_according_to(df, DateTime.index, symbols['wind_code']) # # -1表示特殊数据,处理下 # df.replace(-1, np.nan, inplace=True) # print("数据加载完成") # toc() # # return df # # Path: kquant_data/api.py # def get_datetime(path): # dt = pd.read_csv(path, index_col=0, parse_dates=True) # dt['date'] = dt.index # return dt # # def all_instruments(path=None, type=None): # """ # 得到合约列表 # :param type: # :return: # """ # if path is None: # path = os.path.join(__CONFIG_H5_STK_DIR__, "daily", 'Symbol.csv') # # df = pd.read_csv(path, dtype={'code': str}) # # return df # # Path: kquant_data/xio/h5.py # def write_dataframe_set_dtype_remove_head(path, data, dtype, dataset_name): # """ # 每个单元格的数据类型都一样 # 强行指定类型可以让文件的占用更小 # 表头不保存 # :param path: # :param data: # :param dtype: # :param dateset_name: # :return: # """ # f = h5py.File(path, 'w') # if dtype is None: # f.create_dataset(dataset_name, data=data.as_matrix(), compression="gzip", compression_opts=6) # else: # f.create_dataset(dataset_name, data=data, compression="gzip", compression_opts=6, dtype=dtype) # f.close() # return which might include code, classes, or functions. Output only the next line.
path = os.path.join(__CONFIG_H5_STK_DIR__, "5min_000905.SH", 'Symbol.csv')
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ 指定数据目录,生成对应的合约行业数据 分为两种 1. 全市场数据,将部分标记上权重 2. 只对历史上成为成份股的,进行处理,由于前面已经转换了数据,这里只要跳选数据并处理即可 以前的做法是先生成数据,然后再生成合约 """ if __name__ == '__main__': # 时间和合约都已经生成了 # 只要将时间与合约对上即可 path = os.path.join(__CONFIG_H5_STK_DIR__, "5min_000905.SH", 'Symbol.csv') symbols = all_instruments(path) path = os.path.join(__CONFIG_H5_STK_DIR__, "5min_000905.SH", 'DateTime.csv') DateTime = get_datetime(path) <|code_end|> with the help of current file imports: import os from kquant_data.config import __CONFIG_H5_STK_DIR__ from kquant_data.processing.merge import merge_weight_internal from kquant_data.api import get_datetime, all_instruments from kquant_data.xio.h5 import write_dataframe_set_dtype_remove_head and context from other files: # Path: kquant_data/config.py # __CONFIG_H5_STK_DIR__ = r'D:\DATA_STK' # # Path: kquant_data/processing/merge.py # def merge_weight_internal(symbols, DateTime, wind_code): # """ # 合并一级文件夹 # :param rule: # :param sector_name: # :param dataset_name: # :return: # """ # tic() # path = os.path.join(__CONFIG_H5_STK_WEIGHT_DIR__, wind_code) # df = load_index_weight(path) # print("数据加载完成") # # 与行业不同,行业是全部有数据,它是有一部分有数据,所以直接用fillna会出错,需要先填充 # df.fillna(-1, inplace=True) # toc() # # # 原始数据比较简单,但与行业板块数据又不一样 # # 1.每年的约定时间会调整成份股 # # 2.每天的值都不一样 # # 约定nan表示不属于成份,0表示属于成份,但权重为0 # df = expand_dataframe_according_to(df, DateTime.index, symbols['wind_code']) # # -1表示特殊数据,处理下 # df.replace(-1, np.nan, inplace=True) # print("数据加载完成") # toc() # # return df # # Path: kquant_data/api.py # def get_datetime(path): # dt = pd.read_csv(path, index_col=0, parse_dates=True) # dt['date'] = dt.index # return dt # # def all_instruments(path=None, type=None): # """ # 得到合约列表 # :param type: # :return: # """ # if path is None: # path = os.path.join(__CONFIG_H5_STK_DIR__, "daily", 'Symbol.csv') # # df = pd.read_csv(path, dtype={'code': str}) # # return df # # Path: kquant_data/xio/h5.py # def write_dataframe_set_dtype_remove_head(path, data, dtype, dataset_name): # """ # 每个单元格的数据类型都一样 # 强行指定类型可以让文件的占用更小 # 表头不保存 # :param path: # :param data: # :param dtype: # :param dateset_name: # :return: # """ # f = h5py.File(path, 'w') # if dtype is None: # f.create_dataset(dataset_name, data=data.as_matrix(), compression="gzip", compression_opts=6) # else: # f.create_dataset(dataset_name, data=data, compression="gzip", compression_opts=6, dtype=dtype) # f.close() # return , which may contain function names, class names, or code. Output only the next line.
df = merge_weight_internal(symbols, DateTime, "000905.SH")
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ 指定数据目录,生成对应的合约行业数据 分为两种 1. 全市场数据,将部分标记上权重 2. 只对历史上成为成份股的,进行处理,由于前面已经转换了数据,这里只要跳选数据并处理即可 以前的做法是先生成数据,然后再生成合约 """ if __name__ == '__main__': # 时间和合约都已经生成了 # 只要将时间与合约对上即可 path = os.path.join(__CONFIG_H5_STK_DIR__, "5min_000905.SH", 'Symbol.csv') symbols = all_instruments(path) path = os.path.join(__CONFIG_H5_STK_DIR__, "5min_000905.SH", 'DateTime.csv') <|code_end|> with the help of current file imports: import os from kquant_data.config import __CONFIG_H5_STK_DIR__ from kquant_data.processing.merge import merge_weight_internal from kquant_data.api import get_datetime, all_instruments from kquant_data.xio.h5 import write_dataframe_set_dtype_remove_head and context from other files: # Path: kquant_data/config.py # __CONFIG_H5_STK_DIR__ = r'D:\DATA_STK' # # Path: kquant_data/processing/merge.py # def merge_weight_internal(symbols, DateTime, wind_code): # """ # 合并一级文件夹 # :param rule: # :param sector_name: # :param dataset_name: # :return: # """ # tic() # path = os.path.join(__CONFIG_H5_STK_WEIGHT_DIR__, wind_code) # df = load_index_weight(path) # print("数据加载完成") # # 与行业不同,行业是全部有数据,它是有一部分有数据,所以直接用fillna会出错,需要先填充 # df.fillna(-1, inplace=True) # toc() # # # 原始数据比较简单,但与行业板块数据又不一样 # # 1.每年的约定时间会调整成份股 # # 2.每天的值都不一样 # # 约定nan表示不属于成份,0表示属于成份,但权重为0 # df = expand_dataframe_according_to(df, DateTime.index, symbols['wind_code']) # # -1表示特殊数据,处理下 # df.replace(-1, np.nan, inplace=True) # print("数据加载完成") # toc() # # return df # # Path: kquant_data/api.py # def get_datetime(path): # dt = pd.read_csv(path, index_col=0, parse_dates=True) # dt['date'] = dt.index # return dt # # def all_instruments(path=None, type=None): # """ # 得到合约列表 # :param type: # :return: # """ # if path is None: # path = os.path.join(__CONFIG_H5_STK_DIR__, "daily", 'Symbol.csv') # # df = pd.read_csv(path, dtype={'code': str}) # # return df # # Path: kquant_data/xio/h5.py # def write_dataframe_set_dtype_remove_head(path, data, dtype, dataset_name): # """ # 每个单元格的数据类型都一样 # 强行指定类型可以让文件的占用更小 # 表头不保存 # :param path: # :param data: # :param dtype: # :param dateset_name: # :return: # """ # f = h5py.File(path, 'w') # if dtype is None: # f.create_dataset(dataset_name, data=data.as_matrix(), compression="gzip", compression_opts=6) # else: # f.create_dataset(dataset_name, data=data, compression="gzip", compression_opts=6, dtype=dtype) # f.close() # return , which may contain function names, class names, or code. Output only the next line.
DateTime = get_datetime(path)
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ 指定数据目录,生成对应的合约行业数据 分为两种 1. 全市场数据,将部分标记上权重 2. 只对历史上成为成份股的,进行处理,由于前面已经转换了数据,这里只要跳选数据并处理即可 以前的做法是先生成数据,然后再生成合约 """ if __name__ == '__main__': # 时间和合约都已经生成了 # 只要将时间与合约对上即可 path = os.path.join(__CONFIG_H5_STK_DIR__, "5min_000905.SH", 'Symbol.csv') <|code_end|> , predict the next line using imports from the current file: import os from kquant_data.config import __CONFIG_H5_STK_DIR__ from kquant_data.processing.merge import merge_weight_internal from kquant_data.api import get_datetime, all_instruments from kquant_data.xio.h5 import write_dataframe_set_dtype_remove_head and context including class names, function names, and sometimes code from other files: # Path: kquant_data/config.py # __CONFIG_H5_STK_DIR__ = r'D:\DATA_STK' # # Path: kquant_data/processing/merge.py # def merge_weight_internal(symbols, DateTime, wind_code): # """ # 合并一级文件夹 # :param rule: # :param sector_name: # :param dataset_name: # :return: # """ # tic() # path = os.path.join(__CONFIG_H5_STK_WEIGHT_DIR__, wind_code) # df = load_index_weight(path) # print("数据加载完成") # # 与行业不同,行业是全部有数据,它是有一部分有数据,所以直接用fillna会出错,需要先填充 # df.fillna(-1, inplace=True) # toc() # # # 原始数据比较简单,但与行业板块数据又不一样 # # 1.每年的约定时间会调整成份股 # # 2.每天的值都不一样 # # 约定nan表示不属于成份,0表示属于成份,但权重为0 # df = expand_dataframe_according_to(df, DateTime.index, symbols['wind_code']) # # -1表示特殊数据,处理下 # df.replace(-1, np.nan, inplace=True) # print("数据加载完成") # toc() # # return df # # Path: kquant_data/api.py # def get_datetime(path): # dt = pd.read_csv(path, index_col=0, parse_dates=True) # dt['date'] = dt.index # return dt # # def all_instruments(path=None, type=None): # """ # 得到合约列表 # :param type: # :return: # """ # if path is None: # path = os.path.join(__CONFIG_H5_STK_DIR__, "daily", 'Symbol.csv') # # df = pd.read_csv(path, dtype={'code': str}) # # return df # # Path: kquant_data/xio/h5.py # def write_dataframe_set_dtype_remove_head(path, data, dtype, dataset_name): # """ # 每个单元格的数据类型都一样 # 强行指定类型可以让文件的占用更小 # 表头不保存 # :param path: # :param data: # :param dtype: # :param dateset_name: # :return: # """ # f = h5py.File(path, 'w') # if dtype is None: # f.create_dataset(dataset_name, data=data.as_matrix(), compression="gzip", compression_opts=6) # else: # f.create_dataset(dataset_name, data=data, compression="gzip", compression_opts=6, dtype=dtype) # f.close() # return . Output only the next line.
symbols = all_instruments(path)
Given the code snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ 指定数据目录,生成对应的合约行业数据 分为两种 1. 全市场数据,将部分标记上权重 2. 只对历史上成为成份股的,进行处理,由于前面已经转换了数据,这里只要跳选数据并处理即可 以前的做法是先生成数据,然后再生成合约 """ if __name__ == '__main__': # 时间和合约都已经生成了 # 只要将时间与合约对上即可 path = os.path.join(__CONFIG_H5_STK_DIR__, "5min_000905.SH", 'Symbol.csv') symbols = all_instruments(path) path = os.path.join(__CONFIG_H5_STK_DIR__, "5min_000905.SH", 'DateTime.csv') DateTime = get_datetime(path) df = merge_weight_internal(symbols, DateTime, "000905.SH") path = os.path.join(__CONFIG_H5_STK_DIR__, "5min_000905.SH", 'weight.h5') <|code_end|> , generate the next line using the imports in this file: import os from kquant_data.config import __CONFIG_H5_STK_DIR__ from kquant_data.processing.merge import merge_weight_internal from kquant_data.api import get_datetime, all_instruments from kquant_data.xio.h5 import write_dataframe_set_dtype_remove_head and context (functions, classes, or occasionally code) from other files: # Path: kquant_data/config.py # __CONFIG_H5_STK_DIR__ = r'D:\DATA_STK' # # Path: kquant_data/processing/merge.py # def merge_weight_internal(symbols, DateTime, wind_code): # """ # 合并一级文件夹 # :param rule: # :param sector_name: # :param dataset_name: # :return: # """ # tic() # path = os.path.join(__CONFIG_H5_STK_WEIGHT_DIR__, wind_code) # df = load_index_weight(path) # print("数据加载完成") # # 与行业不同,行业是全部有数据,它是有一部分有数据,所以直接用fillna会出错,需要先填充 # df.fillna(-1, inplace=True) # toc() # # # 原始数据比较简单,但与行业板块数据又不一样 # # 1.每年的约定时间会调整成份股 # # 2.每天的值都不一样 # # 约定nan表示不属于成份,0表示属于成份,但权重为0 # df = expand_dataframe_according_to(df, DateTime.index, symbols['wind_code']) # # -1表示特殊数据,处理下 # df.replace(-1, np.nan, inplace=True) # print("数据加载完成") # toc() # # return df # # Path: kquant_data/api.py # def get_datetime(path): # dt = pd.read_csv(path, index_col=0, parse_dates=True) # dt['date'] = dt.index # return dt # # def all_instruments(path=None, type=None): # """ # 得到合约列表 # :param type: # :return: # """ # if path is None: # path = os.path.join(__CONFIG_H5_STK_DIR__, "daily", 'Symbol.csv') # # df = pd.read_csv(path, dtype={'code': str}) # # return df # # Path: kquant_data/xio/h5.py # def write_dataframe_set_dtype_remove_head(path, data, dtype, dataset_name): # """ # 每个单元格的数据类型都一样 # 强行指定类型可以让文件的占用更小 # 表头不保存 # :param path: # :param data: # :param dtype: # :param dateset_name: # :return: # """ # f = h5py.File(path, 'w') # if dtype is None: # f.create_dataset(dataset_name, data=data.as_matrix(), compression="gzip", compression_opts=6) # else: # f.create_dataset(dataset_name, data=data, compression="gzip", compression_opts=6, dtype=dtype) # f.close() # return . Output only the next line.
write_dataframe_set_dtype_remove_head(path, df, None, "weight")
Given snippet: <|code_start|>10001027 510050C1806A02800 50ETF购6月2.749A 10185 10/26/2017 0:00 10001131 510050C1806M02750 50ETF购6月2.75 10000 12/1/2017 0:00 由于执行价重复,所以不同软件显示不同 万得和通达信都列出了两个6月,另一个是6月-A wind_code 不会变,但对应的trade_code和exx_price是发生变动的 :param path: :return: """ df = read_data_dataframe(path) df_extract1 = df['trade_code'].str.extract('(\d{6})([CP])(\d{4})(\D)\d{4, 5}', expand=True) df_extract1.columns = ['option_mark_code', 'call_or_put', 'limit_month', 'limit_month_m'] df_extract1['limit_month'] = df_extract1['limit_month'].astype(int) # 这个以后再拼接也成 # df_extract1['option_mark_code'] = df_extract1['option_mark_code'] + '.SH' # 已经退市sec_name会变,主要是年份的区别 df_extract2 = df['sec_name'].str.split('月', expand=True) df_extract2[1] = df_extract2[1].str.extract('([\d\.-]*)', expand=True) df_extract2[1] = df_extract2[1].astype(float) df_extract2.columns = ['tmp', 'exercise_price'] df = df.merge(df_extract1, how='left', left_index=True, right_index=True) df = df.merge(df_extract2[['exercise_price']], how='left', left_index=True, right_index=True) df.index = df.index.astype(str) return df def get_opt_info(filename): <|code_end|> , continue by predicting the next line. Consider current file imports: import os from ..config import __CONFIG_H5_OPT_DIR__ from ..xio.csv import read_data_dataframe and context: # Path: kquant_data/config.py # __CONFIG_H5_OPT_DIR__ = r'D:\DATA_OPT' # # Path: kquant_data/xio/csv.py # def read_data_dataframe(path, sep=','): # """ # 读取季报的公告日 # 注意:有些股票多个季度一起发,一般是公司出问题了,特别是600878,四个报告同一天发布 # 年报与一季报很有可能一起发 # :param path: # :param sep: # :return: # """ # try: # df = pd.read_csv(path, index_col=0, parse_dates=True, encoding='utf-8-sig', sep=sep) # except (FileNotFoundError, OSError): # return None # # return df which might include code, classes, or functions. Output only the next line.
root_path = os.path.join(__CONFIG_H5_OPT_DIR__, 'optioncontractbasicinfo', filename)
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ """ def read_optioncontractbasicinfo(path): """ http://www.sse.com.cn/disclosure/announcement/general/c/c_20171127_4425064.shtml 2017年11月28号除权日 除权除息时行权价和合约单位都需要调整 调整后合约行权价可能与之前重复,如2.75被调成2.7,而2.7被调成2.651 可能挂的合约执行价相同 10001025 510050C1806A02700 50ETF购6月2.651A 10185 10/26/2017 0:00 10001026 510050C1806A02750 50ETF购6月2.70A 10185 10/26/2017 0:00 10001139 510050C1806M02700 50ETF购6月2.70 10000 12/18/2017 0:00 10001027 510050C1806A02800 50ETF购6月2.749A 10185 10/26/2017 0:00 10001131 510050C1806M02750 50ETF购6月2.75 10000 12/1/2017 0:00 由于执行价重复,所以不同软件显示不同 万得和通达信都列出了两个6月,另一个是6月-A wind_code 不会变,但对应的trade_code和exx_price是发生变动的 :param path: :return: """ <|code_end|> , predict the next line using imports from the current file: import os from ..config import __CONFIG_H5_OPT_DIR__ from ..xio.csv import read_data_dataframe and context including class names, function names, and sometimes code from other files: # Path: kquant_data/config.py # __CONFIG_H5_OPT_DIR__ = r'D:\DATA_OPT' # # Path: kquant_data/xio/csv.py # def read_data_dataframe(path, sep=','): # """ # 读取季报的公告日 # 注意:有些股票多个季度一起发,一般是公司出问题了,特别是600878,四个报告同一天发布 # 年报与一季报很有可能一起发 # :param path: # :param sep: # :return: # """ # try: # df = pd.read_csv(path, index_col=0, parse_dates=True, encoding='utf-8-sig', sep=sep) # except (FileNotFoundError, OSError): # return None # # return df . Output only the next line.
df = read_data_dataframe(path)
Next line prediction: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ 更新郑商所合约名,3位转4位,不小心转错的需要再转回来 只在需要的时候才用,由于每天都在下数据,历史上的只要不下载历史数据就可以不更新 FG这种有12个月的可用来参考,然后改CZCE_convert函数 """ def process_CZCE_type2(path): # 郑商所的合约,对于已经退市的合约需要将3位变成4位 # 1. 最后一个文件肯定是最新的,它是当前正在交易的合约,应当全是3位,然后遍历其它文件没有出现的就可以改名 # 2. 实际测试后发现,退市的合约并不是立即换成4位,需要等一年多,或更长时间 for dirpath, dirnames, filenames in os.walk(path, topdown=False): for filename in filenames: if filename < '2015-01-01.csv': continue curr_path = os.path.join(dirpath, filename) print(curr_path) curr_df = read_constituent(curr_path) if curr_df is None: continue curr_set = set(curr_df['wind_code']) <|code_end|> . Use current file imports: (import os import pandas as pd from kquant_data.future.symbol import CZCE_convert from kquant_data.wind_resume.wset import read_constituent, write_constituent from kquant_data.config import __CONFIG_H5_FUT_SECTOR_DIR__) and context including class names, function names, or small code snippets from other files: # Path: kquant_data/future/symbol.py # def CZCE_convert(symbol): # match = CZCE_pattern.match(symbol) # # 有就直接用,没有就得填,到2000年怎么办,到2020年怎么办 # if not match: # return symbol # # num1 = match.group(2) # num3 = match.group(3) # # 这里老要改 # if num3 > '606' and num1 == '1': # return "%s%s%s" % (match.group(1), match.group(3), match.group(4)) # if len(num1) == 0 and num3 <= '606': # return "%s1%s%s" % (match.group(1), match.group(3), match.group(4)) # return symbol # # Path: kquant_data/wind_resume/wset.py # def _binsearch_download_constituent(w, dates, path, file_ext, start, end, sector, windcode, field, # two_sides=False, is_indexconstituent=False): # def file_download_constituent(w, dates, path, file_ext, sector, windcode, field, is_indexconstituent): # def move_constituent(path, dst_path): # def download_sectors_list( # w, # root_path, # sector_name="中信证券一级行业指数"): # def download_sectors( # w, # trading_days, # root_path, # sector_name="中信证券一级行业指数"): # def download_sector( # w, # trading_days, # root_path, # sector_name="风险警示股票"): # def download_index_weight(w, trading_days, wind_code, root_path): # def download_index_weight2(w, dates, wind_code, root_path): # def download_futureoir_day_range(w, day_range, windcode, root_path): # def resume_download_futureoir(w, trading_days, root_path, windcode, adjust_trading_days): # # Path: kquant_data/config.py # __CONFIG_H5_FUT_SECTOR_DIR__ = os.path.join(__CONFIG_H5_FUT_DIR__, 'sectorconstituent') . Output only the next line.
mod_set = set(map(CZCE_convert, curr_set))
Given the code snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ 更新郑商所合约名,3位转4位,不小心转错的需要再转回来 只在需要的时候才用,由于每天都在下数据,历史上的只要不下载历史数据就可以不更新 FG这种有12个月的可用来参考,然后改CZCE_convert函数 """ def process_CZCE_type2(path): # 郑商所的合约,对于已经退市的合约需要将3位变成4位 # 1. 最后一个文件肯定是最新的,它是当前正在交易的合约,应当全是3位,然后遍历其它文件没有出现的就可以改名 # 2. 实际测试后发现,退市的合约并不是立即换成4位,需要等一年多,或更长时间 for dirpath, dirnames, filenames in os.walk(path, topdown=False): for filename in filenames: if filename < '2015-01-01.csv': continue curr_path = os.path.join(dirpath, filename) print(curr_path) <|code_end|> , generate the next line using the imports in this file: import os import pandas as pd from kquant_data.future.symbol import CZCE_convert from kquant_data.wind_resume.wset import read_constituent, write_constituent from kquant_data.config import __CONFIG_H5_FUT_SECTOR_DIR__ and context (functions, classes, or occasionally code) from other files: # Path: kquant_data/future/symbol.py # def CZCE_convert(symbol): # match = CZCE_pattern.match(symbol) # # 有就直接用,没有就得填,到2000年怎么办,到2020年怎么办 # if not match: # return symbol # # num1 = match.group(2) # num3 = match.group(3) # # 这里老要改 # if num3 > '606' and num1 == '1': # return "%s%s%s" % (match.group(1), match.group(3), match.group(4)) # if len(num1) == 0 and num3 <= '606': # return "%s1%s%s" % (match.group(1), match.group(3), match.group(4)) # return symbol # # Path: kquant_data/wind_resume/wset.py # def _binsearch_download_constituent(w, dates, path, file_ext, start, end, sector, windcode, field, # two_sides=False, is_indexconstituent=False): # def file_download_constituent(w, dates, path, file_ext, sector, windcode, field, is_indexconstituent): # def move_constituent(path, dst_path): # def download_sectors_list( # w, # root_path, # sector_name="中信证券一级行业指数"): # def download_sectors( # w, # trading_days, # root_path, # sector_name="中信证券一级行业指数"): # def download_sector( # w, # trading_days, # root_path, # sector_name="风险警示股票"): # def download_index_weight(w, trading_days, wind_code, root_path): # def download_index_weight2(w, dates, wind_code, root_path): # def download_futureoir_day_range(w, day_range, windcode, root_path): # def resume_download_futureoir(w, trading_days, root_path, windcode, adjust_trading_days): # # Path: kquant_data/config.py # __CONFIG_H5_FUT_SECTOR_DIR__ = os.path.join(__CONFIG_H5_FUT_DIR__, 'sectorconstituent') . Output only the next line.
curr_df = read_constituent(curr_path)
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ 更新郑商所合约名,3位转4位,不小心转错的需要再转回来 只在需要的时候才用,由于每天都在下数据,历史上的只要不下载历史数据就可以不更新 FG这种有12个月的可用来参考,然后改CZCE_convert函数 """ def process_CZCE_type2(path): # 郑商所的合约,对于已经退市的合约需要将3位变成4位 # 1. 最后一个文件肯定是最新的,它是当前正在交易的合约,应当全是3位,然后遍历其它文件没有出现的就可以改名 # 2. 实际测试后发现,退市的合约并不是立即换成4位,需要等一年多,或更长时间 for dirpath, dirnames, filenames in os.walk(path, topdown=False): for filename in filenames: if filename < '2015-01-01.csv': continue curr_path = os.path.join(dirpath, filename) print(curr_path) curr_df = read_constituent(curr_path) if curr_df is None: continue curr_set = set(curr_df['wind_code']) mod_set = set(map(CZCE_convert, curr_set)) if curr_set == mod_set: continue new_df = pd.DataFrame(list(mod_set), columns=['wind_code']) new_df.sort_values(by=['wind_code'], inplace=True) <|code_end|> with the help of current file imports: import os import pandas as pd from kquant_data.future.symbol import CZCE_convert from kquant_data.wind_resume.wset import read_constituent, write_constituent from kquant_data.config import __CONFIG_H5_FUT_SECTOR_DIR__ and context from other files: # Path: kquant_data/future/symbol.py # def CZCE_convert(symbol): # match = CZCE_pattern.match(symbol) # # 有就直接用,没有就得填,到2000年怎么办,到2020年怎么办 # if not match: # return symbol # # num1 = match.group(2) # num3 = match.group(3) # # 这里老要改 # if num3 > '606' and num1 == '1': # return "%s%s%s" % (match.group(1), match.group(3), match.group(4)) # if len(num1) == 0 and num3 <= '606': # return "%s1%s%s" % (match.group(1), match.group(3), match.group(4)) # return symbol # # Path: kquant_data/wind_resume/wset.py # def _binsearch_download_constituent(w, dates, path, file_ext, start, end, sector, windcode, field, # two_sides=False, is_indexconstituent=False): # def file_download_constituent(w, dates, path, file_ext, sector, windcode, field, is_indexconstituent): # def move_constituent(path, dst_path): # def download_sectors_list( # w, # root_path, # sector_name="中信证券一级行业指数"): # def download_sectors( # w, # trading_days, # root_path, # sector_name="中信证券一级行业指数"): # def download_sector( # w, # trading_days, # root_path, # sector_name="风险警示股票"): # def download_index_weight(w, trading_days, wind_code, root_path): # def download_index_weight2(w, dates, wind_code, root_path): # def download_futureoir_day_range(w, day_range, windcode, root_path): # def resume_download_futureoir(w, trading_days, root_path, windcode, adjust_trading_days): # # Path: kquant_data/config.py # __CONFIG_H5_FUT_SECTOR_DIR__ = os.path.join(__CONFIG_H5_FUT_DIR__, 'sectorconstituent') , which may contain function names, class names, or code. Output only the next line.
write_constituent(curr_path, new_df)
Predict the next line for this snippet: <|code_start|>更新郑商所合约名,3位转4位,不小心转错的需要再转回来 只在需要的时候才用,由于每天都在下数据,历史上的只要不下载历史数据就可以不更新 FG这种有12个月的可用来参考,然后改CZCE_convert函数 """ def process_CZCE_type2(path): # 郑商所的合约,对于已经退市的合约需要将3位变成4位 # 1. 最后一个文件肯定是最新的,它是当前正在交易的合约,应当全是3位,然后遍历其它文件没有出现的就可以改名 # 2. 实际测试后发现,退市的合约并不是立即换成4位,需要等一年多,或更长时间 for dirpath, dirnames, filenames in os.walk(path, topdown=False): for filename in filenames: if filename < '2015-01-01.csv': continue curr_path = os.path.join(dirpath, filename) print(curr_path) curr_df = read_constituent(curr_path) if curr_df is None: continue curr_set = set(curr_df['wind_code']) mod_set = set(map(CZCE_convert, curr_set)) if curr_set == mod_set: continue new_df = pd.DataFrame(list(mod_set), columns=['wind_code']) new_df.sort_values(by=['wind_code'], inplace=True) write_constituent(curr_path, new_df) if __name__ == '__main__': <|code_end|> with the help of current file imports: import os import pandas as pd from kquant_data.future.symbol import CZCE_convert from kquant_data.wind_resume.wset import read_constituent, write_constituent from kquant_data.config import __CONFIG_H5_FUT_SECTOR_DIR__ and context from other files: # Path: kquant_data/future/symbol.py # def CZCE_convert(symbol): # match = CZCE_pattern.match(symbol) # # 有就直接用,没有就得填,到2000年怎么办,到2020年怎么办 # if not match: # return symbol # # num1 = match.group(2) # num3 = match.group(3) # # 这里老要改 # if num3 > '606' and num1 == '1': # return "%s%s%s" % (match.group(1), match.group(3), match.group(4)) # if len(num1) == 0 and num3 <= '606': # return "%s1%s%s" % (match.group(1), match.group(3), match.group(4)) # return symbol # # Path: kquant_data/wind_resume/wset.py # def _binsearch_download_constituent(w, dates, path, file_ext, start, end, sector, windcode, field, # two_sides=False, is_indexconstituent=False): # def file_download_constituent(w, dates, path, file_ext, sector, windcode, field, is_indexconstituent): # def move_constituent(path, dst_path): # def download_sectors_list( # w, # root_path, # sector_name="中信证券一级行业指数"): # def download_sectors( # w, # trading_days, # root_path, # sector_name="中信证券一级行业指数"): # def download_sector( # w, # trading_days, # root_path, # sector_name="风险警示股票"): # def download_index_weight(w, trading_days, wind_code, root_path): # def download_index_weight2(w, dates, wind_code, root_path): # def download_futureoir_day_range(w, day_range, windcode, root_path): # def resume_download_futureoir(w, trading_days, root_path, windcode, adjust_trading_days): # # Path: kquant_data/config.py # __CONFIG_H5_FUT_SECTOR_DIR__ = os.path.join(__CONFIG_H5_FUT_DIR__, 'sectorconstituent') , which may contain function names, class names, or code. Output only the next line.
path = os.path.join(__CONFIG_H5_FUT_SECTOR_DIR__, '郑商所全部品种')
Given snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ 得到合约的上市时间 有新品种上市时才运行 """ if __name__ == '__main__': w.start() # 加载股票列表,这里需要在每天收盘后导出日线数据才能做 wind_codes = get_all_products_wind() wind_codes_s = get_all_products_wind_S() wind_codes.extend(wind_codes_s) # if True: <|code_end|> , continue by predicting the next line. Consider current file imports: import os import numpy as np from WindPy import w from kquant_data.wind_resume.wsd import resume_download_delist_date from kquant_data.future.symbol import get_all_products_wind, get_all_products_wind_S from kquant_data.config import __CONFIG_H5_FUT_FACTOR_DIR__ and context: # Path: kquant_data/wind_resume/wsd.py # def resume_download_delist_date( # w, # wind_codes, # root_path, # field='delist_date', # dtype=np.datetime64): # """ # 下载每支股票的delist_date # 如果以后有同类的每个股票一个数,但可能上新股票都得更新的field就可以用 # :param w: # :param wind_codes: # :param field: # :param dtype: # :param root_path: # :return: # """ # wind_codes_set = set(wind_codes) # # date_str = datetime.today().strftime('%Y-%m-%d') # # path = os.path.join(root_path, '%s.csv' % field) # if dtype == np.datetime64: # df_old = read_datetime_dataframe(path) # else: # df_old = read_data_dataframe(path) # # if df_old is None: # new_symbols = wind_codes_set # else: # df_old.dropna(axis=1, inplace=True) # new_symbols = wind_codes_set - set(df_old.columns) # # # 没有新数据好办,只有一个数据怎么办?会出错吗 # if len(new_symbols) == 0: # print('没有空合约,没有必要更新%s' % field) # # 可能排序不行,还是再处理下 # df_new = df_old.copy() # else: # # 第一次下全,以后每次下最新的 # df_new = download_daily_at(w, list(new_symbols), field, date_str) # # # 新旧数据的合并 # df = pd.DataFrame(columns=wind_codes) # if df_old is not None: # df[df_old.columns] = df_old # df.index = df_new.index # df[df_new.columns] = df_new # else: # df = df_new # # # 排序有点乱,得处理 # df = df[wind_codes] # if dtype == np.datetime64: # write_datetime_dataframe(path, df) # else: # write_data_dataframe(path, df) # # Path: kquant_data/future/symbol.py # def get_all_products_wind(): # _lst = get_all_products() # __lst = [get_wind_code(x).upper() for x in _lst] # return __lst # # def get_all_products_wind_S(): # _lst = get_all_products() # __lst = [get_wind_code_S(x).upper() for x in _lst] # return __lst # # Path: kquant_data/config.py # __CONFIG_H5_FUT_FACTOR_DIR__ = os.path.join(__CONFIG_H5_FUT_DIR__, 'factor') which might include code, classes, or functions. Output only the next line.
resume_download_delist_date(w, wind_codes, __CONFIG_H5_FUT_FACTOR_DIR__,
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ 得到合约的上市时间 有新品种上市时才运行 """ if __name__ == '__main__': w.start() # 加载股票列表,这里需要在每天收盘后导出日线数据才能做 <|code_end|> using the current file's imports: import os import numpy as np from WindPy import w from kquant_data.wind_resume.wsd import resume_download_delist_date from kquant_data.future.symbol import get_all_products_wind, get_all_products_wind_S from kquant_data.config import __CONFIG_H5_FUT_FACTOR_DIR__ and any relevant context from other files: # Path: kquant_data/wind_resume/wsd.py # def resume_download_delist_date( # w, # wind_codes, # root_path, # field='delist_date', # dtype=np.datetime64): # """ # 下载每支股票的delist_date # 如果以后有同类的每个股票一个数,但可能上新股票都得更新的field就可以用 # :param w: # :param wind_codes: # :param field: # :param dtype: # :param root_path: # :return: # """ # wind_codes_set = set(wind_codes) # # date_str = datetime.today().strftime('%Y-%m-%d') # # path = os.path.join(root_path, '%s.csv' % field) # if dtype == np.datetime64: # df_old = read_datetime_dataframe(path) # else: # df_old = read_data_dataframe(path) # # if df_old is None: # new_symbols = wind_codes_set # else: # df_old.dropna(axis=1, inplace=True) # new_symbols = wind_codes_set - set(df_old.columns) # # # 没有新数据好办,只有一个数据怎么办?会出错吗 # if len(new_symbols) == 0: # print('没有空合约,没有必要更新%s' % field) # # 可能排序不行,还是再处理下 # df_new = df_old.copy() # else: # # 第一次下全,以后每次下最新的 # df_new = download_daily_at(w, list(new_symbols), field, date_str) # # # 新旧数据的合并 # df = pd.DataFrame(columns=wind_codes) # if df_old is not None: # df[df_old.columns] = df_old # df.index = df_new.index # df[df_new.columns] = df_new # else: # df = df_new # # # 排序有点乱,得处理 # df = df[wind_codes] # if dtype == np.datetime64: # write_datetime_dataframe(path, df) # else: # write_data_dataframe(path, df) # # Path: kquant_data/future/symbol.py # def get_all_products_wind(): # _lst = get_all_products() # __lst = [get_wind_code(x).upper() for x in _lst] # return __lst # # def get_all_products_wind_S(): # _lst = get_all_products() # __lst = [get_wind_code_S(x).upper() for x in _lst] # return __lst # # Path: kquant_data/config.py # __CONFIG_H5_FUT_FACTOR_DIR__ = os.path.join(__CONFIG_H5_FUT_DIR__, 'factor') . Output only the next line.
wind_codes = get_all_products_wind()
Next line prediction: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ 得到合约的上市时间 有新品种上市时才运行 """ if __name__ == '__main__': w.start() # 加载股票列表,这里需要在每天收盘后导出日线数据才能做 wind_codes = get_all_products_wind() <|code_end|> . Use current file imports: (import os import numpy as np from WindPy import w from kquant_data.wind_resume.wsd import resume_download_delist_date from kquant_data.future.symbol import get_all_products_wind, get_all_products_wind_S from kquant_data.config import __CONFIG_H5_FUT_FACTOR_DIR__) and context including class names, function names, or small code snippets from other files: # Path: kquant_data/wind_resume/wsd.py # def resume_download_delist_date( # w, # wind_codes, # root_path, # field='delist_date', # dtype=np.datetime64): # """ # 下载每支股票的delist_date # 如果以后有同类的每个股票一个数,但可能上新股票都得更新的field就可以用 # :param w: # :param wind_codes: # :param field: # :param dtype: # :param root_path: # :return: # """ # wind_codes_set = set(wind_codes) # # date_str = datetime.today().strftime('%Y-%m-%d') # # path = os.path.join(root_path, '%s.csv' % field) # if dtype == np.datetime64: # df_old = read_datetime_dataframe(path) # else: # df_old = read_data_dataframe(path) # # if df_old is None: # new_symbols = wind_codes_set # else: # df_old.dropna(axis=1, inplace=True) # new_symbols = wind_codes_set - set(df_old.columns) # # # 没有新数据好办,只有一个数据怎么办?会出错吗 # if len(new_symbols) == 0: # print('没有空合约,没有必要更新%s' % field) # # 可能排序不行,还是再处理下 # df_new = df_old.copy() # else: # # 第一次下全,以后每次下最新的 # df_new = download_daily_at(w, list(new_symbols), field, date_str) # # # 新旧数据的合并 # df = pd.DataFrame(columns=wind_codes) # if df_old is not None: # df[df_old.columns] = df_old # df.index = df_new.index # df[df_new.columns] = df_new # else: # df = df_new # # # 排序有点乱,得处理 # df = df[wind_codes] # if dtype == np.datetime64: # write_datetime_dataframe(path, df) # else: # write_data_dataframe(path, df) # # Path: kquant_data/future/symbol.py # def get_all_products_wind(): # _lst = get_all_products() # __lst = [get_wind_code(x).upper() for x in _lst] # return __lst # # def get_all_products_wind_S(): # _lst = get_all_products() # __lst = [get_wind_code_S(x).upper() for x in _lst] # return __lst # # Path: kquant_data/config.py # __CONFIG_H5_FUT_FACTOR_DIR__ = os.path.join(__CONFIG_H5_FUT_DIR__, 'factor') . Output only the next line.
wind_codes_s = get_all_products_wind_S()
Next line prediction: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ 得到合约的上市时间 有新品种上市时才运行 """ if __name__ == '__main__': w.start() # 加载股票列表,这里需要在每天收盘后导出日线数据才能做 wind_codes = get_all_products_wind() wind_codes_s = get_all_products_wind_S() wind_codes.extend(wind_codes_s) # if True: <|code_end|> . Use current file imports: (import os import numpy as np from WindPy import w from kquant_data.wind_resume.wsd import resume_download_delist_date from kquant_data.future.symbol import get_all_products_wind, get_all_products_wind_S from kquant_data.config import __CONFIG_H5_FUT_FACTOR_DIR__) and context including class names, function names, or small code snippets from other files: # Path: kquant_data/wind_resume/wsd.py # def resume_download_delist_date( # w, # wind_codes, # root_path, # field='delist_date', # dtype=np.datetime64): # """ # 下载每支股票的delist_date # 如果以后有同类的每个股票一个数,但可能上新股票都得更新的field就可以用 # :param w: # :param wind_codes: # :param field: # :param dtype: # :param root_path: # :return: # """ # wind_codes_set = set(wind_codes) # # date_str = datetime.today().strftime('%Y-%m-%d') # # path = os.path.join(root_path, '%s.csv' % field) # if dtype == np.datetime64: # df_old = read_datetime_dataframe(path) # else: # df_old = read_data_dataframe(path) # # if df_old is None: # new_symbols = wind_codes_set # else: # df_old.dropna(axis=1, inplace=True) # new_symbols = wind_codes_set - set(df_old.columns) # # # 没有新数据好办,只有一个数据怎么办?会出错吗 # if len(new_symbols) == 0: # print('没有空合约,没有必要更新%s' % field) # # 可能排序不行,还是再处理下 # df_new = df_old.copy() # else: # # 第一次下全,以后每次下最新的 # df_new = download_daily_at(w, list(new_symbols), field, date_str) # # # 新旧数据的合并 # df = pd.DataFrame(columns=wind_codes) # if df_old is not None: # df[df_old.columns] = df_old # df.index = df_new.index # df[df_new.columns] = df_new # else: # df = df_new # # # 排序有点乱,得处理 # df = df[wind_codes] # if dtype == np.datetime64: # write_datetime_dataframe(path, df) # else: # write_data_dataframe(path, df) # # Path: kquant_data/future/symbol.py # def get_all_products_wind(): # _lst = get_all_products() # __lst = [get_wind_code(x).upper() for x in _lst] # return __lst # # def get_all_products_wind_S(): # _lst = get_all_products() # __lst = [get_wind_code_S(x).upper() for x in _lst] # return __lst # # Path: kquant_data/config.py # __CONFIG_H5_FUT_FACTOR_DIR__ = os.path.join(__CONFIG_H5_FUT_DIR__, 'factor') . Output only the next line.
resume_download_delist_date(w, wind_codes, __CONFIG_H5_FUT_FACTOR_DIR__,
Given snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ 演示将5分钟数据转成1小时数据 """ def _export_data(rule, _input, output, instruments, i): t = instruments.iloc[i] print("%d %s" % (i, t['local_symbol'])) <|code_end|> , continue by predicting the next line. Consider current file imports: import os import pandas as pd from kquant_data.config import __CONFIG_H5_STK_DIR__ from kquant_data.stock.stock import bars_to_h5 from kquant_data.processing.utils import filter_dataframe, bar_convert, multiprocessing_convert from kquant_data.stock.symbol import get_folder_symbols and context: # Path: kquant_data/config.py # __CONFIG_H5_STK_DIR__ = r'D:\DATA_STK' # # Path: kquant_data/stock/stock.py # def sort_dividend(divs): # def factor(daily, divs, ndigits): # def adjust(df, adjust_type=None): # def merge_adjust_factor(df, div): # def read_h5_tdx(market, code, bar_size, h5_path, tdx_path, div_path): # def _export_dividend_from_data(tdx_root, dividend_output, daily_output, data): # def export_dividend_daily_dzh(dzh_input, tdx_root, dividend_output, daily_output): # def export_dividend_daily_gbbq(gbbq_input, tdx_root, dividend_output, daily_output): # # Path: kquant_data/processing/utils.py # def filter_dataframe(df, index_name=None, start_date=None, end_date=None, fields=None): # if index_name is not None: # df['index_datetime'] = df[index_name].apply(yyyyMMddHHmm_2_datetime) # df = df.set_index('index_datetime') # # 过滤时间 # if start_date is not None or end_date is not None: # df = df[start_date:end_date] # # 过滤字段 # if fields is not None: # df = df[fields] # return df # # def bar_convert(df, rule='1H'): # """ # 数据转换 # :param df: # :param rule: # :return: # """ # how_dict = { # 'DateTime': 'first', # 'Open': 'first', # 'High': 'max', # 'Low': 'min', # 'Close': 'last', # 'Amount': 'sum', # 'Volume': 'sum', # 'backward_factor': 'last', # 'forward_factor': 'last', # } # # how_dict = { # # 'Symbol': 'first', # # 'DateTime': 'first', # # 'TradingDay': 'first', # # 'ActionDay': 'first', # # 'Time': 'first', # # 'BarSize': 'first', # # 'Pad': 'min', # # 'Open': 'first', # # 'High': 'max', # # 'Low': 'min', # # 'Close': 'last', # # 'Volume': 'sum', # # 'Amount': 'sum', # # 'OpenInterest': 'last', # # 'Settle': 'last', # # 'AdjustFactorPM': 'last', # # 'AdjustFactorTD': 'last', # # 'BAdjustFactorPM': 'last', # # 'BAdjustFactorTD': 'last', # # 'FAdjustFactorPM': 'last', # # 'FAdjustFactorTD': 'last', # # 'MoneyFlow': 'sum', # # } # columns = df.columns # new = df.resample(rule, closed='left', label='left').apply(how_dict) # # new.dropna(inplace=True) # # 有些才上市没多久的,居然开头有很多天为空白,需要删除,如sh603990 # new = new[new['Open'] != 0] # # # 居然位置要调整一下 # new = new[columns] # # # 由于存盘时是用的DateTime这个字段,不是index上的时间,这会导致其它软件读取数据时出错,需要修正数据 # new['DateTime'] = new.index.map(datetime_2_yyyyMMddHHmm) # # return new # # def multiprocessing_convert(multi, rule, _input, output, instruments, func_convert): # tic() # # if multi: # pool_size = multiprocessing.cpu_count() - 1 # pool = multiprocessing.Pool(processes=pool_size) # func = partial(func_convert, rule, _input, output, instruments) # pool_outputs = pool.map(func, range(len(instruments))) # print('Pool:', pool_outputs) # else: # for i in range(len(instruments)): # func_convert(rule, _input, output, instruments, i) # # toc() # # Path: kquant_data/stock/symbol.py # def get_folder_symbols(folder, sub_folder): # path = os.path.join(folder, sub_folder, 'sh') # df_sh = get_symbols_from_path(path, "SSE") # path = os.path.join(folder, sub_folder, 'sz') # df_sz = get_symbols_from_path(path, "SZSE") # df = pd.concat([df_sh, df_sz]) # # return df which might include code, classes, or functions. Output only the next line.
path = os.path.join(__CONFIG_H5_STK_DIR__, _input, t['market'], "%s.h5" % t['local_symbol'])
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ 演示将5分钟数据转成1小时数据 """ def _export_data(rule, _input, output, instruments, i): t = instruments.iloc[i] print("%d %s" % (i, t['local_symbol'])) path = os.path.join(__CONFIG_H5_STK_DIR__, _input, t['market'], "%s.h5" % t['local_symbol']) df = None try: df = pd.read_hdf(path) except: pass if df is None: return None df = filter_dataframe(df, 'DateTime', None, None, None) df1 = bar_convert(df, rule) date_output = os.path.join(__CONFIG_H5_STK_DIR__, output, t['market'], "%s.h5" % t['local_symbol']) <|code_end|> with the help of current file imports: import os import pandas as pd from kquant_data.config import __CONFIG_H5_STK_DIR__ from kquant_data.stock.stock import bars_to_h5 from kquant_data.processing.utils import filter_dataframe, bar_convert, multiprocessing_convert from kquant_data.stock.symbol import get_folder_symbols and context from other files: # Path: kquant_data/config.py # __CONFIG_H5_STK_DIR__ = r'D:\DATA_STK' # # Path: kquant_data/stock/stock.py # def sort_dividend(divs): # def factor(daily, divs, ndigits): # def adjust(df, adjust_type=None): # def merge_adjust_factor(df, div): # def read_h5_tdx(market, code, bar_size, h5_path, tdx_path, div_path): # def _export_dividend_from_data(tdx_root, dividend_output, daily_output, data): # def export_dividend_daily_dzh(dzh_input, tdx_root, dividend_output, daily_output): # def export_dividend_daily_gbbq(gbbq_input, tdx_root, dividend_output, daily_output): # # Path: kquant_data/processing/utils.py # def filter_dataframe(df, index_name=None, start_date=None, end_date=None, fields=None): # if index_name is not None: # df['index_datetime'] = df[index_name].apply(yyyyMMddHHmm_2_datetime) # df = df.set_index('index_datetime') # # 过滤时间 # if start_date is not None or end_date is not None: # df = df[start_date:end_date] # # 过滤字段 # if fields is not None: # df = df[fields] # return df # # def bar_convert(df, rule='1H'): # """ # 数据转换 # :param df: # :param rule: # :return: # """ # how_dict = { # 'DateTime': 'first', # 'Open': 'first', # 'High': 'max', # 'Low': 'min', # 'Close': 'last', # 'Amount': 'sum', # 'Volume': 'sum', # 'backward_factor': 'last', # 'forward_factor': 'last', # } # # how_dict = { # # 'Symbol': 'first', # # 'DateTime': 'first', # # 'TradingDay': 'first', # # 'ActionDay': 'first', # # 'Time': 'first', # # 'BarSize': 'first', # # 'Pad': 'min', # # 'Open': 'first', # # 'High': 'max', # # 'Low': 'min', # # 'Close': 'last', # # 'Volume': 'sum', # # 'Amount': 'sum', # # 'OpenInterest': 'last', # # 'Settle': 'last', # # 'AdjustFactorPM': 'last', # # 'AdjustFactorTD': 'last', # # 'BAdjustFactorPM': 'last', # # 'BAdjustFactorTD': 'last', # # 'FAdjustFactorPM': 'last', # # 'FAdjustFactorTD': 'last', # # 'MoneyFlow': 'sum', # # } # columns = df.columns # new = df.resample(rule, closed='left', label='left').apply(how_dict) # # new.dropna(inplace=True) # # 有些才上市没多久的,居然开头有很多天为空白,需要删除,如sh603990 # new = new[new['Open'] != 0] # # # 居然位置要调整一下 # new = new[columns] # # # 由于存盘时是用的DateTime这个字段,不是index上的时间,这会导致其它软件读取数据时出错,需要修正数据 # new['DateTime'] = new.index.map(datetime_2_yyyyMMddHHmm) # # return new # # def multiprocessing_convert(multi, rule, _input, output, instruments, func_convert): # tic() # # if multi: # pool_size = multiprocessing.cpu_count() - 1 # pool = multiprocessing.Pool(processes=pool_size) # func = partial(func_convert, rule, _input, output, instruments) # pool_outputs = pool.map(func, range(len(instruments))) # print('Pool:', pool_outputs) # else: # for i in range(len(instruments)): # func_convert(rule, _input, output, instruments, i) # # toc() # # Path: kquant_data/stock/symbol.py # def get_folder_symbols(folder, sub_folder): # path = os.path.join(folder, sub_folder, 'sh') # df_sh = get_symbols_from_path(path, "SSE") # path = os.path.join(folder, sub_folder, 'sz') # df_sz = get_symbols_from_path(path, "SZSE") # df = pd.concat([df_sh, df_sz]) # # return df , which may contain function names, class names, or code. Output only the next line.
bars_to_h5(date_output, df1)
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ 演示将5分钟数据转成1小时数据 """ def _export_data(rule, _input, output, instruments, i): t = instruments.iloc[i] print("%d %s" % (i, t['local_symbol'])) path = os.path.join(__CONFIG_H5_STK_DIR__, _input, t['market'], "%s.h5" % t['local_symbol']) df = None try: df = pd.read_hdf(path) except: pass if df is None: return None <|code_end|> , predict the next line using imports from the current file: import os import pandas as pd from kquant_data.config import __CONFIG_H5_STK_DIR__ from kquant_data.stock.stock import bars_to_h5 from kquant_data.processing.utils import filter_dataframe, bar_convert, multiprocessing_convert from kquant_data.stock.symbol import get_folder_symbols and context including class names, function names, and sometimes code from other files: # Path: kquant_data/config.py # __CONFIG_H5_STK_DIR__ = r'D:\DATA_STK' # # Path: kquant_data/stock/stock.py # def sort_dividend(divs): # def factor(daily, divs, ndigits): # def adjust(df, adjust_type=None): # def merge_adjust_factor(df, div): # def read_h5_tdx(market, code, bar_size, h5_path, tdx_path, div_path): # def _export_dividend_from_data(tdx_root, dividend_output, daily_output, data): # def export_dividend_daily_dzh(dzh_input, tdx_root, dividend_output, daily_output): # def export_dividend_daily_gbbq(gbbq_input, tdx_root, dividend_output, daily_output): # # Path: kquant_data/processing/utils.py # def filter_dataframe(df, index_name=None, start_date=None, end_date=None, fields=None): # if index_name is not None: # df['index_datetime'] = df[index_name].apply(yyyyMMddHHmm_2_datetime) # df = df.set_index('index_datetime') # # 过滤时间 # if start_date is not None or end_date is not None: # df = df[start_date:end_date] # # 过滤字段 # if fields is not None: # df = df[fields] # return df # # def bar_convert(df, rule='1H'): # """ # 数据转换 # :param df: # :param rule: # :return: # """ # how_dict = { # 'DateTime': 'first', # 'Open': 'first', # 'High': 'max', # 'Low': 'min', # 'Close': 'last', # 'Amount': 'sum', # 'Volume': 'sum', # 'backward_factor': 'last', # 'forward_factor': 'last', # } # # how_dict = { # # 'Symbol': 'first', # # 'DateTime': 'first', # # 'TradingDay': 'first', # # 'ActionDay': 'first', # # 'Time': 'first', # # 'BarSize': 'first', # # 'Pad': 'min', # # 'Open': 'first', # # 'High': 'max', # # 'Low': 'min', # # 'Close': 'last', # # 'Volume': 'sum', # # 'Amount': 'sum', # # 'OpenInterest': 'last', # # 'Settle': 'last', # # 'AdjustFactorPM': 'last', # # 'AdjustFactorTD': 'last', # # 'BAdjustFactorPM': 'last', # # 'BAdjustFactorTD': 'last', # # 'FAdjustFactorPM': 'last', # # 'FAdjustFactorTD': 'last', # # 'MoneyFlow': 'sum', # # } # columns = df.columns # new = df.resample(rule, closed='left', label='left').apply(how_dict) # # new.dropna(inplace=True) # # 有些才上市没多久的,居然开头有很多天为空白,需要删除,如sh603990 # new = new[new['Open'] != 0] # # # 居然位置要调整一下 # new = new[columns] # # # 由于存盘时是用的DateTime这个字段,不是index上的时间,这会导致其它软件读取数据时出错,需要修正数据 # new['DateTime'] = new.index.map(datetime_2_yyyyMMddHHmm) # # return new # # def multiprocessing_convert(multi, rule, _input, output, instruments, func_convert): # tic() # # if multi: # pool_size = multiprocessing.cpu_count() - 1 # pool = multiprocessing.Pool(processes=pool_size) # func = partial(func_convert, rule, _input, output, instruments) # pool_outputs = pool.map(func, range(len(instruments))) # print('Pool:', pool_outputs) # else: # for i in range(len(instruments)): # func_convert(rule, _input, output, instruments, i) # # toc() # # Path: kquant_data/stock/symbol.py # def get_folder_symbols(folder, sub_folder): # path = os.path.join(folder, sub_folder, 'sh') # df_sh = get_symbols_from_path(path, "SSE") # path = os.path.join(folder, sub_folder, 'sz') # df_sz = get_symbols_from_path(path, "SZSE") # df = pd.concat([df_sh, df_sz]) # # return df . Output only the next line.
df = filter_dataframe(df, 'DateTime', None, None, None)
Based on the snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ 演示将5分钟数据转成1小时数据 """ def _export_data(rule, _input, output, instruments, i): t = instruments.iloc[i] print("%d %s" % (i, t['local_symbol'])) path = os.path.join(__CONFIG_H5_STK_DIR__, _input, t['market'], "%s.h5" % t['local_symbol']) df = None try: df = pd.read_hdf(path) except: pass if df is None: return None df = filter_dataframe(df, 'DateTime', None, None, None) <|code_end|> , predict the immediate next line with the help of imports: import os import pandas as pd from kquant_data.config import __CONFIG_H5_STK_DIR__ from kquant_data.stock.stock import bars_to_h5 from kquant_data.processing.utils import filter_dataframe, bar_convert, multiprocessing_convert from kquant_data.stock.symbol import get_folder_symbols and context (classes, functions, sometimes code) from other files: # Path: kquant_data/config.py # __CONFIG_H5_STK_DIR__ = r'D:\DATA_STK' # # Path: kquant_data/stock/stock.py # def sort_dividend(divs): # def factor(daily, divs, ndigits): # def adjust(df, adjust_type=None): # def merge_adjust_factor(df, div): # def read_h5_tdx(market, code, bar_size, h5_path, tdx_path, div_path): # def _export_dividend_from_data(tdx_root, dividend_output, daily_output, data): # def export_dividend_daily_dzh(dzh_input, tdx_root, dividend_output, daily_output): # def export_dividend_daily_gbbq(gbbq_input, tdx_root, dividend_output, daily_output): # # Path: kquant_data/processing/utils.py # def filter_dataframe(df, index_name=None, start_date=None, end_date=None, fields=None): # if index_name is not None: # df['index_datetime'] = df[index_name].apply(yyyyMMddHHmm_2_datetime) # df = df.set_index('index_datetime') # # 过滤时间 # if start_date is not None or end_date is not None: # df = df[start_date:end_date] # # 过滤字段 # if fields is not None: # df = df[fields] # return df # # def bar_convert(df, rule='1H'): # """ # 数据转换 # :param df: # :param rule: # :return: # """ # how_dict = { # 'DateTime': 'first', # 'Open': 'first', # 'High': 'max', # 'Low': 'min', # 'Close': 'last', # 'Amount': 'sum', # 'Volume': 'sum', # 'backward_factor': 'last', # 'forward_factor': 'last', # } # # how_dict = { # # 'Symbol': 'first', # # 'DateTime': 'first', # # 'TradingDay': 'first', # # 'ActionDay': 'first', # # 'Time': 'first', # # 'BarSize': 'first', # # 'Pad': 'min', # # 'Open': 'first', # # 'High': 'max', # # 'Low': 'min', # # 'Close': 'last', # # 'Volume': 'sum', # # 'Amount': 'sum', # # 'OpenInterest': 'last', # # 'Settle': 'last', # # 'AdjustFactorPM': 'last', # # 'AdjustFactorTD': 'last', # # 'BAdjustFactorPM': 'last', # # 'BAdjustFactorTD': 'last', # # 'FAdjustFactorPM': 'last', # # 'FAdjustFactorTD': 'last', # # 'MoneyFlow': 'sum', # # } # columns = df.columns # new = df.resample(rule, closed='left', label='left').apply(how_dict) # # new.dropna(inplace=True) # # 有些才上市没多久的,居然开头有很多天为空白,需要删除,如sh603990 # new = new[new['Open'] != 0] # # # 居然位置要调整一下 # new = new[columns] # # # 由于存盘时是用的DateTime这个字段,不是index上的时间,这会导致其它软件读取数据时出错,需要修正数据 # new['DateTime'] = new.index.map(datetime_2_yyyyMMddHHmm) # # return new # # def multiprocessing_convert(multi, rule, _input, output, instruments, func_convert): # tic() # # if multi: # pool_size = multiprocessing.cpu_count() - 1 # pool = multiprocessing.Pool(processes=pool_size) # func = partial(func_convert, rule, _input, output, instruments) # pool_outputs = pool.map(func, range(len(instruments))) # print('Pool:', pool_outputs) # else: # for i in range(len(instruments)): # func_convert(rule, _input, output, instruments, i) # # toc() # # Path: kquant_data/stock/symbol.py # def get_folder_symbols(folder, sub_folder): # path = os.path.join(folder, sub_folder, 'sh') # df_sh = get_symbols_from_path(path, "SSE") # path = os.path.join(folder, sub_folder, 'sz') # df_sz = get_symbols_from_path(path, "SZSE") # df = pd.concat([df_sh, df_sz]) # # return df . Output only the next line.
df1 = bar_convert(df, rule)
Given snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ 合并财务数据 """ if __name__ == '__main__': rule = '1day' field = 'total_shares' <|code_end|> , continue by predicting the next line. Consider current file imports: from kquant_data.processing.merge import merge_report and context: # Path: kquant_data/processing/merge.py # def merge_report(rule, field, dataset_name): # path = os.path.join(__CONFIG_H5_STK_DIR__, rule, 'Symbol.csv') # symbols = all_instruments(path) # # path = os.path.join(__CONFIG_H5_STK_DIR__, rule, 'DateTime.csv') # DateTime = get_datetime(path) # # tic() # path = os.path.join(__CONFIG_H5_STK_FACTOR_DIR__, field) # df = None # cnt = 0 # for dirpath, dirnames, filenames in os.walk(path): # # 只处理目录 # for filename in filenames: # print(filename) # filepath = os.path.join(dirpath, filename) # df_ = read_data_dataframe(filepath) # df_tmp = df_.stack() # if df is None: # df = df_tmp # else: # df = pd.concat([df, df_tmp]) # cnt += 1 # # if cnt > 10: # # break # # df = df.unstack() # df.fillna(method='ffill', inplace=True) # print("数据加载完成") # toc() # # df = expand_dataframe_according_to(df, DateTime.index, symbols['wind_code']) # # # path = os.path.join(__CONFIG_H5_STK_DIR__, rule, "%s.h5" % dataset_name) # write_dataframe_set_dtype_remove_head(path, df, None, field) which might include code, classes, or functions. Output only the next line.
merge_report(rule, field, field)
Next line prediction: <|code_start|>""" def func_select_instrument_by_signal(row, field, _open, df_info, month_index, atm_index): """ # 用开盘价来选要交易的合约代码 long_short_opt = long_short_enter.apply(func_select_instrument_by_signal, axis=1, args=('SZ50', Open, df_info, 3, 1)) long_short_opt.set_index(['index_datetime'], inplace=True) 由于比较特别,还是需要用户自己选才行 :param row: 每行信号 :param field: 信号在当前数据中的字段名 :param _open: 交易当天的开盘价 :param df_info: 期权合约信息表,将通过etf行情和执行价选出实虚合约 :param month_index: 选出当月、次月、当季、次季 :param atm_index: 选出虚几 :return: """ signal = row[field] if np.isnan(signal): return row if signal == 0: row[field] = np.nan return row # 取指定日期的数据 date = row['index_datetime'].strftime("%Y-%m-%d") # 指定日期 # 2015-05-29号,5月份的合约已经结束,应当切换成6月才行 <|code_end|> . Use current file imports: (import numpy as np from .info import get_opt_info_filtered_by_date, get_opt_info_filtered_by_month, \ get_opt_info_filtered_by_call_or_put) and context including class names, function names, or small code snippets from other files: # Path: kquant_data/option/info.py # def get_opt_info_filtered_by_date(df_info, date): # # date = '2018-03-04' # 指定日期 # # call_or_put = 'C' # 指定类别 # # limit_month = 1806 # 指定月份 # # limit_month_m = 'A' # 指定月份2 # df_filtered = df_info[(df_info['listed_date'] <= date) # & (df_info['expire_date'] >= date)] # return df_filtered # # def get_opt_info_filtered_by_month(df_info, limit_month): # df_filtered = df_info[ # (df_info['limit_month'] == limit_month)] # return df_filtered # # def get_opt_info_filtered_by_call_or_put(df_info, call_or_put): # df_filtered = df_info[ # (df_info['call_or_put'] == call_or_put)] # return df_filtered . Output only the next line.
df_filtered = get_opt_info_filtered_by_date(df_info, date)
Using the snippet: <|code_start|> :param df_info: 期权合约信息表,将通过etf行情和执行价选出实虚合约 :param month_index: 选出当月、次月、当季、次季 :param atm_index: 选出虚几 :return: """ signal = row[field] if np.isnan(signal): return row if signal == 0: row[field] = np.nan return row # 取指定日期的数据 date = row['index_datetime'].strftime("%Y-%m-%d") # 指定日期 # 2015-05-29号,5月份的合约已经结束,应当切换成6月才行 df_filtered = get_opt_info_filtered_by_date(df_info, date) df_filtered1 = df_filtered.reset_index() # 除权时,选合约会有问题,如果改成除权后,有新开仓才去新合约即可 df_filtered1.set_index(['limit_month', 'limit_month_m'], inplace=True) list_limit_month = list(set(df_filtered1.index.get_level_values(0))) list_limit_month.sort() # 设定是做哪个类型 # 看多,买入call # 看空,买入put call_or_put = 'C' if signal > 0 else 'P' df_filtered2 = get_opt_info_filtered_by_call_or_put(df_filtered, call_or_put) # 选择当月,次月,当季,下季 # 有可能选出来的合约没有虚值,或没有实值,因为当天新挂合约并知道 <|code_end|> , determine the next line of code. You have imports: import numpy as np from .info import get_opt_info_filtered_by_date, get_opt_info_filtered_by_month, \ get_opt_info_filtered_by_call_or_put and context (class names, function names, or code) available: # Path: kquant_data/option/info.py # def get_opt_info_filtered_by_date(df_info, date): # # date = '2018-03-04' # 指定日期 # # call_or_put = 'C' # 指定类别 # # limit_month = 1806 # 指定月份 # # limit_month_m = 'A' # 指定月份2 # df_filtered = df_info[(df_info['listed_date'] <= date) # & (df_info['expire_date'] >= date)] # return df_filtered # # def get_opt_info_filtered_by_month(df_info, limit_month): # df_filtered = df_info[ # (df_info['limit_month'] == limit_month)] # return df_filtered # # def get_opt_info_filtered_by_call_or_put(df_info, call_or_put): # df_filtered = df_info[ # (df_info['call_or_put'] == call_or_put)] # return df_filtered . Output only the next line.
df_filtered3 = get_opt_info_filtered_by_month(df_filtered2, list_limit_month[month_index])
Given the code snippet: <|code_start|> 由于比较特别,还是需要用户自己选才行 :param row: 每行信号 :param field: 信号在当前数据中的字段名 :param _open: 交易当天的开盘价 :param df_info: 期权合约信息表,将通过etf行情和执行价选出实虚合约 :param month_index: 选出当月、次月、当季、次季 :param atm_index: 选出虚几 :return: """ signal = row[field] if np.isnan(signal): return row if signal == 0: row[field] = np.nan return row # 取指定日期的数据 date = row['index_datetime'].strftime("%Y-%m-%d") # 指定日期 # 2015-05-29号,5月份的合约已经结束,应当切换成6月才行 df_filtered = get_opt_info_filtered_by_date(df_info, date) df_filtered1 = df_filtered.reset_index() # 除权时,选合约会有问题,如果改成除权后,有新开仓才去新合约即可 df_filtered1.set_index(['limit_month', 'limit_month_m'], inplace=True) list_limit_month = list(set(df_filtered1.index.get_level_values(0))) list_limit_month.sort() # 设定是做哪个类型 # 看多,买入call # 看空,买入put call_or_put = 'C' if signal > 0 else 'P' <|code_end|> , generate the next line using the imports in this file: import numpy as np from .info import get_opt_info_filtered_by_date, get_opt_info_filtered_by_month, \ get_opt_info_filtered_by_call_or_put and context (functions, classes, or occasionally code) from other files: # Path: kquant_data/option/info.py # def get_opt_info_filtered_by_date(df_info, date): # # date = '2018-03-04' # 指定日期 # # call_or_put = 'C' # 指定类别 # # limit_month = 1806 # 指定月份 # # limit_month_m = 'A' # 指定月份2 # df_filtered = df_info[(df_info['listed_date'] <= date) # & (df_info['expire_date'] >= date)] # return df_filtered # # def get_opt_info_filtered_by_month(df_info, limit_month): # df_filtered = df_info[ # (df_info['limit_month'] == limit_month)] # return df_filtered # # def get_opt_info_filtered_by_call_or_put(df_info, call_or_put): # df_filtered = df_info[ # (df_info['call_or_put'] == call_or_put)] # return df_filtered . Output only the next line.
df_filtered2 = get_opt_info_filtered_by_call_or_put(df_filtered, call_or_put)
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- """ 更新数据范围列表,用于下载数据时减少重复下载 日线数据路径是 IF/IF1804.h5 分钟数据路径是 IF1804/IF1804_20180226.h5 已经退市的合约,只要做过一次,后面就没有必要再做了 但数据还是有问题,不活跃的合约,最后几天完全没有行情了 """ # 解决Python 3.6的pandas不支持中文路径的问题 print(sys.getfilesystemencoding()) # 查看修改前的 try: sys._enablelegacywindowsfsencoding() # 修改 print(sys.getfilesystemencoding()) # 查看修改后的 except: pass path_ipo_last_trade = os.path.join(__CONFIG_H5_FUT_SECTOR_DIR__, 'ipo_last_trade_trading.csv') def get_in_file_day(file_path, wind_code, df): print(file_path) # 需要 df_h5 = pd.read_hdf(file_path) df_h5.dropna(axis=0, how='all', thresh=3, inplace=True) if df_h5.empty: return df <|code_end|> with the help of current file imports: import os import sys import pandas as pd from datetime import datetime from kquant_data.utils.xdatetime import yyyyMMddHHmm_2_datetime, yyyyMMdd_2_datetime from kquant_data.config import __CONFIG_H5_FUT_SECTOR_DIR__ from kquant_data.future.symbol import wind_code_2_InstrumentID from kquant_data.xio.csv import read_datetime_dataframe from kquant_data.utils.xdatetime import tic, toc and context from other files: # Path: kquant_data/utils/xdatetime.py # def yyyyMMddHHmm_2_datetime(dt): # """ # 输入一个长整型yyyyMMddhmm,返回对应的时间 # :param dt: # :return: # """ # dt = int(dt) # FIXME:在python2下会有问题吗? # (yyyyMMdd, hh) = divmod(dt, 10000) # (yyyy, MMdd) = divmod(yyyyMMdd, 10000) # (MM, dd) = divmod(MMdd, 100) # (hh, mm) = divmod(hh, 100) # # return datetime(yyyy, MM, dd, hh, mm) # # def yyyyMMdd_2_datetime(dt): # yyyyMMdd = int(dt) # (yyyy, MMdd) = divmod(yyyyMMdd, 10000) # (MM, dd) = divmod(MMdd, 100) # if yyyy == 0: # return None # # return datetime(yyyy, MM, dd, 0, 0) # # Path: kquant_data/config.py # __CONFIG_H5_FUT_SECTOR_DIR__ = os.path.join(__CONFIG_H5_FUT_DIR__, 'sectorconstituent') # # Path: kquant_data/future/symbol.py # def wind_code_2_InstrumentID(df, field): # sym_ex = df[field].str.split('.') # sym_ex = list(sym_ex) # sym_ex_df = pd.DataFrame(sym_ex, index=df.index) # sym_ex_df.columns = ['InstrumentID', 'exchange'] # df = pd.concat([df, sym_ex_df], axis=1) # df['lower'] = (df['exchange'] == 'SHF') | (df['exchange'] == 'DCE') | (df['exchange'] == 'INE') # df['InstrumentID'][df['lower']] = df['InstrumentID'].str.lower() # return df # # Path: kquant_data/xio/csv.py # def read_datetime_dataframe(path, sep=','): # """ # 读取季报的公告日,即里面全是日期 # 注意:有些股票多个季度一起发,一般是公司出问题了,特别是600878,四个报告同一天发布 # 年报与一季报很有可能一起发 # # 读取ipo_date # :param path: # :param sep: # :return: # """ # try: # df = pd.read_csv(path, index_col=0, parse_dates=True, encoding='utf-8-sig', sep=sep) # except (FileNotFoundError, OSError): # return None # # df = df.stack(dropna=False) # df = pd.to_datetime(df) # df = df.unstack() # # return df # # Path: kquant_data/utils/xdatetime.py # def tic(): # """ # 对应MATLAB中的tic # :return: # """ # globals()['tt'] = time.clock() # # def toc(): # """ # 对应MATLAB中的toc # :return: # """ # t = time.clock() - globals()['tt'] # print('\nElapsed time: %.8f seconds\n' % t) # return t , which may contain function names, class names, or code. Output only the next line.
first = yyyyMMddHHmm_2_datetime(df_h5['DateTime'].iloc[0])
Based on the snippet: <|code_start|> print(row['last']) continue except: pass df = get_in_file_day(dirpath_filename, shotname, df) path = os.path.join(root_path, 'first_last.csv') df.index.name = 'product' df.to_csv(path) return df def CZCE_3to4(x): if x['exchange'] == 'CZC': x['InstrumentID'] = '%s%s%s' % (x['InstrumentID'][0:2], str(x['lasttrade_date'])[2], x['InstrumentID'][-3:]) return x def load_ipo_last_trade_trading(): df_csv = pd.read_csv(path_ipo_last_trade, encoding='utf-8-sig') df = wind_code_2_InstrumentID(df_csv, 'wind_code') df = df.apply(CZCE_3to4, axis=1) df = df.set_index(['InstrumentID']) return df if __name__ == '__main__': ipo_last_trade = load_ipo_last_trade_trading() <|code_end|> , predict the immediate next line with the help of imports: import os import sys import pandas as pd from datetime import datetime from kquant_data.utils.xdatetime import yyyyMMddHHmm_2_datetime, yyyyMMdd_2_datetime from kquant_data.config import __CONFIG_H5_FUT_SECTOR_DIR__ from kquant_data.future.symbol import wind_code_2_InstrumentID from kquant_data.xio.csv import read_datetime_dataframe from kquant_data.utils.xdatetime import tic, toc and context (classes, functions, sometimes code) from other files: # Path: kquant_data/utils/xdatetime.py # def yyyyMMddHHmm_2_datetime(dt): # """ # 输入一个长整型yyyyMMddhmm,返回对应的时间 # :param dt: # :return: # """ # dt = int(dt) # FIXME:在python2下会有问题吗? # (yyyyMMdd, hh) = divmod(dt, 10000) # (yyyy, MMdd) = divmod(yyyyMMdd, 10000) # (MM, dd) = divmod(MMdd, 100) # (hh, mm) = divmod(hh, 100) # # return datetime(yyyy, MM, dd, hh, mm) # # def yyyyMMdd_2_datetime(dt): # yyyyMMdd = int(dt) # (yyyy, MMdd) = divmod(yyyyMMdd, 10000) # (MM, dd) = divmod(MMdd, 100) # if yyyy == 0: # return None # # return datetime(yyyy, MM, dd, 0, 0) # # Path: kquant_data/config.py # __CONFIG_H5_FUT_SECTOR_DIR__ = os.path.join(__CONFIG_H5_FUT_DIR__, 'sectorconstituent') # # Path: kquant_data/future/symbol.py # def wind_code_2_InstrumentID(df, field): # sym_ex = df[field].str.split('.') # sym_ex = list(sym_ex) # sym_ex_df = pd.DataFrame(sym_ex, index=df.index) # sym_ex_df.columns = ['InstrumentID', 'exchange'] # df = pd.concat([df, sym_ex_df], axis=1) # df['lower'] = (df['exchange'] == 'SHF') | (df['exchange'] == 'DCE') | (df['exchange'] == 'INE') # df['InstrumentID'][df['lower']] = df['InstrumentID'].str.lower() # return df # # Path: kquant_data/xio/csv.py # def read_datetime_dataframe(path, sep=','): # """ # 读取季报的公告日,即里面全是日期 # 注意:有些股票多个季度一起发,一般是公司出问题了,特别是600878,四个报告同一天发布 # 年报与一季报很有可能一起发 # # 读取ipo_date # :param path: # :param sep: # :return: # """ # try: # df = pd.read_csv(path, index_col=0, parse_dates=True, encoding='utf-8-sig', sep=sep) # except (FileNotFoundError, OSError): # return None # # df = df.stack(dropna=False) # df = pd.to_datetime(df) # df = df.unstack() # # return df # # Path: kquant_data/utils/xdatetime.py # def tic(): # """ # 对应MATLAB中的tic # :return: # """ # globals()['tt'] = time.clock() # # def toc(): # """ # 对应MATLAB中的toc # :return: # """ # t = time.clock() - globals()['tt'] # print('\nElapsed time: %.8f seconds\n' % t) # return t . Output only the next line.
ipo_last_trade['ipo_date'] = ipo_last_trade['ipo_date'].apply(lambda x: yyyyMMdd_2_datetime(x))
Here is a snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ 更新数据范围列表,用于下载数据时减少重复下载 日线数据路径是 IF/IF1804.h5 分钟数据路径是 IF1804/IF1804_20180226.h5 已经退市的合约,只要做过一次,后面就没有必要再做了 但数据还是有问题,不活跃的合约,最后几天完全没有行情了 """ # 解决Python 3.6的pandas不支持中文路径的问题 print(sys.getfilesystemencoding()) # 查看修改前的 try: sys._enablelegacywindowsfsencoding() # 修改 print(sys.getfilesystemencoding()) # 查看修改后的 except: pass <|code_end|> . Write the next line using the current file imports: import os import sys import pandas as pd from datetime import datetime from kquant_data.utils.xdatetime import yyyyMMddHHmm_2_datetime, yyyyMMdd_2_datetime from kquant_data.config import __CONFIG_H5_FUT_SECTOR_DIR__ from kquant_data.future.symbol import wind_code_2_InstrumentID from kquant_data.xio.csv import read_datetime_dataframe from kquant_data.utils.xdatetime import tic, toc and context from other files: # Path: kquant_data/utils/xdatetime.py # def yyyyMMddHHmm_2_datetime(dt): # """ # 输入一个长整型yyyyMMddhmm,返回对应的时间 # :param dt: # :return: # """ # dt = int(dt) # FIXME:在python2下会有问题吗? # (yyyyMMdd, hh) = divmod(dt, 10000) # (yyyy, MMdd) = divmod(yyyyMMdd, 10000) # (MM, dd) = divmod(MMdd, 100) # (hh, mm) = divmod(hh, 100) # # return datetime(yyyy, MM, dd, hh, mm) # # def yyyyMMdd_2_datetime(dt): # yyyyMMdd = int(dt) # (yyyy, MMdd) = divmod(yyyyMMdd, 10000) # (MM, dd) = divmod(MMdd, 100) # if yyyy == 0: # return None # # return datetime(yyyy, MM, dd, 0, 0) # # Path: kquant_data/config.py # __CONFIG_H5_FUT_SECTOR_DIR__ = os.path.join(__CONFIG_H5_FUT_DIR__, 'sectorconstituent') # # Path: kquant_data/future/symbol.py # def wind_code_2_InstrumentID(df, field): # sym_ex = df[field].str.split('.') # sym_ex = list(sym_ex) # sym_ex_df = pd.DataFrame(sym_ex, index=df.index) # sym_ex_df.columns = ['InstrumentID', 'exchange'] # df = pd.concat([df, sym_ex_df], axis=1) # df['lower'] = (df['exchange'] == 'SHF') | (df['exchange'] == 'DCE') | (df['exchange'] == 'INE') # df['InstrumentID'][df['lower']] = df['InstrumentID'].str.lower() # return df # # Path: kquant_data/xio/csv.py # def read_datetime_dataframe(path, sep=','): # """ # 读取季报的公告日,即里面全是日期 # 注意:有些股票多个季度一起发,一般是公司出问题了,特别是600878,四个报告同一天发布 # 年报与一季报很有可能一起发 # # 读取ipo_date # :param path: # :param sep: # :return: # """ # try: # df = pd.read_csv(path, index_col=0, parse_dates=True, encoding='utf-8-sig', sep=sep) # except (FileNotFoundError, OSError): # return None # # df = df.stack(dropna=False) # df = pd.to_datetime(df) # df = df.unstack() # # return df # # Path: kquant_data/utils/xdatetime.py # def tic(): # """ # 对应MATLAB中的tic # :return: # """ # globals()['tt'] = time.clock() # # def toc(): # """ # 对应MATLAB中的toc # :return: # """ # t = time.clock() - globals()['tt'] # print('\nElapsed time: %.8f seconds\n' % t) # return t , which may include functions, classes, or code. Output only the next line.
path_ipo_last_trade = os.path.join(__CONFIG_H5_FUT_SECTOR_DIR__, 'ipo_last_trade_trading.csv')
Predict the next line for this snippet: <|code_start|> dirpath_filename = os.path.join(_dirpath, filename) shotname, extension = os.path.splitext(filename) if extension != '.h5': continue try: row = date_table.loc[shotname] # 最后一天如何判断数据已经完成? if row['lasttrade_date'] == row['last']: print(row['last']) continue except: pass df = get_in_file_day(dirpath_filename, shotname, df) path = os.path.join(root_path, 'first_last.csv') df.index.name = 'product' df.to_csv(path) return df def CZCE_3to4(x): if x['exchange'] == 'CZC': x['InstrumentID'] = '%s%s%s' % (x['InstrumentID'][0:2], str(x['lasttrade_date'])[2], x['InstrumentID'][-3:]) return x def load_ipo_last_trade_trading(): df_csv = pd.read_csv(path_ipo_last_trade, encoding='utf-8-sig') <|code_end|> with the help of current file imports: import os import sys import pandas as pd from datetime import datetime from kquant_data.utils.xdatetime import yyyyMMddHHmm_2_datetime, yyyyMMdd_2_datetime from kquant_data.config import __CONFIG_H5_FUT_SECTOR_DIR__ from kquant_data.future.symbol import wind_code_2_InstrumentID from kquant_data.xio.csv import read_datetime_dataframe from kquant_data.utils.xdatetime import tic, toc and context from other files: # Path: kquant_data/utils/xdatetime.py # def yyyyMMddHHmm_2_datetime(dt): # """ # 输入一个长整型yyyyMMddhmm,返回对应的时间 # :param dt: # :return: # """ # dt = int(dt) # FIXME:在python2下会有问题吗? # (yyyyMMdd, hh) = divmod(dt, 10000) # (yyyy, MMdd) = divmod(yyyyMMdd, 10000) # (MM, dd) = divmod(MMdd, 100) # (hh, mm) = divmod(hh, 100) # # return datetime(yyyy, MM, dd, hh, mm) # # def yyyyMMdd_2_datetime(dt): # yyyyMMdd = int(dt) # (yyyy, MMdd) = divmod(yyyyMMdd, 10000) # (MM, dd) = divmod(MMdd, 100) # if yyyy == 0: # return None # # return datetime(yyyy, MM, dd, 0, 0) # # Path: kquant_data/config.py # __CONFIG_H5_FUT_SECTOR_DIR__ = os.path.join(__CONFIG_H5_FUT_DIR__, 'sectorconstituent') # # Path: kquant_data/future/symbol.py # def wind_code_2_InstrumentID(df, field): # sym_ex = df[field].str.split('.') # sym_ex = list(sym_ex) # sym_ex_df = pd.DataFrame(sym_ex, index=df.index) # sym_ex_df.columns = ['InstrumentID', 'exchange'] # df = pd.concat([df, sym_ex_df], axis=1) # df['lower'] = (df['exchange'] == 'SHF') | (df['exchange'] == 'DCE') | (df['exchange'] == 'INE') # df['InstrumentID'][df['lower']] = df['InstrumentID'].str.lower() # return df # # Path: kquant_data/xio/csv.py # def read_datetime_dataframe(path, sep=','): # """ # 读取季报的公告日,即里面全是日期 # 注意:有些股票多个季度一起发,一般是公司出问题了,特别是600878,四个报告同一天发布 # 年报与一季报很有可能一起发 # # 读取ipo_date # :param path: # :param sep: # :return: # """ # try: # df = pd.read_csv(path, index_col=0, parse_dates=True, encoding='utf-8-sig', sep=sep) # except (FileNotFoundError, OSError): # return None # # df = df.stack(dropna=False) # df = pd.to_datetime(df) # df = df.unstack() # # return df # # Path: kquant_data/utils/xdatetime.py # def tic(): # """ # 对应MATLAB中的tic # :return: # """ # globals()['tt'] = time.clock() # # def toc(): # """ # 对应MATLAB中的toc # :return: # """ # t = time.clock() - globals()['tt'] # print('\nElapsed time: %.8f seconds\n' % t) # return t , which may contain function names, class names, or code. Output only the next line.
df = wind_code_2_InstrumentID(df_csv, 'wind_code')
Here is a snippet: <|code_start|> df.index.name = 'product' df.to_csv(path) return df def CZCE_3to4(x): if x['exchange'] == 'CZC': x['InstrumentID'] = '%s%s%s' % (x['InstrumentID'][0:2], str(x['lasttrade_date'])[2], x['InstrumentID'][-3:]) return x def load_ipo_last_trade_trading(): df_csv = pd.read_csv(path_ipo_last_trade, encoding='utf-8-sig') df = wind_code_2_InstrumentID(df_csv, 'wind_code') df = df.apply(CZCE_3to4, axis=1) df = df.set_index(['InstrumentID']) return df if __name__ == '__main__': ipo_last_trade = load_ipo_last_trade_trading() ipo_last_trade['ipo_date'] = ipo_last_trade['ipo_date'].apply(lambda x: yyyyMMdd_2_datetime(x)) ipo_last_trade['lasttrade_date'] = ipo_last_trade['lasttrade_date'].apply(lambda x: yyyyMMdd_2_datetime(x)) ipo_last_trade['ipo_date'] = pd.to_datetime(ipo_last_trade['ipo_date']) ipo_last_trade['lasttrade_date'] = pd.to_datetime(ipo_last_trade['lasttrade_date']) root_path = r'D:\DATA_FUT_HDF5\Data_Wind\60' csv_path = os.path.join(root_path, 'first_last.csv') <|code_end|> . Write the next line using the current file imports: import os import sys import pandas as pd from datetime import datetime from kquant_data.utils.xdatetime import yyyyMMddHHmm_2_datetime, yyyyMMdd_2_datetime from kquant_data.config import __CONFIG_H5_FUT_SECTOR_DIR__ from kquant_data.future.symbol import wind_code_2_InstrumentID from kquant_data.xio.csv import read_datetime_dataframe from kquant_data.utils.xdatetime import tic, toc and context from other files: # Path: kquant_data/utils/xdatetime.py # def yyyyMMddHHmm_2_datetime(dt): # """ # 输入一个长整型yyyyMMddhmm,返回对应的时间 # :param dt: # :return: # """ # dt = int(dt) # FIXME:在python2下会有问题吗? # (yyyyMMdd, hh) = divmod(dt, 10000) # (yyyy, MMdd) = divmod(yyyyMMdd, 10000) # (MM, dd) = divmod(MMdd, 100) # (hh, mm) = divmod(hh, 100) # # return datetime(yyyy, MM, dd, hh, mm) # # def yyyyMMdd_2_datetime(dt): # yyyyMMdd = int(dt) # (yyyy, MMdd) = divmod(yyyyMMdd, 10000) # (MM, dd) = divmod(MMdd, 100) # if yyyy == 0: # return None # # return datetime(yyyy, MM, dd, 0, 0) # # Path: kquant_data/config.py # __CONFIG_H5_FUT_SECTOR_DIR__ = os.path.join(__CONFIG_H5_FUT_DIR__, 'sectorconstituent') # # Path: kquant_data/future/symbol.py # def wind_code_2_InstrumentID(df, field): # sym_ex = df[field].str.split('.') # sym_ex = list(sym_ex) # sym_ex_df = pd.DataFrame(sym_ex, index=df.index) # sym_ex_df.columns = ['InstrumentID', 'exchange'] # df = pd.concat([df, sym_ex_df], axis=1) # df['lower'] = (df['exchange'] == 'SHF') | (df['exchange'] == 'DCE') | (df['exchange'] == 'INE') # df['InstrumentID'][df['lower']] = df['InstrumentID'].str.lower() # return df # # Path: kquant_data/xio/csv.py # def read_datetime_dataframe(path, sep=','): # """ # 读取季报的公告日,即里面全是日期 # 注意:有些股票多个季度一起发,一般是公司出问题了,特别是600878,四个报告同一天发布 # 年报与一季报很有可能一起发 # # 读取ipo_date # :param path: # :param sep: # :return: # """ # try: # df = pd.read_csv(path, index_col=0, parse_dates=True, encoding='utf-8-sig', sep=sep) # except (FileNotFoundError, OSError): # return None # # df = df.stack(dropna=False) # df = pd.to_datetime(df) # df = df.unstack() # # return df # # Path: kquant_data/utils/xdatetime.py # def tic(): # """ # 对应MATLAB中的tic # :return: # """ # globals()['tt'] = time.clock() # # def toc(): # """ # 对应MATLAB中的toc # :return: # """ # t = time.clock() - globals()['tt'] # print('\nElapsed time: %.8f seconds\n' % t) # return t , which may include functions, classes, or code. Output only the next line.
first_last = read_datetime_dataframe(csv_path)
Predict the next line after this snippet: <|code_start|> if x['exchange'] == 'CZC': x['InstrumentID'] = '%s%s%s' % (x['InstrumentID'][0:2], str(x['lasttrade_date'])[2], x['InstrumentID'][-3:]) return x def load_ipo_last_trade_trading(): df_csv = pd.read_csv(path_ipo_last_trade, encoding='utf-8-sig') df = wind_code_2_InstrumentID(df_csv, 'wind_code') df = df.apply(CZCE_3to4, axis=1) df = df.set_index(['InstrumentID']) return df if __name__ == '__main__': ipo_last_trade = load_ipo_last_trade_trading() ipo_last_trade['ipo_date'] = ipo_last_trade['ipo_date'].apply(lambda x: yyyyMMdd_2_datetime(x)) ipo_last_trade['lasttrade_date'] = ipo_last_trade['lasttrade_date'].apply(lambda x: yyyyMMdd_2_datetime(x)) ipo_last_trade['ipo_date'] = pd.to_datetime(ipo_last_trade['ipo_date']) ipo_last_trade['lasttrade_date'] = pd.to_datetime(ipo_last_trade['lasttrade_date']) root_path = r'D:\DATA_FUT_HDF5\Data_Wind\60' csv_path = os.path.join(root_path, 'first_last.csv') first_last = read_datetime_dataframe(csv_path) if first_last is None: first_last = pd.DataFrame(columns=['first', 'last']) date_table = ipo_last_trade.merge(first_last, how='inner', left_index=True, right_index=True) <|code_end|> using the current file's imports: import os import sys import pandas as pd from datetime import datetime from kquant_data.utils.xdatetime import yyyyMMddHHmm_2_datetime, yyyyMMdd_2_datetime from kquant_data.config import __CONFIG_H5_FUT_SECTOR_DIR__ from kquant_data.future.symbol import wind_code_2_InstrumentID from kquant_data.xio.csv import read_datetime_dataframe from kquant_data.utils.xdatetime import tic, toc and any relevant context from other files: # Path: kquant_data/utils/xdatetime.py # def yyyyMMddHHmm_2_datetime(dt): # """ # 输入一个长整型yyyyMMddhmm,返回对应的时间 # :param dt: # :return: # """ # dt = int(dt) # FIXME:在python2下会有问题吗? # (yyyyMMdd, hh) = divmod(dt, 10000) # (yyyy, MMdd) = divmod(yyyyMMdd, 10000) # (MM, dd) = divmod(MMdd, 100) # (hh, mm) = divmod(hh, 100) # # return datetime(yyyy, MM, dd, hh, mm) # # def yyyyMMdd_2_datetime(dt): # yyyyMMdd = int(dt) # (yyyy, MMdd) = divmod(yyyyMMdd, 10000) # (MM, dd) = divmod(MMdd, 100) # if yyyy == 0: # return None # # return datetime(yyyy, MM, dd, 0, 0) # # Path: kquant_data/config.py # __CONFIG_H5_FUT_SECTOR_DIR__ = os.path.join(__CONFIG_H5_FUT_DIR__, 'sectorconstituent') # # Path: kquant_data/future/symbol.py # def wind_code_2_InstrumentID(df, field): # sym_ex = df[field].str.split('.') # sym_ex = list(sym_ex) # sym_ex_df = pd.DataFrame(sym_ex, index=df.index) # sym_ex_df.columns = ['InstrumentID', 'exchange'] # df = pd.concat([df, sym_ex_df], axis=1) # df['lower'] = (df['exchange'] == 'SHF') | (df['exchange'] == 'DCE') | (df['exchange'] == 'INE') # df['InstrumentID'][df['lower']] = df['InstrumentID'].str.lower() # return df # # Path: kquant_data/xio/csv.py # def read_datetime_dataframe(path, sep=','): # """ # 读取季报的公告日,即里面全是日期 # 注意:有些股票多个季度一起发,一般是公司出问题了,特别是600878,四个报告同一天发布 # 年报与一季报很有可能一起发 # # 读取ipo_date # :param path: # :param sep: # :return: # """ # try: # df = pd.read_csv(path, index_col=0, parse_dates=True, encoding='utf-8-sig', sep=sep) # except (FileNotFoundError, OSError): # return None # # df = df.stack(dropna=False) # df = pd.to_datetime(df) # df = df.unstack() # # return df # # Path: kquant_data/utils/xdatetime.py # def tic(): # """ # 对应MATLAB中的tic # :return: # """ # globals()['tt'] = time.clock() # # def toc(): # """ # 对应MATLAB中的toc # :return: # """ # t = time.clock() - globals()['tt'] # print('\nElapsed time: %.8f seconds\n' % t) # return t . Output only the next line.
tic()
Given the following code snippet before the placeholder: <|code_start|> return x def load_ipo_last_trade_trading(): df_csv = pd.read_csv(path_ipo_last_trade, encoding='utf-8-sig') df = wind_code_2_InstrumentID(df_csv, 'wind_code') df = df.apply(CZCE_3to4, axis=1) df = df.set_index(['InstrumentID']) return df if __name__ == '__main__': ipo_last_trade = load_ipo_last_trade_trading() ipo_last_trade['ipo_date'] = ipo_last_trade['ipo_date'].apply(lambda x: yyyyMMdd_2_datetime(x)) ipo_last_trade['lasttrade_date'] = ipo_last_trade['lasttrade_date'].apply(lambda x: yyyyMMdd_2_datetime(x)) ipo_last_trade['ipo_date'] = pd.to_datetime(ipo_last_trade['ipo_date']) ipo_last_trade['lasttrade_date'] = pd.to_datetime(ipo_last_trade['lasttrade_date']) root_path = r'D:\DATA_FUT_HDF5\Data_Wind\60' csv_path = os.path.join(root_path, 'first_last.csv') first_last = read_datetime_dataframe(csv_path) if first_last is None: first_last = pd.DataFrame(columns=['first', 'last']) date_table = ipo_last_trade.merge(first_last, how='inner', left_index=True, right_index=True) tic() df = get_first_last_min(root_path, date_table, first_last) <|code_end|> , predict the next line using imports from the current file: import os import sys import pandas as pd from datetime import datetime from kquant_data.utils.xdatetime import yyyyMMddHHmm_2_datetime, yyyyMMdd_2_datetime from kquant_data.config import __CONFIG_H5_FUT_SECTOR_DIR__ from kquant_data.future.symbol import wind_code_2_InstrumentID from kquant_data.xio.csv import read_datetime_dataframe from kquant_data.utils.xdatetime import tic, toc and context including class names, function names, and sometimes code from other files: # Path: kquant_data/utils/xdatetime.py # def yyyyMMddHHmm_2_datetime(dt): # """ # 输入一个长整型yyyyMMddhmm,返回对应的时间 # :param dt: # :return: # """ # dt = int(dt) # FIXME:在python2下会有问题吗? # (yyyyMMdd, hh) = divmod(dt, 10000) # (yyyy, MMdd) = divmod(yyyyMMdd, 10000) # (MM, dd) = divmod(MMdd, 100) # (hh, mm) = divmod(hh, 100) # # return datetime(yyyy, MM, dd, hh, mm) # # def yyyyMMdd_2_datetime(dt): # yyyyMMdd = int(dt) # (yyyy, MMdd) = divmod(yyyyMMdd, 10000) # (MM, dd) = divmod(MMdd, 100) # if yyyy == 0: # return None # # return datetime(yyyy, MM, dd, 0, 0) # # Path: kquant_data/config.py # __CONFIG_H5_FUT_SECTOR_DIR__ = os.path.join(__CONFIG_H5_FUT_DIR__, 'sectorconstituent') # # Path: kquant_data/future/symbol.py # def wind_code_2_InstrumentID(df, field): # sym_ex = df[field].str.split('.') # sym_ex = list(sym_ex) # sym_ex_df = pd.DataFrame(sym_ex, index=df.index) # sym_ex_df.columns = ['InstrumentID', 'exchange'] # df = pd.concat([df, sym_ex_df], axis=1) # df['lower'] = (df['exchange'] == 'SHF') | (df['exchange'] == 'DCE') | (df['exchange'] == 'INE') # df['InstrumentID'][df['lower']] = df['InstrumentID'].str.lower() # return df # # Path: kquant_data/xio/csv.py # def read_datetime_dataframe(path, sep=','): # """ # 读取季报的公告日,即里面全是日期 # 注意:有些股票多个季度一起发,一般是公司出问题了,特别是600878,四个报告同一天发布 # 年报与一季报很有可能一起发 # # 读取ipo_date # :param path: # :param sep: # :return: # """ # try: # df = pd.read_csv(path, index_col=0, parse_dates=True, encoding='utf-8-sig', sep=sep) # except (FileNotFoundError, OSError): # return None # # df = df.stack(dropna=False) # df = pd.to_datetime(df) # df = df.unstack() # # return df # # Path: kquant_data/utils/xdatetime.py # def tic(): # """ # 对应MATLAB中的tic # :return: # """ # globals()['tt'] = time.clock() # # def toc(): # """ # 对应MATLAB中的toc # :return: # """ # t = time.clock() - globals()['tt'] # print('\nElapsed time: %.8f seconds\n' % t) # return t . Output only the next line.
toc()
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ 调用wss函数的部分 """ def download_fellow_listeddate(w, wind_codes, year): """ 增发上市日 本想通过它来确认股本,但实际发现还是有一些差别,可能需要补充多下一些数据 :param w: :param wind_codes: :param year: :return: """ <|code_end|> with the help of current file imports: from WindPy import w from .utils import asDateTime from ..utils.xdatetime import datetime_2_yyyy from ..utils.xdatetime import datetime_2_yyyyMMdd import os import pandas as pd and context from other files: # Path: kquant_data/wind/utils.py # def asDateTime(v, asDate=False): # """ # 万得中读出来的时间总多5ms,覆写这部分 # w.asDateTime = asDateTime # w.start() # :param v: # :param asDate: # :return: # """ # # return datetime(1899, 12, 30, 0, 0, 0, 0) + timedelta(v + 0.005 / 3600 / 24) # return datetime(1899, 12, 30, 0, 0, 0, 0) + timedelta(v) # # Path: kquant_data/utils/xdatetime.py # def datetime_2_yyyy(dt): # """ # 将时间转换成float类型 # :param dt: # :return: # """ # t = dt.timetuple() # return t.tm_year # # Path: kquant_data/utils/xdatetime.py # def datetime_2_yyyyMMdd(dt): # """ # 将时间转换成float类型 # :param dt: # :return: # """ # t = dt.timetuple() # return int((t.tm_year * 10000.0 + t.tm_mon * 100 + t.tm_mday)) , which may contain function names, class names, or code. Output only the next line.
w.asDateTime = asDateTime
Given the following code snippet before the placeholder: <|code_start|> w_wss_data = w.wss(wind_codes, "sec_name,ipo_date,lasttrade_date,lasttradingdate", "") grid = w_wss_data.Data # T1803一类的会被当成时间,需要提前转置 new_grid = [[row[i] for row in grid] for i in range(len(grid[0]))] df = pd.DataFrame(new_grid) df.columns = ['sec_name', 'ipo_date', 'lasttrade_date', 'lasttradingdate'] df.index = w_wss_data.Codes df.index.name = 'wind_code' df['ipo_date'] = df['ipo_date'].apply(datetime_2_yyyyMMdd) df['lasttrade_date'] = df['lasttrade_date'].apply(datetime_2_yyyyMMdd) df['lasttradingdate'] = df['lasttradingdate'].apply(datetime_2_yyyyMMdd) df.replace(18991230, 0, inplace=True) return df def download_test(w): """ 有问题,现在没法用 :param w: :return: """ df = pd.read_csv(r'D:\DATA_STK_HDF5\factor\seoimplementation.csv', parse_dates=True, index_col=0, dtype={'issue_code': str}) df['seo_anncedate'] = pd.to_datetime(df['seo_anncedate']) <|code_end|> , predict the next line using imports from the current file: from WindPy import w from .utils import asDateTime from ..utils.xdatetime import datetime_2_yyyy from ..utils.xdatetime import datetime_2_yyyyMMdd import os import pandas as pd and context including class names, function names, and sometimes code from other files: # Path: kquant_data/wind/utils.py # def asDateTime(v, asDate=False): # """ # 万得中读出来的时间总多5ms,覆写这部分 # w.asDateTime = asDateTime # w.start() # :param v: # :param asDate: # :return: # """ # # return datetime(1899, 12, 30, 0, 0, 0, 0) + timedelta(v + 0.005 / 3600 / 24) # return datetime(1899, 12, 30, 0, 0, 0, 0) + timedelta(v) # # Path: kquant_data/utils/xdatetime.py # def datetime_2_yyyy(dt): # """ # 将时间转换成float类型 # :param dt: # :return: # """ # t = dt.timetuple() # return t.tm_year # # Path: kquant_data/utils/xdatetime.py # def datetime_2_yyyyMMdd(dt): # """ # 将时间转换成float类型 # :param dt: # :return: # """ # t = dt.timetuple() # return int((t.tm_year * 10000.0 + t.tm_mon * 100 + t.tm_mday)) . Output only the next line.
df['yyyy'] = df['seo_anncedate'].apply(datetime_2_yyyy)
Here is a snippet: <|code_start|> 本想通过它来确认股本,但实际发现还是有一些差别,可能需要补充多下一些数据 :param w: :param wind_codes: :param year: :return: """ w.asDateTime = asDateTime w_wss_data = w.wss(wind_codes, "fellow_listeddate", "year=%s" % year) df = pd.DataFrame(w_wss_data.Data) df = df.T df.columns = ['fellow_listeddate'] df.index = w_wss_data.Codes return df def download_ipo_last_trade_trading(w, wind_codes): # 黄金从20130625开始将最小变动价位从0.01调整成了0.05,但从万得上查出来还是完全一样,所以没有必要记录mfprice # 郑商所在修改合约交易单位时都改了合约代码,所以没有必要记录contractmultiplier w.asDateTime = asDateTime w_wss_data = w.wss(wind_codes, "sec_name,ipo_date,lasttrade_date,lasttradingdate", "") grid = w_wss_data.Data # T1803一类的会被当成时间,需要提前转置 new_grid = [[row[i] for row in grid] for i in range(len(grid[0]))] df = pd.DataFrame(new_grid) df.columns = ['sec_name', 'ipo_date', 'lasttrade_date', 'lasttradingdate'] df.index = w_wss_data.Codes df.index.name = 'wind_code' <|code_end|> . Write the next line using the current file imports: from WindPy import w from .utils import asDateTime from ..utils.xdatetime import datetime_2_yyyy from ..utils.xdatetime import datetime_2_yyyyMMdd import os import pandas as pd and context from other files: # Path: kquant_data/wind/utils.py # def asDateTime(v, asDate=False): # """ # 万得中读出来的时间总多5ms,覆写这部分 # w.asDateTime = asDateTime # w.start() # :param v: # :param asDate: # :return: # """ # # return datetime(1899, 12, 30, 0, 0, 0, 0) + timedelta(v + 0.005 / 3600 / 24) # return datetime(1899, 12, 30, 0, 0, 0, 0) + timedelta(v) # # Path: kquant_data/utils/xdatetime.py # def datetime_2_yyyy(dt): # """ # 将时间转换成float类型 # :param dt: # :return: # """ # t = dt.timetuple() # return t.tm_year # # Path: kquant_data/utils/xdatetime.py # def datetime_2_yyyyMMdd(dt): # """ # 将时间转换成float类型 # :param dt: # :return: # """ # t = dt.timetuple() # return int((t.tm_year * 10000.0 + t.tm_mon * 100 + t.tm_mday)) , which may include functions, classes, or code. Output only the next line.
df['ipo_date'] = df['ipo_date'].apply(datetime_2_yyyyMMdd)
Next line prediction: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ 增量下载期货仓单数据 """ if __name__ == '__main__': w.start() date_str = datetime.today().strftime('%Y-%m-%d') windcodes = get_all_products_wind() root_path = os.path.join(__CONFIG_H5_FUT_DATA_DIR__, "st_stock") # 下载仓单数据 <|code_end|> . Use current file imports: (from WindPy import w from datetime import datetime from kquant_data.wind_resume.wsd import resume_download_daily_many_to_one_file from kquant_data.future.symbol import get_all_products_wind from kquant_data.config import __CONFIG_H5_FUT_DATA_DIR__ import os) and context including class names, function names, or small code snippets from other files: # Path: kquant_data/wind_resume/wsd.py # def resume_download_daily_many_to_one_file( # w, # wind_codes, # field, # dtype, # enddate, # root_path, # option='unit=1;rptType=1;Period=Q;Days=Alldays', # default_start_date='2000-01-01'): # """ # 增量下载,下载每个季度因子到一个文件,由于季度使用日历日 # 按日下数据也没有关系,一般是每天都不一样才使用,这时使用交易日 # # # 对于有些因子,可能公司有问题,很久不公布,可能过了一年都不公布 # # 这种一般是退市或停牌了,对于这些,找一个时间更新一下即可 # # 补最近的两个报告 # dr = pd.date_range(end=datetime.datetime.today().date(), periods=4, freq='Q') # new_end_str = dr[-1].strftime('%Y-%m-%d') # :param w: # :param wind_codes: # :param field: # :param enddate: # :param option: # :param root_path: # :return: # """ # df_old = None # df_old_output = None # new_end_str = enddate # # path = os.path.join(root_path, '%s.csv' % field) # # 补数据时,将半年内的数据再重下一次 # try: # df_old = pd.read_csv(path, index_col=0, parse_dates=True, encoding='utf-8-sig') # df_old_output = df_old.copy() # # # 如果最后日子不相等,表示是以前下的,需要多考虑一天 # old_end_str = df_old.index[-1].strftime('%Y-%m-%d') # back = -2 # if old_end_str != new_end_str: # back = -3 # new_start_str = df_old.index[back].strftime('%Y-%m-%d') # df_old = df_old[:back] # except: # # 打开失败,使用老数据 # new_start_str = default_start_date # # df_new = download_daily_between(w, wind_codes, field, # new_start_str, new_end_str, option) # # if df_old is None: # df = df_new # else: # # 合并,第一,需要两者列相同 # df = pd.DataFrame(index=df_old.index, columns=df_new.columns) # # 这里有可能重复 # df[df_old.columns] = df_old # df = pd.concat([df, df_new]) # # # 数据内容实际是时间,需要强行转换,这样后面写csv时就不会出现后面一段了 # # 排序会不会出问题呢? # if dtype == np.datetime64: # df = df.stack(dropna=False) # df = pd.to_datetime(df) # df = df.unstack() # # df = df[wind_codes] # write_data_dataframe(path, df) # print(path) # # 输出这前后两个DataFrame可以提供给外界判断是否有新数据要下载 # return df_old_output, df # # Path: kquant_data/future/symbol.py # def get_all_products_wind(): # _lst = get_all_products() # __lst = [get_wind_code(x).upper() for x in _lst] # return __lst # # Path: kquant_data/config.py # __CONFIG_H5_FUT_DATA_DIR__ = os.path.join(__CONFIG_H5_FUT_DIR__, 'data') . Output only the next line.
df_old_output, df = resume_download_daily_many_to_one_file(w, windcodes, field='st_stock', dtype=None,
Next line prediction: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ 增量下载期货仓单数据 """ if __name__ == '__main__': w.start() date_str = datetime.today().strftime('%Y-%m-%d') <|code_end|> . Use current file imports: (from WindPy import w from datetime import datetime from kquant_data.wind_resume.wsd import resume_download_daily_many_to_one_file from kquant_data.future.symbol import get_all_products_wind from kquant_data.config import __CONFIG_H5_FUT_DATA_DIR__ import os) and context including class names, function names, or small code snippets from other files: # Path: kquant_data/wind_resume/wsd.py # def resume_download_daily_many_to_one_file( # w, # wind_codes, # field, # dtype, # enddate, # root_path, # option='unit=1;rptType=1;Period=Q;Days=Alldays', # default_start_date='2000-01-01'): # """ # 增量下载,下载每个季度因子到一个文件,由于季度使用日历日 # 按日下数据也没有关系,一般是每天都不一样才使用,这时使用交易日 # # # 对于有些因子,可能公司有问题,很久不公布,可能过了一年都不公布 # # 这种一般是退市或停牌了,对于这些,找一个时间更新一下即可 # # 补最近的两个报告 # dr = pd.date_range(end=datetime.datetime.today().date(), periods=4, freq='Q') # new_end_str = dr[-1].strftime('%Y-%m-%d') # :param w: # :param wind_codes: # :param field: # :param enddate: # :param option: # :param root_path: # :return: # """ # df_old = None # df_old_output = None # new_end_str = enddate # # path = os.path.join(root_path, '%s.csv' % field) # # 补数据时,将半年内的数据再重下一次 # try: # df_old = pd.read_csv(path, index_col=0, parse_dates=True, encoding='utf-8-sig') # df_old_output = df_old.copy() # # # 如果最后日子不相等,表示是以前下的,需要多考虑一天 # old_end_str = df_old.index[-1].strftime('%Y-%m-%d') # back = -2 # if old_end_str != new_end_str: # back = -3 # new_start_str = df_old.index[back].strftime('%Y-%m-%d') # df_old = df_old[:back] # except: # # 打开失败,使用老数据 # new_start_str = default_start_date # # df_new = download_daily_between(w, wind_codes, field, # new_start_str, new_end_str, option) # # if df_old is None: # df = df_new # else: # # 合并,第一,需要两者列相同 # df = pd.DataFrame(index=df_old.index, columns=df_new.columns) # # 这里有可能重复 # df[df_old.columns] = df_old # df = pd.concat([df, df_new]) # # # 数据内容实际是时间,需要强行转换,这样后面写csv时就不会出现后面一段了 # # 排序会不会出问题呢? # if dtype == np.datetime64: # df = df.stack(dropna=False) # df = pd.to_datetime(df) # df = df.unstack() # # df = df[wind_codes] # write_data_dataframe(path, df) # print(path) # # 输出这前后两个DataFrame可以提供给外界判断是否有新数据要下载 # return df_old_output, df # # Path: kquant_data/future/symbol.py # def get_all_products_wind(): # _lst = get_all_products() # __lst = [get_wind_code(x).upper() for x in _lst] # return __lst # # Path: kquant_data/config.py # __CONFIG_H5_FUT_DATA_DIR__ = os.path.join(__CONFIG_H5_FUT_DIR__, 'data') . Output only the next line.
windcodes = get_all_products_wind()
Given the code snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ 增量下载期货仓单数据 """ if __name__ == '__main__': w.start() date_str = datetime.today().strftime('%Y-%m-%d') windcodes = get_all_products_wind() <|code_end|> , generate the next line using the imports in this file: from WindPy import w from datetime import datetime from kquant_data.wind_resume.wsd import resume_download_daily_many_to_one_file from kquant_data.future.symbol import get_all_products_wind from kquant_data.config import __CONFIG_H5_FUT_DATA_DIR__ import os and context (functions, classes, or occasionally code) from other files: # Path: kquant_data/wind_resume/wsd.py # def resume_download_daily_many_to_one_file( # w, # wind_codes, # field, # dtype, # enddate, # root_path, # option='unit=1;rptType=1;Period=Q;Days=Alldays', # default_start_date='2000-01-01'): # """ # 增量下载,下载每个季度因子到一个文件,由于季度使用日历日 # 按日下数据也没有关系,一般是每天都不一样才使用,这时使用交易日 # # # 对于有些因子,可能公司有问题,很久不公布,可能过了一年都不公布 # # 这种一般是退市或停牌了,对于这些,找一个时间更新一下即可 # # 补最近的两个报告 # dr = pd.date_range(end=datetime.datetime.today().date(), periods=4, freq='Q') # new_end_str = dr[-1].strftime('%Y-%m-%d') # :param w: # :param wind_codes: # :param field: # :param enddate: # :param option: # :param root_path: # :return: # """ # df_old = None # df_old_output = None # new_end_str = enddate # # path = os.path.join(root_path, '%s.csv' % field) # # 补数据时,将半年内的数据再重下一次 # try: # df_old = pd.read_csv(path, index_col=0, parse_dates=True, encoding='utf-8-sig') # df_old_output = df_old.copy() # # # 如果最后日子不相等,表示是以前下的,需要多考虑一天 # old_end_str = df_old.index[-1].strftime('%Y-%m-%d') # back = -2 # if old_end_str != new_end_str: # back = -3 # new_start_str = df_old.index[back].strftime('%Y-%m-%d') # df_old = df_old[:back] # except: # # 打开失败,使用老数据 # new_start_str = default_start_date # # df_new = download_daily_between(w, wind_codes, field, # new_start_str, new_end_str, option) # # if df_old is None: # df = df_new # else: # # 合并,第一,需要两者列相同 # df = pd.DataFrame(index=df_old.index, columns=df_new.columns) # # 这里有可能重复 # df[df_old.columns] = df_old # df = pd.concat([df, df_new]) # # # 数据内容实际是时间,需要强行转换,这样后面写csv时就不会出现后面一段了 # # 排序会不会出问题呢? # if dtype == np.datetime64: # df = df.stack(dropna=False) # df = pd.to_datetime(df) # df = df.unstack() # # df = df[wind_codes] # write_data_dataframe(path, df) # print(path) # # 输出这前后两个DataFrame可以提供给外界判断是否有新数据要下载 # return df_old_output, df # # Path: kquant_data/future/symbol.py # def get_all_products_wind(): # _lst = get_all_products() # __lst = [get_wind_code(x).upper() for x in _lst] # return __lst # # Path: kquant_data/config.py # __CONFIG_H5_FUT_DATA_DIR__ = os.path.join(__CONFIG_H5_FUT_DIR__, 'data') . Output only the next line.
root_path = os.path.join(__CONFIG_H5_FUT_DATA_DIR__, "st_stock")
Given snippet: <|code_start|>""" 下载财报一类的信息 """ if __name__ == '__main__': w.start() path = os.path.join(__CONFIG_H5_STK_DIR__, '1day', 'Symbol.csv') Symbols = all_instruments(path) wind_codes = list(Symbols['wind_code']) # 下载多天数据,以另一数据做为标准来下载 # 比如交易数据是10月8号,那就得取10月7号,然后再平移到8号,如果7号没有数据那就得9月30号 path = os.path.join(__CONFIG_H5_STK_FACTOR_DIR__, 'roe.csv') date_index = read_data_dataframe(path) field = 'pb_lf' df = None for i in range(len(date_index)): print(date_index.index[i]) date_str = date_index.index[i].strftime('%Y-%m-%d') df_new = download_daily_at(w, wind_codes, field, date_str, "Days=Alldays") if df is None: df = df_new else: df = pd.concat([df, df_new]) path = os.path.join(__CONFIG_H5_STK_FACTOR_DIR__, '%s.csv' % field) <|code_end|> , continue by predicting the next line. Consider current file imports: import os import pandas as pd from WindPy import w from kquant_data.xio.csv import write_data_dataframe, read_data_dataframe from kquant_data.api import all_instruments from kquant_data.wind_resume.wsd import download_daily_at from kquant_data.config import __CONFIG_H5_STK_FACTOR_DIR__, __CONFIG_H5_STK_DIR__ and context: # Path: kquant_data/xio/csv.py # def write_data_dataframe(path, df, date_format='%Y-%m-%d'): # """ # 写入数据 # :param path: # :param df: # :return: # """ # df.to_csv(path, date_format=date_format, encoding='utf-8-sig') # # def read_data_dataframe(path, sep=','): # """ # 读取季报的公告日 # 注意:有些股票多个季度一起发,一般是公司出问题了,特别是600878,四个报告同一天发布 # 年报与一季报很有可能一起发 # :param path: # :param sep: # :return: # """ # try: # df = pd.read_csv(path, index_col=0, parse_dates=True, encoding='utf-8-sig', sep=sep) # except (FileNotFoundError, OSError): # return None # # return df # # Path: kquant_data/api.py # def all_instruments(path=None, type=None): # """ # 得到合约列表 # :param type: # :return: # """ # if path is None: # path = os.path.join(__CONFIG_H5_STK_DIR__, "daily", 'Symbol.csv') # # df = pd.read_csv(path, dtype={'code': str}) # # return df # # Path: kquant_data/wind_resume/wsd.py # def resume_download_daily_many_to_one_file( # w, # wind_codes, # field, # dtype, # enddate, # root_path, # option='unit=1;rptType=1;Period=Q;Days=Alldays', # default_start_date='2000-01-01'): # def resume_download_daily_one_to_one_file( # w, # symbol, # ipo_date, # field, # trading_days, # root_path): # def resume_download_daily_to_many_files( # w, # trading_days, # ipo_date, # root_path, # field='total_shares'): # def resume_download_delist_date( # w, # wind_codes, # root_path, # field='delist_date', # dtype=np.datetime64): # def combine_func(x1, x2): # def resume_download_financial_report_data_daily_latest( # w, # wind_codes, # trading_days, # root_path, # field='total_shares', # date_str=datetime.today().strftime('%Y-%m-%d'), # option=""): # def resume_download_financial_report_quarter(w, wind_codes, root_path, fields=['stm_issuingdate'], dtype=np.datetime64): # # Path: kquant_data/config.py # __CONFIG_H5_STK_FACTOR_DIR__ = os.path.join(__CONFIG_H5_STK_DIR__, 'factor') # # __CONFIG_H5_STK_DIR__ = r'D:\DATA_STK' which might include code, classes, or functions. Output only the next line.
write_data_dataframe(path, df)
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ 下载财报一类的信息 """ if __name__ == '__main__': w.start() path = os.path.join(__CONFIG_H5_STK_DIR__, '1day', 'Symbol.csv') Symbols = all_instruments(path) wind_codes = list(Symbols['wind_code']) # 下载多天数据,以另一数据做为标准来下载 # 比如交易数据是10月8号,那就得取10月7号,然后再平移到8号,如果7号没有数据那就得9月30号 path = os.path.join(__CONFIG_H5_STK_FACTOR_DIR__, 'roe.csv') <|code_end|> with the help of current file imports: import os import pandas as pd from WindPy import w from kquant_data.xio.csv import write_data_dataframe, read_data_dataframe from kquant_data.api import all_instruments from kquant_data.wind_resume.wsd import download_daily_at from kquant_data.config import __CONFIG_H5_STK_FACTOR_DIR__, __CONFIG_H5_STK_DIR__ and context from other files: # Path: kquant_data/xio/csv.py # def write_data_dataframe(path, df, date_format='%Y-%m-%d'): # """ # 写入数据 # :param path: # :param df: # :return: # """ # df.to_csv(path, date_format=date_format, encoding='utf-8-sig') # # def read_data_dataframe(path, sep=','): # """ # 读取季报的公告日 # 注意:有些股票多个季度一起发,一般是公司出问题了,特别是600878,四个报告同一天发布 # 年报与一季报很有可能一起发 # :param path: # :param sep: # :return: # """ # try: # df = pd.read_csv(path, index_col=0, parse_dates=True, encoding='utf-8-sig', sep=sep) # except (FileNotFoundError, OSError): # return None # # return df # # Path: kquant_data/api.py # def all_instruments(path=None, type=None): # """ # 得到合约列表 # :param type: # :return: # """ # if path is None: # path = os.path.join(__CONFIG_H5_STK_DIR__, "daily", 'Symbol.csv') # # df = pd.read_csv(path, dtype={'code': str}) # # return df # # Path: kquant_data/wind_resume/wsd.py # def resume_download_daily_many_to_one_file( # w, # wind_codes, # field, # dtype, # enddate, # root_path, # option='unit=1;rptType=1;Period=Q;Days=Alldays', # default_start_date='2000-01-01'): # def resume_download_daily_one_to_one_file( # w, # symbol, # ipo_date, # field, # trading_days, # root_path): # def resume_download_daily_to_many_files( # w, # trading_days, # ipo_date, # root_path, # field='total_shares'): # def resume_download_delist_date( # w, # wind_codes, # root_path, # field='delist_date', # dtype=np.datetime64): # def combine_func(x1, x2): # def resume_download_financial_report_data_daily_latest( # w, # wind_codes, # trading_days, # root_path, # field='total_shares', # date_str=datetime.today().strftime('%Y-%m-%d'), # option=""): # def resume_download_financial_report_quarter(w, wind_codes, root_path, fields=['stm_issuingdate'], dtype=np.datetime64): # # Path: kquant_data/config.py # __CONFIG_H5_STK_FACTOR_DIR__ = os.path.join(__CONFIG_H5_STK_DIR__, 'factor') # # __CONFIG_H5_STK_DIR__ = r'D:\DATA_STK' , which may contain function names, class names, or code. Output only the next line.
date_index = read_data_dataframe(path)
Given the code snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ 下载财报一类的信息 """ if __name__ == '__main__': w.start() path = os.path.join(__CONFIG_H5_STK_DIR__, '1day', 'Symbol.csv') <|code_end|> , generate the next line using the imports in this file: import os import pandas as pd from WindPy import w from kquant_data.xio.csv import write_data_dataframe, read_data_dataframe from kquant_data.api import all_instruments from kquant_data.wind_resume.wsd import download_daily_at from kquant_data.config import __CONFIG_H5_STK_FACTOR_DIR__, __CONFIG_H5_STK_DIR__ and context (functions, classes, or occasionally code) from other files: # Path: kquant_data/xio/csv.py # def write_data_dataframe(path, df, date_format='%Y-%m-%d'): # """ # 写入数据 # :param path: # :param df: # :return: # """ # df.to_csv(path, date_format=date_format, encoding='utf-8-sig') # # def read_data_dataframe(path, sep=','): # """ # 读取季报的公告日 # 注意:有些股票多个季度一起发,一般是公司出问题了,特别是600878,四个报告同一天发布 # 年报与一季报很有可能一起发 # :param path: # :param sep: # :return: # """ # try: # df = pd.read_csv(path, index_col=0, parse_dates=True, encoding='utf-8-sig', sep=sep) # except (FileNotFoundError, OSError): # return None # # return df # # Path: kquant_data/api.py # def all_instruments(path=None, type=None): # """ # 得到合约列表 # :param type: # :return: # """ # if path is None: # path = os.path.join(__CONFIG_H5_STK_DIR__, "daily", 'Symbol.csv') # # df = pd.read_csv(path, dtype={'code': str}) # # return df # # Path: kquant_data/wind_resume/wsd.py # def resume_download_daily_many_to_one_file( # w, # wind_codes, # field, # dtype, # enddate, # root_path, # option='unit=1;rptType=1;Period=Q;Days=Alldays', # default_start_date='2000-01-01'): # def resume_download_daily_one_to_one_file( # w, # symbol, # ipo_date, # field, # trading_days, # root_path): # def resume_download_daily_to_many_files( # w, # trading_days, # ipo_date, # root_path, # field='total_shares'): # def resume_download_delist_date( # w, # wind_codes, # root_path, # field='delist_date', # dtype=np.datetime64): # def combine_func(x1, x2): # def resume_download_financial_report_data_daily_latest( # w, # wind_codes, # trading_days, # root_path, # field='total_shares', # date_str=datetime.today().strftime('%Y-%m-%d'), # option=""): # def resume_download_financial_report_quarter(w, wind_codes, root_path, fields=['stm_issuingdate'], dtype=np.datetime64): # # Path: kquant_data/config.py # __CONFIG_H5_STK_FACTOR_DIR__ = os.path.join(__CONFIG_H5_STK_DIR__, 'factor') # # __CONFIG_H5_STK_DIR__ = r'D:\DATA_STK' . Output only the next line.
Symbols = all_instruments(path)
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ 下载财报一类的信息 """ if __name__ == '__main__': w.start() path = os.path.join(__CONFIG_H5_STK_DIR__, '1day', 'Symbol.csv') Symbols = all_instruments(path) wind_codes = list(Symbols['wind_code']) # 下载多天数据,以另一数据做为标准来下载 # 比如交易数据是10月8号,那就得取10月7号,然后再平移到8号,如果7号没有数据那就得9月30号 path = os.path.join(__CONFIG_H5_STK_FACTOR_DIR__, 'roe.csv') date_index = read_data_dataframe(path) field = 'pb_lf' df = None for i in range(len(date_index)): print(date_index.index[i]) date_str = date_index.index[i].strftime('%Y-%m-%d') <|code_end|> using the current file's imports: import os import pandas as pd from WindPy import w from kquant_data.xio.csv import write_data_dataframe, read_data_dataframe from kquant_data.api import all_instruments from kquant_data.wind_resume.wsd import download_daily_at from kquant_data.config import __CONFIG_H5_STK_FACTOR_DIR__, __CONFIG_H5_STK_DIR__ and any relevant context from other files: # Path: kquant_data/xio/csv.py # def write_data_dataframe(path, df, date_format='%Y-%m-%d'): # """ # 写入数据 # :param path: # :param df: # :return: # """ # df.to_csv(path, date_format=date_format, encoding='utf-8-sig') # # def read_data_dataframe(path, sep=','): # """ # 读取季报的公告日 # 注意:有些股票多个季度一起发,一般是公司出问题了,特别是600878,四个报告同一天发布 # 年报与一季报很有可能一起发 # :param path: # :param sep: # :return: # """ # try: # df = pd.read_csv(path, index_col=0, parse_dates=True, encoding='utf-8-sig', sep=sep) # except (FileNotFoundError, OSError): # return None # # return df # # Path: kquant_data/api.py # def all_instruments(path=None, type=None): # """ # 得到合约列表 # :param type: # :return: # """ # if path is None: # path = os.path.join(__CONFIG_H5_STK_DIR__, "daily", 'Symbol.csv') # # df = pd.read_csv(path, dtype={'code': str}) # # return df # # Path: kquant_data/wind_resume/wsd.py # def resume_download_daily_many_to_one_file( # w, # wind_codes, # field, # dtype, # enddate, # root_path, # option='unit=1;rptType=1;Period=Q;Days=Alldays', # default_start_date='2000-01-01'): # def resume_download_daily_one_to_one_file( # w, # symbol, # ipo_date, # field, # trading_days, # root_path): # def resume_download_daily_to_many_files( # w, # trading_days, # ipo_date, # root_path, # field='total_shares'): # def resume_download_delist_date( # w, # wind_codes, # root_path, # field='delist_date', # dtype=np.datetime64): # def combine_func(x1, x2): # def resume_download_financial_report_data_daily_latest( # w, # wind_codes, # trading_days, # root_path, # field='total_shares', # date_str=datetime.today().strftime('%Y-%m-%d'), # option=""): # def resume_download_financial_report_quarter(w, wind_codes, root_path, fields=['stm_issuingdate'], dtype=np.datetime64): # # Path: kquant_data/config.py # __CONFIG_H5_STK_FACTOR_DIR__ = os.path.join(__CONFIG_H5_STK_DIR__, 'factor') # # __CONFIG_H5_STK_DIR__ = r'D:\DATA_STK' . Output only the next line.
df_new = download_daily_at(w, wind_codes, field, date_str, "Days=Alldays")
Given the code snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ 下载财报一类的信息 """ if __name__ == '__main__': w.start() path = os.path.join(__CONFIG_H5_STK_DIR__, '1day', 'Symbol.csv') Symbols = all_instruments(path) wind_codes = list(Symbols['wind_code']) # 下载多天数据,以另一数据做为标准来下载 # 比如交易数据是10月8号,那就得取10月7号,然后再平移到8号,如果7号没有数据那就得9月30号 <|code_end|> , generate the next line using the imports in this file: import os import pandas as pd from WindPy import w from kquant_data.xio.csv import write_data_dataframe, read_data_dataframe from kquant_data.api import all_instruments from kquant_data.wind_resume.wsd import download_daily_at from kquant_data.config import __CONFIG_H5_STK_FACTOR_DIR__, __CONFIG_H5_STK_DIR__ and context (functions, classes, or occasionally code) from other files: # Path: kquant_data/xio/csv.py # def write_data_dataframe(path, df, date_format='%Y-%m-%d'): # """ # 写入数据 # :param path: # :param df: # :return: # """ # df.to_csv(path, date_format=date_format, encoding='utf-8-sig') # # def read_data_dataframe(path, sep=','): # """ # 读取季报的公告日 # 注意:有些股票多个季度一起发,一般是公司出问题了,特别是600878,四个报告同一天发布 # 年报与一季报很有可能一起发 # :param path: # :param sep: # :return: # """ # try: # df = pd.read_csv(path, index_col=0, parse_dates=True, encoding='utf-8-sig', sep=sep) # except (FileNotFoundError, OSError): # return None # # return df # # Path: kquant_data/api.py # def all_instruments(path=None, type=None): # """ # 得到合约列表 # :param type: # :return: # """ # if path is None: # path = os.path.join(__CONFIG_H5_STK_DIR__, "daily", 'Symbol.csv') # # df = pd.read_csv(path, dtype={'code': str}) # # return df # # Path: kquant_data/wind_resume/wsd.py # def resume_download_daily_many_to_one_file( # w, # wind_codes, # field, # dtype, # enddate, # root_path, # option='unit=1;rptType=1;Period=Q;Days=Alldays', # default_start_date='2000-01-01'): # def resume_download_daily_one_to_one_file( # w, # symbol, # ipo_date, # field, # trading_days, # root_path): # def resume_download_daily_to_many_files( # w, # trading_days, # ipo_date, # root_path, # field='total_shares'): # def resume_download_delist_date( # w, # wind_codes, # root_path, # field='delist_date', # dtype=np.datetime64): # def combine_func(x1, x2): # def resume_download_financial_report_data_daily_latest( # w, # wind_codes, # trading_days, # root_path, # field='total_shares', # date_str=datetime.today().strftime('%Y-%m-%d'), # option=""): # def resume_download_financial_report_quarter(w, wind_codes, root_path, fields=['stm_issuingdate'], dtype=np.datetime64): # # Path: kquant_data/config.py # __CONFIG_H5_STK_FACTOR_DIR__ = os.path.join(__CONFIG_H5_STK_DIR__, 'factor') # # __CONFIG_H5_STK_DIR__ = r'D:\DATA_STK' . Output only the next line.
path = os.path.join(__CONFIG_H5_STK_FACTOR_DIR__, 'roe.csv')
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ 下载财报一类的信息 """ if __name__ == '__main__': w.start() <|code_end|> with the help of current file imports: import os import pandas as pd from WindPy import w from kquant_data.xio.csv import write_data_dataframe, read_data_dataframe from kquant_data.api import all_instruments from kquant_data.wind_resume.wsd import download_daily_at from kquant_data.config import __CONFIG_H5_STK_FACTOR_DIR__, __CONFIG_H5_STK_DIR__ and context from other files: # Path: kquant_data/xio/csv.py # def write_data_dataframe(path, df, date_format='%Y-%m-%d'): # """ # 写入数据 # :param path: # :param df: # :return: # """ # df.to_csv(path, date_format=date_format, encoding='utf-8-sig') # # def read_data_dataframe(path, sep=','): # """ # 读取季报的公告日 # 注意:有些股票多个季度一起发,一般是公司出问题了,特别是600878,四个报告同一天发布 # 年报与一季报很有可能一起发 # :param path: # :param sep: # :return: # """ # try: # df = pd.read_csv(path, index_col=0, parse_dates=True, encoding='utf-8-sig', sep=sep) # except (FileNotFoundError, OSError): # return None # # return df # # Path: kquant_data/api.py # def all_instruments(path=None, type=None): # """ # 得到合约列表 # :param type: # :return: # """ # if path is None: # path = os.path.join(__CONFIG_H5_STK_DIR__, "daily", 'Symbol.csv') # # df = pd.read_csv(path, dtype={'code': str}) # # return df # # Path: kquant_data/wind_resume/wsd.py # def resume_download_daily_many_to_one_file( # w, # wind_codes, # field, # dtype, # enddate, # root_path, # option='unit=1;rptType=1;Period=Q;Days=Alldays', # default_start_date='2000-01-01'): # def resume_download_daily_one_to_one_file( # w, # symbol, # ipo_date, # field, # trading_days, # root_path): # def resume_download_daily_to_many_files( # w, # trading_days, # ipo_date, # root_path, # field='total_shares'): # def resume_download_delist_date( # w, # wind_codes, # root_path, # field='delist_date', # dtype=np.datetime64): # def combine_func(x1, x2): # def resume_download_financial_report_data_daily_latest( # w, # wind_codes, # trading_days, # root_path, # field='total_shares', # date_str=datetime.today().strftime('%Y-%m-%d'), # option=""): # def resume_download_financial_report_quarter(w, wind_codes, root_path, fields=['stm_issuingdate'], dtype=np.datetime64): # # Path: kquant_data/config.py # __CONFIG_H5_STK_FACTOR_DIR__ = os.path.join(__CONFIG_H5_STK_DIR__, 'factor') # # __CONFIG_H5_STK_DIR__ = r'D:\DATA_STK' , which may contain function names, class names, or code. Output only the next line.
path = os.path.join(__CONFIG_H5_STK_DIR__, '1day', 'Symbol.csv')
Predict the next line after this snippet: <|code_start|># limitations under the License. # Unit tests need LDIF added to the path, because the scripts aren't # in the repository top-level directory. ldif_root = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir) sys.path.append(ldif_root) TEST_DATA_DIR = './data' class TestSif(unittest.TestCase): def _ensure_sifs_equal(self, a, b, ith=0): end=ith+1 if ith == -1: self.assertEqual(a.bs, b.bs) ith = 0 end = b.bs self.assertTrue(torch.all(a._constants.eq(b._constants[ith:end, ...]))) self.assertTrue(torch.all(a._centers.eq(b._centers[ith:end, ...]))) self.assertTrue(torch.all(a._radii.eq(b._radii[ith:end, ...]))) self.assertTrue(torch.all(a._rotations.eq(b._rotations[ith:end, ...]))) self.assertEqual(a.symmetry_count, b.symmetry_count) self.assertEqual(a.element_count, b.element_count) def test_load_sif(self): sif_path = os.path.join(TEST_DATA_DIR, 'b831f60f211435df5bbc861d0124304c.txt') constants, centers, radii, rotations, symmetry_count, features = ( <|code_end|> using the current file's imports: import os import sys import unittest import numpy as np import torch from ldif.torch import sif and any relevant context from other files: # Path: ldif/torch/sif.py # def ensure_are_tensors(named_tensors): # def ensure_type(v, t, name): # def _load_v1_txt(path): # def _tile_for_symgroups(elements, symmetry_count): # def reflect_z(samples): # def _generate_symgroup_samples(samples, element_count, symmetry_count): # def _generate_symgroup_frames(world2local, symmetry_count): # def __init__(self, constants, centers, radii, rotations, symmetry_count): # def from_file(cls, path): # def from_flat_tensor(cls, tensor, symmetry_count): # def to_flat_tensor(self): # def rbf_influence(self, samples): # def effective_element_count(self): # def constants(self): # def _tiled_constants(self): # def _tiled_centers(self): # def _tiled_radii(self): # def _tiled_rotations(self): # def world2local(self): # def eval(self, samples): # class Sif(object): . Output only the next line.
sif._load_v1_txt(sif_path))
Next line prediction: <|code_start|># Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Utilities for managing gpus.""" def get_free_gpu_memory(cuda_device_index): """Returns the current # of free megabytes for the specified device.""" if sys.platform == "darwin": # No GPUs on darwin... return 0 result = sp.check_output('nvidia-smi --query-gpu=memory.free ' '--format=csv,nounits,noheader', shell=True) result = result.decode('utf-8').split('\n')[:-1] <|code_end|> . Use current file imports: (import sys import subprocess as sp from ldif.util.file_util import log) and context including class names, function names, or small code snippets from other files: # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): . Output only the next line.
log.verbose(f'The system has {len(result)} gpu(s).')
Based on the snippet: <|code_start|># you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Tests for ldif.util.tf_util.""" # LDIF is an internal package, should be imported last. # pylint: disable=g-bad-import-order # pylint: enable=g-bad-import-order DISTANCE_EPS = 1e-6 class TfUtilTest(tf.test.TestCase): @parameterized.expand([('RemoveSecondRow', 1, 0, [[1.0, 2.0]]), ('RemoveFirstRow', 0, 0, [[3.0, 4.0]]), ('RemoveFirstCol', 0, 1, [[2.0], [4.0]]), ('RemoveSecondCol', 1, 1, [[1.0], [3.0]])]) def testRemoveElement(self, name, elt, axis, expected): initial = tf.constant([[1.0, 2.0], [3.0, 4.0]], dtype=tf.float32) <|code_end|> , predict the immediate next line with the help of imports: import numpy as np import tensorflow as tf from parameterized import parameterized from ldif.util import tf_util and context (classes, functions, sometimes code) from other files: # Path: ldif/util/tf_util.py # def assert_shape(tensor, shape, name): # def log(msg, t): # def tile_new_axis(t, axis, length): # def zero_by_mask(mask, vals, replace_with=0.0): # def remove_element(t, elt, axis): . Output only the next line.
removed = tf_util.remove_element(initial, tf.constant([elt],
Given snippet: <|code_start|> 'Whether to transform from the gaps to occnet frame.') def make_metrics(proto): """Builds a dictionary containing proto elements.""" key, s = proto p = results_pb2.Results.FromString(s) mesh_path = FLAGS.occnet_dir + key.replace('test/', '') + '.ply' log.warning('Mesh path: %s' % mesh_path) try: mesh = file_util.read_mesh(mesh_path) if FLAGS.transform: # TODO(ldif-user) Set up the path to the transformation: tx_path = 'ROOT_DIR/%s/occnet_to_gaps.txt' % key occnet_to_gaps = file_util.read_txt_to_np(tx_path).reshape([4, 4]) gaps_to_occnet = np.linalg.inv(occnet_to_gaps) mesh.apply_transform(gaps_to_occnet) # pylint: disable=broad-except except Exception as e: # pylint: enable=broad-except log.error("Couldn't load %s, skipping due to %s." % (mesh_path, repr(e))) return [] gt_mesh = mesh_util.deserialize(p.gt_mesh) dir_out = FLAGS.occnet_dir + '/metrics-out-gt/%s' % key if not file_util.exists(dir_out): file_util.makedirs(dir_out) file_util.write_mesh(f'{dir_out}gt_mesh.ply', gt_mesh) file_util.write_mesh(f'{dir_out}occnet_pred.ply', mesh) <|code_end|> , continue by predicting the next line. Consider current file imports: from absl import app from absl import flags from ldif.inference import metrics from ldif.results import results_pb2 from ldif.util import file_util from ldif.util import mesh_util from ldif.util.file_util import log import apache_beam as beam import numpy as np import pandas as pd and context: # Path: ldif/inference/metrics.py # OCCNET_FSCORE_EPS = 1e-09 # def get_class(row): # def print_pivot_table(class_mean_df, metric_name, metric_pretty_print): # def aggregate_extracted(csv_path_or_df): # def sample_points_and_face_normals(mesh, sample_count): # def pointcloud_neighbor_distances_indices(source_points, target_points): # def dot_product(a, b): # def point_iou(pred_is_inside, gt_is_inside): # def point_metrics(element): # def element_to_example(element): # def percent_below(dists, thresh): # def f_score(a_to_b, b_to_a, thresh): # def fscore(mesh1, # mesh2, # sample_count=100000, # tau=1e-04, # points1=None, # points2=None): # def mesh_chamfer_via_points(mesh1, # mesh2, # sample_count=100000, # points1=None, # points2=None): # def get_points(mesh1, mesh2, points1, points2, sample_count): # def normal_consistency(mesh1, mesh2, sample_count=100000, return_points=False): # def print_mesh_metrics(pred_mesh, gt_mesh, sample_count=100000): # def compute_all(sif_vector, decoder, e, resolution=256, sample_count=100000): # def print_all(sif_vector, decoder, e, resolution=256, sample_count=100000): # def all_mesh_metrics(mesh1, mesh2, sample_count=100000): # def mesh_metrics(element): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): # # Path: ldif/util/mesh_util.py # def serialize(mesh): # def deserialize(mesh_str): # def remove_small_components(mesh, min_volume=5e-05): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): which might include code, classes, or functions. Output only the next line.
nc, fst, fs2t, chamfer = metrics.all_mesh_metrics(mesh, gt_mesh)
Given the following code snippet before the placeholder: <|code_start|> # LDIF is an internal package, should be imported last. # pylint: disable=g-bad-import-order # pylint: enable=g-bad-import-order FLAGS = flags.FLAGS flags.DEFINE_string('occnet_dir', None, "The folder with OccNet's meshes.") flags.mark_flag_as_required('occnet_dir') flags.DEFINE_boolean('write_metrics', None, 'Whether to write full metrics in the results.') flags.mark_flag_as_required('write_metrics') flags.DEFINE_boolean('write_metric_summaries', None, 'Whether to write summaries of metrics in the results.') flags.mark_flag_as_required('write_metric_summaries') flags.DEFINE_boolean('transform', True, 'Whether to transform from the gaps to occnet frame.') def make_metrics(proto): """Builds a dictionary containing proto elements.""" key, s = proto p = results_pb2.Results.FromString(s) mesh_path = FLAGS.occnet_dir + key.replace('test/', '') + '.ply' log.warning('Mesh path: %s' % mesh_path) try: <|code_end|> , predict the next line using imports from the current file: from absl import app from absl import flags from ldif.inference import metrics from ldif.results import results_pb2 from ldif.util import file_util from ldif.util import mesh_util from ldif.util.file_util import log import apache_beam as beam import numpy as np import pandas as pd and context including class names, function names, and sometimes code from other files: # Path: ldif/inference/metrics.py # OCCNET_FSCORE_EPS = 1e-09 # def get_class(row): # def print_pivot_table(class_mean_df, metric_name, metric_pretty_print): # def aggregate_extracted(csv_path_or_df): # def sample_points_and_face_normals(mesh, sample_count): # def pointcloud_neighbor_distances_indices(source_points, target_points): # def dot_product(a, b): # def point_iou(pred_is_inside, gt_is_inside): # def point_metrics(element): # def element_to_example(element): # def percent_below(dists, thresh): # def f_score(a_to_b, b_to_a, thresh): # def fscore(mesh1, # mesh2, # sample_count=100000, # tau=1e-04, # points1=None, # points2=None): # def mesh_chamfer_via_points(mesh1, # mesh2, # sample_count=100000, # points1=None, # points2=None): # def get_points(mesh1, mesh2, points1, points2, sample_count): # def normal_consistency(mesh1, mesh2, sample_count=100000, return_points=False): # def print_mesh_metrics(pred_mesh, gt_mesh, sample_count=100000): # def compute_all(sif_vector, decoder, e, resolution=256, sample_count=100000): # def print_all(sif_vector, decoder, e, resolution=256, sample_count=100000): # def all_mesh_metrics(mesh1, mesh2, sample_count=100000): # def mesh_metrics(element): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): # # Path: ldif/util/mesh_util.py # def serialize(mesh): # def deserialize(mesh_str): # def remove_small_components(mesh, min_volume=5e-05): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): . Output only the next line.
mesh = file_util.read_mesh(mesh_path)
Next line prediction: <|code_start|>flags.mark_flag_as_required('write_metrics') flags.DEFINE_boolean('write_metric_summaries', None, 'Whether to write summaries of metrics in the results.') flags.mark_flag_as_required('write_metric_summaries') flags.DEFINE_boolean('transform', True, 'Whether to transform from the gaps to occnet frame.') def make_metrics(proto): """Builds a dictionary containing proto elements.""" key, s = proto p = results_pb2.Results.FromString(s) mesh_path = FLAGS.occnet_dir + key.replace('test/', '') + '.ply' log.warning('Mesh path: %s' % mesh_path) try: mesh = file_util.read_mesh(mesh_path) if FLAGS.transform: # TODO(ldif-user) Set up the path to the transformation: tx_path = 'ROOT_DIR/%s/occnet_to_gaps.txt' % key occnet_to_gaps = file_util.read_txt_to_np(tx_path).reshape([4, 4]) gaps_to_occnet = np.linalg.inv(occnet_to_gaps) mesh.apply_transform(gaps_to_occnet) # pylint: disable=broad-except except Exception as e: # pylint: enable=broad-except log.error("Couldn't load %s, skipping due to %s." % (mesh_path, repr(e))) return [] <|code_end|> . Use current file imports: (from absl import app from absl import flags from ldif.inference import metrics from ldif.results import results_pb2 from ldif.util import file_util from ldif.util import mesh_util from ldif.util.file_util import log import apache_beam as beam import numpy as np import pandas as pd) and context including class names, function names, or small code snippets from other files: # Path: ldif/inference/metrics.py # OCCNET_FSCORE_EPS = 1e-09 # def get_class(row): # def print_pivot_table(class_mean_df, metric_name, metric_pretty_print): # def aggregate_extracted(csv_path_or_df): # def sample_points_and_face_normals(mesh, sample_count): # def pointcloud_neighbor_distances_indices(source_points, target_points): # def dot_product(a, b): # def point_iou(pred_is_inside, gt_is_inside): # def point_metrics(element): # def element_to_example(element): # def percent_below(dists, thresh): # def f_score(a_to_b, b_to_a, thresh): # def fscore(mesh1, # mesh2, # sample_count=100000, # tau=1e-04, # points1=None, # points2=None): # def mesh_chamfer_via_points(mesh1, # mesh2, # sample_count=100000, # points1=None, # points2=None): # def get_points(mesh1, mesh2, points1, points2, sample_count): # def normal_consistency(mesh1, mesh2, sample_count=100000, return_points=False): # def print_mesh_metrics(pred_mesh, gt_mesh, sample_count=100000): # def compute_all(sif_vector, decoder, e, resolution=256, sample_count=100000): # def print_all(sif_vector, decoder, e, resolution=256, sample_count=100000): # def all_mesh_metrics(mesh1, mesh2, sample_count=100000): # def mesh_metrics(element): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): # # Path: ldif/util/mesh_util.py # def serialize(mesh): # def deserialize(mesh_str): # def remove_small_components(mesh, min_volume=5e-05): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): . Output only the next line.
gt_mesh = mesh_util.deserialize(p.gt_mesh)
Based on the snippet: <|code_start|># Lint as: python3 """Extracts results for paper presentation.""" # LDIF is an internal package, should be imported last. # pylint: disable=g-bad-import-order # pylint: enable=g-bad-import-order FLAGS = flags.FLAGS flags.DEFINE_string('occnet_dir', None, "The folder with OccNet's meshes.") flags.mark_flag_as_required('occnet_dir') flags.DEFINE_boolean('write_metrics', None, 'Whether to write full metrics in the results.') flags.mark_flag_as_required('write_metrics') flags.DEFINE_boolean('write_metric_summaries', None, 'Whether to write summaries of metrics in the results.') flags.mark_flag_as_required('write_metric_summaries') flags.DEFINE_boolean('transform', True, 'Whether to transform from the gaps to occnet frame.') def make_metrics(proto): """Builds a dictionary containing proto elements.""" key, s = proto p = results_pb2.Results.FromString(s) mesh_path = FLAGS.occnet_dir + key.replace('test/', '') + '.ply' <|code_end|> , predict the immediate next line with the help of imports: from absl import app from absl import flags from ldif.inference import metrics from ldif.results import results_pb2 from ldif.util import file_util from ldif.util import mesh_util from ldif.util.file_util import log import apache_beam as beam import numpy as np import pandas as pd and context (classes, functions, sometimes code) from other files: # Path: ldif/inference/metrics.py # OCCNET_FSCORE_EPS = 1e-09 # def get_class(row): # def print_pivot_table(class_mean_df, metric_name, metric_pretty_print): # def aggregate_extracted(csv_path_or_df): # def sample_points_and_face_normals(mesh, sample_count): # def pointcloud_neighbor_distances_indices(source_points, target_points): # def dot_product(a, b): # def point_iou(pred_is_inside, gt_is_inside): # def point_metrics(element): # def element_to_example(element): # def percent_below(dists, thresh): # def f_score(a_to_b, b_to_a, thresh): # def fscore(mesh1, # mesh2, # sample_count=100000, # tau=1e-04, # points1=None, # points2=None): # def mesh_chamfer_via_points(mesh1, # mesh2, # sample_count=100000, # points1=None, # points2=None): # def get_points(mesh1, mesh2, points1, points2, sample_count): # def normal_consistency(mesh1, mesh2, sample_count=100000, return_points=False): # def print_mesh_metrics(pred_mesh, gt_mesh, sample_count=100000): # def compute_all(sif_vector, decoder, e, resolution=256, sample_count=100000): # def print_all(sif_vector, decoder, e, resolution=256, sample_count=100000): # def all_mesh_metrics(mesh1, mesh2, sample_count=100000): # def mesh_metrics(element): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): # # Path: ldif/util/mesh_util.py # def serialize(mesh): # def deserialize(mesh_str): # def remove_small_components(mesh, min_volume=5e-05): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): . Output only the next line.
log.warning('Mesh path: %s' % mesh_path)
Continue the code snippet: <|code_start|> for a in self.lazy_attrs: val = getattr(self, a) is_initialized = val is not None if is_initialized: raise ValueError('Attribute %s has already been set to value %s' % (a, repr(val))) def set_use_temp_ckpts(self, useable): assert useable in [True, False, 'warn'] self._ensure_lazy_attrs_are_zero() self._use_temp_ckpts = useable @property def is_visible(self): return self.xid in self.experiment.visible_xids def ensure_visible(self): if not self.is_visible: raise ValueError( 'Job failed ensure_visible() check: %i. Only %i are visible.' % (self.xid, self.experiment.visible_xids)) @property def ckpt_dir(self): return self.root_dir + '/train/' @property def root_dir(self): if self._root_dir is None: self._root_dir = '%s/%s/' % (self.experiment.root, self.job_str) <|code_end|> . Use current file imports: import importlib import os import numpy as np from ldif.model import hparams as hparams_util from ldif.util import file_util from ldif.util import path_util from ldif.util.file_util import log and context (classes, functions, or code) from other files: # Path: ldif/model/hparams.py # def backwards_compatible_hparam_defaults(ident): # def tf_hparams_to_dict(tf_hparams): # def build_ldif_hparams(): # def build_sif_hparams(): # def build_improved_sif_hparams(): # def build_singleview_depth_hparams(): # def write_hparams(hparams, path): # def read_hparams_with_new_backwards_compatible_additions(path): # def read_hparams(path): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): # # Path: ldif/util/path_util.py # def get_path_to_ldif_root(): # def get_path_to_ldif_parent(): # def package_to_abs(path): # def gaps_path(): # def test_data_path(): # def util_test_data_path(): # def create_test_output_dir(): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): . Output only the next line.
if not file_util.exists(self._root_dir):
Given snippet: <|code_start|> repr(s)) j = s[0] if must_be_visible: j.ensure_visible() return j def job_from_job_str(self, job_str, must_be_visible=True): xid = to_xid(job_str) return self.job_from_xmanager_id(xid, must_be_visible) class ResultStore(object): """A backing store for results. Has both remote and local components. This class is not synchronized. It assumes nothing is changing on the server or local disk except the operations it performs. """ def __init__(self, experiment, desired_ckpts=-1): self.experiment = experiment self.available_ckpt_dict = {} self.desired_ckpts = desired_ckpts self.remote_base_dirs = {'train': {}, 'val': {}, 'test': {}} self._remote_mesh_names = None self._local_qual_path = None @property def local_root(self): <|code_end|> , continue by predicting the next line. Consider current file imports: import importlib import os import numpy as np from ldif.model import hparams as hparams_util from ldif.util import file_util from ldif.util import path_util from ldif.util.file_util import log and context: # Path: ldif/model/hparams.py # def backwards_compatible_hparam_defaults(ident): # def tf_hparams_to_dict(tf_hparams): # def build_ldif_hparams(): # def build_sif_hparams(): # def build_improved_sif_hparams(): # def build_singleview_depth_hparams(): # def write_hparams(hparams, path): # def read_hparams_with_new_backwards_compatible_additions(path): # def read_hparams(path): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): # # Path: ldif/util/path_util.py # def get_path_to_ldif_root(): # def get_path_to_ldif_parent(): # def package_to_abs(path): # def gaps_path(): # def test_data_path(): # def util_test_data_path(): # def create_test_output_dir(): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): which might include code, classes, or functions. Output only the next line.
return os.path.join(path_util.get_path_to_ldif_root(), 'result_store')
Given the code snippet: <|code_start|> return self._root_dir @property def all_checkpoint_indices(self): return [c.idx for c in self.all_checkpoints] @property def all_checkpoints(self): """A list of all checkpoint objects in the checkpoint directory.""" if self._all_checkpoints is None: candidates = [ os.path.basename(n) for n in file_util.glob(f'{self.ckpt_dir}/*') ] inds = [ int(x.replace('model.ckpt-', '').replace('.index', '')) for x in candidates if 'index' in x and 'tempstate' not in x ] inds.sort(reverse=False) # The train task may delete the 5 most recent checkpoints periodically: if not inds: raise ValueError('There are no checkpoints in the directory %s.' % self.ckpt_dir) elif self._use_temp_ckpts is True: # pylint: disable=g-bool-id-comparison message = 'Temporary checkpoints are enabled.' message += ' The most recent temporary checkpoint is %i.' % inds[-1] if len(inds) >= 6: message += ' The most recent permanent checkpoint is %i.' % inds[-6] else: message += ' There are no permanent checkpoints.' <|code_end|> , generate the next line using the imports in this file: import importlib import os import numpy as np from ldif.model import hparams as hparams_util from ldif.util import file_util from ldif.util import path_util from ldif.util.file_util import log and context (functions, classes, or occasionally code) from other files: # Path: ldif/model/hparams.py # def backwards_compatible_hparam_defaults(ident): # def tf_hparams_to_dict(tf_hparams): # def build_ldif_hparams(): # def build_sif_hparams(): # def build_improved_sif_hparams(): # def build_singleview_depth_hparams(): # def write_hparams(hparams, path): # def read_hparams_with_new_backwards_compatible_additions(path): # def read_hparams(path): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): # # Path: ldif/util/path_util.py # def get_path_to_ldif_root(): # def get_path_to_ldif_parent(): # def package_to_abs(path): # def gaps_path(): # def test_data_path(): # def util_test_data_path(): # def create_test_output_dir(): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): . Output only the next line.
log.warning(message)
Given the code snippet: <|code_start|> def marching_cubes(volume, mcubes_extent): """Maps from a voxel grid of implicit surface samples to a Trimesh mesh.""" volume = np.squeeze(volume) length, height, width = volume.shape resolution = length # This function doesn't support non-cube volumes: assert resolution == height and resolution == width thresh = -0.07 try: vertices, faces, normals, _ = measure.marching_cubes_lewiner(volume, thresh) del normals x, y, z = [np.array(x) for x in zip(*vertices)] xyzw = np.stack([x, y, z, np.ones_like(x)], axis=1) # Center the volume around the origin: xyzw += np.array( [[-resolution / 2.0, -resolution / 2.0, -resolution / 2.0, 0.]]) # This assumes the world is right handed with y up; matplotlib's renderer # has z up and is left handed: # Reflect across z, rotate about x, and rescale to [-0.5, 0.5]. xyzw *= np.array([[(2.0 * mcubes_extent) / resolution, (2.0 * mcubes_extent) / resolution, -1.0 * (2.0 * mcubes_extent) / resolution, 1]]) y_up_to_z_up = np.array([[0., 0., -1., 0.], [0., 1., 0., 0.], [1., 0., 0., 0.], [0., 0., 0., 1.]]) xyzw = np.matmul(y_up_to_z_up, xyzw.T).T faces = np.stack([faces[..., 0], faces[..., 2], faces[..., 1]], axis=-1) world_space_xyz = np.copy(xyzw[:, :3]) mesh = trimesh.Trimesh(vertices=world_space_xyz, faces=faces) <|code_end|> , generate the next line using the imports in this file: import numpy as np import trimesh from skimage import measure from ldif.util.file_util import log and context (functions, classes, or occasionally code) from other files: # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): . Output only the next line.
log.verbose('Generated mesh successfully.')
Next line prediction: <|code_start|># # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Code for preprocessing training examples. This code can be aware of the existence of individual datasets, but it can't be aware of their internals. """ # LDIF is an internal package, should be imported last. # pylint: disable=g-bad-import-order # pylint: enable=g-bad-import-order # Main entry point for preprocessing. This code uses the model config to # generate an appropriate training example. It uses duck typing, in that # it should dispatch generation to a dataset to handle internals, and verify # that the training example contains the properties associated with the config. # But it doesn't care about anything else. def preprocess(model_config): """Generates a training example object from the model config.""" # TODO(kgenova) Check if dataset is shapenet. If so, return a ShapeNet # training example. <|code_end|> . Use current file imports: (import tensorflow as tf from ldif.datasets import shapenet from ldif.util import random_util) and context including class names, function names, or small code snippets from other files: # Path: ldif/datasets/shapenet.py # def ensure_shape_and_resize_if_needed(orig_renders, batch_size, frame_count, # channel_count, orig_height, orig_width, # target_height, target_width): # def select_image(images, indices): # def apply_noise_to_depth(depth, stddev): # def add_noise_to_xyz(xyz, stddev): # def add_noise_in_normal_direction(xyz, normals, stddev): # def __init__(self, model_config): # def full_near_surface_samples(self): # def full_uniform_samples(self): # def _subsample(self, samples, sample_count): # def proto_name(self): # def depth_render(self): # def apply_transformation(self, tx): # def crop_input(self, crop_count=1024): # def crop_supervision(self, crop_count=1024): # def xyz_render(self): # def depth_renders(self): # def random_depth_indices(self): # def random_depth_images(self): # def random_depth_to_worlds(self): # def xyz_renders(self): # def depth_to_world(self): # def renders(self): # def lum_renders(self): # def chosen_renders(self): # def random_lum_render(self): # def random_xyz_render(self): # def grid(self): # def world2grid(self): # def _finite_wrapper(self, t): # def sample_bounding_box(self): # def sample_sdf_near_surface(self, sample_count): # def sample_sdf_uniform(self, sample_count): # def all_uniform_samples(self): # def _set_points_and_normals(self): # def all_surface_points(self): # def all_normals(self): # def sample_zero_set_points_and_normals(self, sample_count): # def __init__(self, lower, upper): # def from_samples(cls, samples): # def build_placeholder_interface(model_config, # proto='ShapeNetNSSDodecaSparseLRGMediumSlimPC'): # class ShapeNetExample(object): # class BoundingBox(object): # # Path: ldif/util/random_util.py # def random_shuffle_along_dim(tensor, dim): # def random_pan_rotations(batch_size): # def random_pan_rotation_np(): # def random_rotations(batch_size): # def random_rotation_np(): # def random_scales(batch_size, minval, maxval): # def random_transformation(origin): # def random_zoom_transformation(origin): # def translation_to_tx(t): # def rotation_to_tx(rot): . Output only the next line.
training_example = shapenet.ShapeNetExample(model_config)
Given the code snippet: <|code_start|># See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Code for preprocessing training examples. This code can be aware of the existence of individual datasets, but it can't be aware of their internals. """ # LDIF is an internal package, should be imported last. # pylint: disable=g-bad-import-order # pylint: enable=g-bad-import-order # Main entry point for preprocessing. This code uses the model config to # generate an appropriate training example. It uses duck typing, in that # it should dispatch generation to a dataset to handle internals, and verify # that the training example contains the properties associated with the config. # But it doesn't care about anything else. def preprocess(model_config): """Generates a training example object from the model config.""" # TODO(kgenova) Check if dataset is shapenet. If so, return a ShapeNet # training example. training_example = shapenet.ShapeNetExample(model_config) # TODO(kgenova) Look at the model config and verify that nothing is missing. if model_config.hparams.da == 'f': return training_example elif model_config.hparams.da == 'p': # Pan: <|code_end|> , generate the next line using the imports in this file: import tensorflow as tf from ldif.datasets import shapenet from ldif.util import random_util and context (functions, classes, or occasionally code) from other files: # Path: ldif/datasets/shapenet.py # def ensure_shape_and_resize_if_needed(orig_renders, batch_size, frame_count, # channel_count, orig_height, orig_width, # target_height, target_width): # def select_image(images, indices): # def apply_noise_to_depth(depth, stddev): # def add_noise_to_xyz(xyz, stddev): # def add_noise_in_normal_direction(xyz, normals, stddev): # def __init__(self, model_config): # def full_near_surface_samples(self): # def full_uniform_samples(self): # def _subsample(self, samples, sample_count): # def proto_name(self): # def depth_render(self): # def apply_transformation(self, tx): # def crop_input(self, crop_count=1024): # def crop_supervision(self, crop_count=1024): # def xyz_render(self): # def depth_renders(self): # def random_depth_indices(self): # def random_depth_images(self): # def random_depth_to_worlds(self): # def xyz_renders(self): # def depth_to_world(self): # def renders(self): # def lum_renders(self): # def chosen_renders(self): # def random_lum_render(self): # def random_xyz_render(self): # def grid(self): # def world2grid(self): # def _finite_wrapper(self, t): # def sample_bounding_box(self): # def sample_sdf_near_surface(self, sample_count): # def sample_sdf_uniform(self, sample_count): # def all_uniform_samples(self): # def _set_points_and_normals(self): # def all_surface_points(self): # def all_normals(self): # def sample_zero_set_points_and_normals(self, sample_count): # def __init__(self, lower, upper): # def from_samples(cls, samples): # def build_placeholder_interface(model_config, # proto='ShapeNetNSSDodecaSparseLRGMediumSlimPC'): # class ShapeNetExample(object): # class BoundingBox(object): # # Path: ldif/util/random_util.py # def random_shuffle_along_dim(tensor, dim): # def random_pan_rotations(batch_size): # def random_pan_rotation_np(): # def random_rotations(batch_size): # def random_rotation_np(): # def random_scales(batch_size, minval, maxval): # def random_transformation(origin): # def random_zoom_transformation(origin): # def translation_to_tx(t): # def rotation_to_tx(rot): . Output only the next line.
tx = random_util.random_pan_rotations(model_config.hparams.bs)
Predict the next line for this snippet: <|code_start|># Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Tests for ldif.hparams.""" # LDIF is an internal package, should be imported last. # pylint: disable=g-bad-import-order # pylint: enable=g-bad-import-order class HparamsTest(googletest.TestCase): def test_read_and_write(self): with tempfile.NamedTemporaryFile(delete=False) as fname: <|code_end|> with the help of current file imports: import tempfile from tensorflow.python.platform import googletest from ldif.model import hparams and context from other files: # Path: ldif/model/hparams.py # def backwards_compatible_hparam_defaults(ident): # def tf_hparams_to_dict(tf_hparams): # def build_ldif_hparams(): # def build_sif_hparams(): # def build_improved_sif_hparams(): # def build_singleview_depth_hparams(): # def write_hparams(hparams, path): # def read_hparams_with_new_backwards_compatible_additions(path): # def read_hparams(path): , which may contain function names, class names, or code. Output only the next line.
hparams.write_hparams(hparams.autoencoder_hparams, fname.name)
Continue the code snippet: <|code_start|># Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Metrics for evaluating structured implicit functions.""" # LDIF is an internal package, should be imported last. # pylint: disable=g-bad-import-order # pylint: enable=g-bad-import-order def point_iou(structured_implicit, sample_locations, sample_gt, model_config): """Estimates the mesh iou by taking the iou from uniform point samples.""" assert model_config.hparams.bs == 1 # Otherwise the result would be wrong pred_class, _ = structured_implicit.class_at_samples(sample_locations) <|code_end|> . Use current file imports: import tensorflow as tf from ldif.util import sdf_util and context (classes, functions, or code) from other files: # Path: ldif/util/sdf_util.py # def apply_class_transfer(sdf, model_config, soft_transfer, offset, dtype=None): # def apply_density_transfer(sdf): . Output only the next line.
gt_is_inside = tf.logical_not(sdf_util.apply_class_transfer(
Predict the next line for this snippet: <|code_start|># https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Refines a prediction according to an observation using gradient descent.""" # LDIF is an internal package, should be imported last. # pylint: disable=g-bad-import-order # pylint: enable=g-bad-import-order def sample_gradients_wrt_placeholders(model_config, training_example, prediction, samples): """Creates gradient ops for refining a quadric prediction.""" structured_implicit_ph = prediction.structured_implicit.as_placeholder() sample_shape = samples.get_shape().as_list() target_shape = samples.get_shape().as_list() target_shape[-1] = 1 # The target is a function value, not an xyz position. samples_ph = tf.placeholder(tf.float32, shape=sample_shape) target_f_ph = tf.placeholder(tf.float32, shape=target_shape) # TODO(kgenova): One way to test whether trilinear interpolation is a problem # or it's some gradient sharing (?) is to replace this with an on-grid # evaluation. <|code_end|> with the help of current file imports: import numpy as np import tensorflow as tf from ldif.training import loss and context from other files: # Path: ldif/training/loss.py # def bounding_box_constraint_error(samples, box): # def shape_element_center_magnitude_loss(model_config, _, structured_implicit): # def element_center_lowres_grid_direct_loss(model_config, training_example, # structured_implicit): # def element_center_lowres_grid_squared_loss(model_config, training_example, # structured_implicit): # def element_center_lowres_grid_inside_loss(model_config, training_example, # structured_implicit): # def smooth_element_center_lowres_grid_inside_loss(model_config, # training_example, # structured_implicit): # def center_variance_loss(model_config, training_example, structured_implicit): # pylint:disable=unused-argument # def center_nn_loss(model_config, training_example, structured_implicit): # pylint:disable=unused-argument # def inside_box_loss(model_config, _, structured_implicit): # def shape_element_center_loss(model_config, training_example, # structured_implicit): # def old_shape_element_center_loss(model_config, training_example, # structured_implicit): # def weighted_l2_loss(gt_value, pred_value, weights): # def sample_loss(model_config, gt_sdf, structured_implicit, global_samples, name, # apply_ucf): # def uniform_sample_loss(model_config, training_example, structured_implicit): # def overlap_loss(model_config, training_example, structured_implicit): # def near_surface_sample_loss(model_config, training_example, # structured_implicit): # def compute_loss(model_config, training_example, structured_implicit): # def set_loss(model_config, training_example, structured_implicit): , which may contain function names, class names, or code. Output only the next line.
loss_val = loss.sample_loss(
Continue the code snippet: <|code_start|># Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Builds the worker tasks for the beam job.""" # LDIF is an internal package, should be imported last. # pylint: disable=g-bad-import-order # pylint: enable=g-bad-import-order def generate_models(flags): """Makes all the dictionaries that workers can process in parallel.""" # TODO(kgenova) If the code fails here, add a model_dir argument. cur_experiment = experiment.Experiment(flags.model_dir, flags.model_name, flags.experiment_name) <|code_end|> . Use current file imports: import sys from ldif.inference import experiment from ldif.inference import util as inference_util from ldif.util.file_util import log and context (classes, functions, or code) from other files: # Path: ldif/inference/experiment.py # def to_xid(job): # def __init__(self, parent_job, idx): # def relpath(self): # def directory(self): # def abspath(self): # def __init__(self, parent_experiment, job_str, use_temp_ckpts='warn'): # def from_xid(cls, parent_experiment, xid): # def _ensure_lazy_attrs_are_zero(self): # def set_use_temp_ckpts(self, useable): # def is_visible(self): # def ensure_visible(self): # def ckpt_dir(self): # def root_dir(self): # def all_checkpoint_indices(self): # def all_checkpoints(self): # def latest_checkpoint_before(self, idx, must_equal=False): # def has_at_least_one_checkpoint(self): # def ensure_has_at_least_one_checkpoint(self): # def checkpoint_count(self): # def newest_checkpoint(self): # def k_evenly_spaced_checkpoints(self, k): # def hparams(self): # def model_config(self): # def __init__(self, model_dir, model_name, experiment_name): # def set_order(self, ordered_xids): # def job_with_xid(self, xid): # def filter_jobs_by_xid(self, xids): # def visible_jobs(self): # def visible_job_count(self): # def visible_xids(self): # def job_from_xmanager_id(self, xid, must_be_visible=True): # def job_from_job_str(self, job_str, must_be_visible=True): # def __init__(self, experiment, desired_ckpts=-1): # def local_root(self): # def remote_root(self): # def remote_result_ckpt_dir(self, xid): # def local_result_ckpt_dir(self, xid): # def ckpts_for_xid_and_split(self, xid, split): # def ckpt_for_xid(self, xid, split): # def remote_result_base(self, xid, split): # def all_remote_mesh_names(self, split, ensure_nonempty=True): # def copy_meshes(self, mesh_names, split, overwrite_if_present=True): # def random_remote_mesh_names(self, count, split): # def remote_path_to_mesh(self, mesh_name, xid, split): # def local_path_to_mesh(self, mesh_name, xid, split): # def _mesh_relative_path(self, mesh_name): # def local_qual_path(self): # def __init__(self, hparams): # class Checkpoint(object): # class Job(object): # class Experiment(object): # class ResultStore(object): # class ModelConfig(object): # # Path: ldif/inference/util.py # def parse_xid_str(xidstr): # def ensure_split_valid(split): # def ensure_category_valid(category): # def ensure_synset_valid(synset): # def ensure_hash_valid(h): # def parse_xid_to_ckpt(xid_to_ckpt): # def get_npz_paths(split, category, modifier=''): # def get_mesh_identifiers(split, category): # def get_rgb_paths(split, category, modifier=''): # def rgb_path_to_synset_and_hash(rgb_path): # def rgb_path_to_npz_path(rgb_path, split, dataset='shapenet-occnet'): # def parse_npz_path(path): # def read_png_to_float_npy_with_reraising(path): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): . Output only the next line.
xids = inference_util.parse_xid_str(flags.xids)
Next line prediction: <|code_start|># you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Builds the worker tasks for the beam job.""" # LDIF is an internal package, should be imported last. # pylint: disable=g-bad-import-order # pylint: enable=g-bad-import-order def generate_models(flags): """Makes all the dictionaries that workers can process in parallel.""" # TODO(kgenova) If the code fails here, add a model_dir argument. cur_experiment = experiment.Experiment(flags.model_dir, flags.model_name, flags.experiment_name) xids = inference_util.parse_xid_str(flags.xids) cur_experiment.filter_jobs_by_xid(xids) cur_experiment.set_order(xids) <|code_end|> . Use current file imports: (import sys from ldif.inference import experiment from ldif.inference import util as inference_util from ldif.util.file_util import log) and context including class names, function names, or small code snippets from other files: # Path: ldif/inference/experiment.py # def to_xid(job): # def __init__(self, parent_job, idx): # def relpath(self): # def directory(self): # def abspath(self): # def __init__(self, parent_experiment, job_str, use_temp_ckpts='warn'): # def from_xid(cls, parent_experiment, xid): # def _ensure_lazy_attrs_are_zero(self): # def set_use_temp_ckpts(self, useable): # def is_visible(self): # def ensure_visible(self): # def ckpt_dir(self): # def root_dir(self): # def all_checkpoint_indices(self): # def all_checkpoints(self): # def latest_checkpoint_before(self, idx, must_equal=False): # def has_at_least_one_checkpoint(self): # def ensure_has_at_least_one_checkpoint(self): # def checkpoint_count(self): # def newest_checkpoint(self): # def k_evenly_spaced_checkpoints(self, k): # def hparams(self): # def model_config(self): # def __init__(self, model_dir, model_name, experiment_name): # def set_order(self, ordered_xids): # def job_with_xid(self, xid): # def filter_jobs_by_xid(self, xids): # def visible_jobs(self): # def visible_job_count(self): # def visible_xids(self): # def job_from_xmanager_id(self, xid, must_be_visible=True): # def job_from_job_str(self, job_str, must_be_visible=True): # def __init__(self, experiment, desired_ckpts=-1): # def local_root(self): # def remote_root(self): # def remote_result_ckpt_dir(self, xid): # def local_result_ckpt_dir(self, xid): # def ckpts_for_xid_and_split(self, xid, split): # def ckpt_for_xid(self, xid, split): # def remote_result_base(self, xid, split): # def all_remote_mesh_names(self, split, ensure_nonempty=True): # def copy_meshes(self, mesh_names, split, overwrite_if_present=True): # def random_remote_mesh_names(self, count, split): # def remote_path_to_mesh(self, mesh_name, xid, split): # def local_path_to_mesh(self, mesh_name, xid, split): # def _mesh_relative_path(self, mesh_name): # def local_qual_path(self): # def __init__(self, hparams): # class Checkpoint(object): # class Job(object): # class Experiment(object): # class ResultStore(object): # class ModelConfig(object): # # Path: ldif/inference/util.py # def parse_xid_str(xidstr): # def ensure_split_valid(split): # def ensure_category_valid(category): # def ensure_synset_valid(synset): # def ensure_hash_valid(h): # def parse_xid_to_ckpt(xid_to_ckpt): # def get_npz_paths(split, category, modifier=''): # def get_mesh_identifiers(split, category): # def get_rgb_paths(split, category, modifier=''): # def rgb_path_to_synset_and_hash(rgb_path): # def rgb_path_to_npz_path(rgb_path, split, dataset='shapenet-occnet'): # def parse_npz_path(path): # def read_png_to_float_npy_with_reraising(path): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): . Output only the next line.
log.info('XIDs to run on: %s' % repr(cur_experiment.visible_xids))
Given snippet: <|code_start|> if synset not in synset_to_cat: raise ValueError('Unrecognized synset: %s' % repr(synset)) def ensure_hash_valid(h): """This does not guarantee only hashes get through, it's best-effort.""" passes = True if not isinstance(h, str): passes = False elif [x for x in h if x not in '0123456789abcdef-u']: passes = False if not passes: raise ValueError('Invalid hash: %s' % repr(h)) def parse_xid_to_ckpt(xid_to_ckpt): tokens = [int(x) for x in xid_to_ckpt.split(',')] xids = tokens[::2] ckpts = tokens[1::2] return {k: v for (k, v) in zip(xids, ckpts)} def get_npz_paths(split, category, modifier=''): """Returns the list of npz paths for the split's ground truth.""" t = time.time() ensure_split_valid(split) filelist = os.path.join( path_util.get_path_to_ldif_root(), 'data/basedirs/%s-%s%s.txt' % (split, category, modifier)) try: <|code_end|> , continue by predicting the next line. Consider current file imports: import os import time import tensorflow as tf from ldif.util import file_util from ldif.util import path_util and context: # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): # # Path: ldif/util/path_util.py # def get_path_to_ldif_root(): # def get_path_to_ldif_parent(): # def package_to_abs(path): # def gaps_path(): # def test_data_path(): # def util_test_data_path(): # def create_test_output_dir(): which might include code, classes, or functions. Output only the next line.
filenames = file_util.readlines(filelist)
Given snippet: <|code_start|> def ensure_synset_valid(synset): if synset not in synset_to_cat: raise ValueError('Unrecognized synset: %s' % repr(synset)) def ensure_hash_valid(h): """This does not guarantee only hashes get through, it's best-effort.""" passes = True if not isinstance(h, str): passes = False elif [x for x in h if x not in '0123456789abcdef-u']: passes = False if not passes: raise ValueError('Invalid hash: %s' % repr(h)) def parse_xid_to_ckpt(xid_to_ckpt): tokens = [int(x) for x in xid_to_ckpt.split(',')] xids = tokens[::2] ckpts = tokens[1::2] return {k: v for (k, v) in zip(xids, ckpts)} def get_npz_paths(split, category, modifier=''): """Returns the list of npz paths for the split's ground truth.""" t = time.time() ensure_split_valid(split) filelist = os.path.join( <|code_end|> , continue by predicting the next line. Consider current file imports: import os import time import tensorflow as tf from ldif.util import file_util from ldif.util import path_util and context: # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): # # Path: ldif/util/path_util.py # def get_path_to_ldif_root(): # def get_path_to_ldif_parent(): # def package_to_abs(path): # def gaps_path(): # def test_data_path(): # def util_test_data_path(): # def create_test_output_dir(): which might include code, classes, or functions. Output only the next line.
path_util.get_path_to_ldif_root(),
Predict the next line for this snippet: <|code_start|> if p[-4:] != '.npz': raise ValueError(f'Expected .npz ending for file {p}.') with base_util.FS.open(p, 'rb') as f: arr = dict(np.load(f, allow_pickle=True)) return arr def read_np(p): if p[-4:] != '.npy': raise ValueError(f'Expected .npy ending for file {p}.') with base_util.FS.open(p, 'rb') as f: arr = np.load(f) return arr def read_txt_to_np(p): with base_util.FS.open(p, 'rt') as f: return np.loadtxt(f) def read_py2_pkl(p): if p[-4:] != '.pkl': raise ValueError(f'Expected .pkl ending for file {p}.') with base_util.FS.open(p, 'rb') as f: # pkl = dict(np.load(f, allow_pickle=True)) pkl = pickle.load(f, encoding='latin1') return pkl def write_mesh(path, mesh): <|code_end|> with the help of current file imports: import os import pickle import struct import numpy as np import pandas as pd from PIL import Image from ldif.util import base_util from ldif.util import mesh_util and context from other files: # Path: ldif/util/base_util.py # ENVIRONMENT = 'EXTERNAL' # FS = StandardFileSystem() # LOG = SimpleLog() # class FileSystem(abc.ABC): # class StandardFileSystem(FileSystem): # class Log(abc.ABC): # class SimpleLog(Log): # def open(self, filename, mode): # def mkdir(self, path, exist_ok=False): # def makedirs(self, path, exist_ok=False): # def glob(self, path): # def exists(self, path): # def cp(self, from_path, to_path): # def rm(self, path): # def mkdir(self, path, exist_ok=False): # def makedirs(self, path, exist_ok=False): # def open(self, *args): # def glob(self, *args): # def exists(self, *args): # def cp(self, *args): # def rm(self, *args): # def log(self, msg, level='info'): # def levels(self): # def level_index(self, level): # def __init__(self): # def log(self, msg, level='info'): # def verbose(self, msg): # def info(self, msg): # def warning(self, msg): # def error(self, msg): # def set_level(self, level): # # Path: ldif/util/mesh_util.py # def serialize(mesh): # def deserialize(mesh_str): # def remove_small_components(mesh, min_volume=5e-05): , which may contain function names, class names, or code. Output only the next line.
mesh_str = mesh_util.serialize(mesh)
Given the following code snippet before the placeholder: <|code_start|> zero = tf.zeros_like(st) one = tf.ones_like(st) base_rot = tf.stack([ct, st, zero, -st, ct, zero, zero, zero, one], axis=-1) base_rot = tf.reshape(base_rot, [batch_size, 3, 3]) v_outer = tf.matmul(v[:, :, tf.newaxis], v[:, tf.newaxis, :]) rotation_3x3 = tf.matmul(v_outer - tf.eye(3, batch_shape=[batch_size]), base_rot) return rotation_to_tx(rotation_3x3) def random_rotation_np(): """Returns a uniformly random SO(3) rotation as a [3,3] numpy array.""" vals = np.random.uniform(size=(3,)) theta = vals[0] * 2.0 * np.pi phi = vals[1] * 2.0 * np.pi z = 2.0 * vals[2] r = np.sqrt(z) v = np.stack([r * np.sin(phi), r * np.cos(phi), np.sqrt(2.0 * (1 - vals[2]))]) st = np.sin(theta) ct = np.cos(theta) base_rot = np.array([[ct, st, 0], [-st, ct, 0], [0, 0, 1]], dtype=np.float32) return (np.outer(v, v) - np.eye(3)).dot(base_rot) def random_scales(batch_size, minval, maxval): scales = tf.random.uniform( shape=[batch_size, 3], minval=minval, maxval=maxval) hom_coord = tf.ones([batch_size, 1], dtype=tf.float32) scales = tf.concat([scales, hom_coord], axis=1) s = tf.linalg.diag(scales) <|code_end|> , predict the next line using imports from the current file: import importlib import math import numpy as np import tensorflow as tf from ldif.util import geom_util from ldif.util.file_util import log and context including class names, function names, and sometimes code from other files: # Path: ldif/util/geom_util.py # def ray_sphere_intersect(ray_start, ray_direction, sphere_center, sphere_radius, # max_t): # def to_homogeneous(t, is_point): # def transform_points_with_normals(points, tx, normals=None): # def transform_featured_points(points, tx): # def rotation_to_tx(rot): # def extract_points_near_origin(points, count, features=None): # def local_views_of_shape(global_points, # world2local, # local_point_count, # global_normals=None, # global_features=None, # zeros_invalid=False, # zero_threshold=1e-6, # expand_region=True, # threshold=4.0): # def chamfer_distance(pred, target): # def dodeca_parameters(dodeca_idx): # def get_camera_to_world(viewpoint, center, world_up): # def get_dodeca_camera_to_worlds(): # def gaps_depth_render_to_xyz(model_config, depth_image, camera_parameters): # def angle_of_rotation_to_2d_rotation_matrix(angle_of_rotation): # def fractional_vector_projection(e0, e1, p, falloff=2.0): # def rotate_about_point(angle_of_rotation, point, to_rotate): # def interpolate_from_grid(samples, grid): # def reflect(samples, reflect_x=False, reflect_y=False, reflect_z=False): # def z_reflect(samples): # def get_world_to_camera(idx): # def transform_depth_dodeca_to_xyz_dodeca(depth_dodeca): # def transform_depth_dodeca_to_xyz_dodeca_np(depth_dodeca): # def _unbatch(arr): # def to_homogenous_np(arr, is_point=True): # def depth_to_cam_np(im, xfov=0.5): # def apply_tx_np(samples, tx, is_point=True): # def depth_image_to_sdf_constraints(im, cam2world, xfov=0.5): # def depth_dodeca_to_sdf_constraints(depth_ims): # def depth_dodeca_to_samples(dodeca): # def depth_image_to_class_constraints(im, cam2world, xfov=0.5): # def depth_image_to_samples(im, cam2world, xfov=0.5): # pylint:disable=unused-argument # def apply_4x4(tensor, tx, are_points=True, batch_rank=None, sample_rank=None): # def depth_image_to_xyz_image(depth_images, world_to_camera, xfov=0.5): # def interpolate_from_grid_coordinates(samples, grid): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): . Output only the next line.
log.info(s.get_shape().as_list())
Next line prediction: <|code_start|># Lint as: python3 """Tests for ldif.util.math_util.""" # LDIF is an internal package, should be imported last. # pylint: disable=g-bad-import-order # pylint: enable=g-bad-import-order FLOAT_DISTANCE_EPS = 1e-5 class MathUtilTest(tf.test.TestCase): @parameterized.expand([('no_flatten', False), ('flatten', True)]) def test_increase_frequency(self, name, flatten): tf.disable_eager_execution() x = np.array([1.0, 0.1123, 0.7463], dtype=np.float32) dim = 3 # pylint:disable=bad-whitespace expected = [ [0, -1, 0, 1, 0, 1 ], [0.345528, 0.938409, 0.648492, 0.761221, 0.987292, 0.158916], [0.715278, -0.69884, -0.99973, -0.0232457, 0.0464788, -0.998919] ] # pylint:enable=bad-whitespace expected = np.array(expected, dtype=np.float32) if flatten: expected = np.reshape(expected, [-1]) <|code_end|> . Use current file imports: (import numpy as np import tensorflow as tf from parameterized import parameterized from ldif.util import math_util) and context including class names, function names, or small code snippets from other files: # Path: ldif/util/math_util.py # def int_log2(i): # def nonzero_mean(tensor): # def increase_frequency(t, out_dim, flatten=False, interleave=True): . Output only the next line.
y = math_util.increase_frequency(
Predict the next line after this snippet: <|code_start|>def transform_depth_dodeca_to_xyz_dodeca_np(depth_dodeca): graph = tf.Graph() with graph.as_default(): depth_in = tf.constant(depth_dodeca) xyz_out = transform_depth_dodeca_to_xyz_dodeca(depth_in) with tf.Session() as session: out_np = session.run(xyz_out) return out_np def _unbatch(arr): if arr.shape[0] == 1: return arr.reshape(arr.shape[1:]) return arr def to_homogenous_np(arr, is_point=True): assert arr.shape[-1] in [2, 3] homogeneous_shape = list(arr.shape[:-1]) + [1] if is_point: coord = np.ones(homogeneous_shape, dtype=np.float32) else: coord = np.zeros(homogeneous_shape, dtype=np.float32) return np.concatenate([arr, coord], axis=-1) def depth_to_cam_np(im, xfov=0.5): """Converts a gaps depth image to camera space.""" im = _unbatch(im) height, width, _ = im.shape <|code_end|> using the current file's imports: import math import numpy as np import tensorflow as tf from ldif.util import np_util from ldif.util import camera_util from ldif.util import tf_util and any relevant context from other files: # Path: ldif/util/np_util.py # def batch_np(arr, batch_size): # def make_coordinate_grid(height, width, is_screen_space, is_homogeneous): # def make_coordinate_grid_3d(length, height, width, is_screen_space, # is_homogeneous): # def filter_valid(mask, vals): # def zero_by_mask(mask, vals, replace_with=0.0): # def make_mask(im, thresh=0.0): # def make_pixel_mask(im): # def thresh_and_radius_to_distance(radius, thresh): # def plot_rbfs_at_thresh(centers, radii, thresh=0.5): # def plot_rbfs(centers, radii, scale=10.0): # def cube_and_render(volume, thresh): # def sample_surface(quadrics, centers, radii, length, height, width, # renormalize): # def visualize_prediction(quadrics, # centers, # radii, # renormalize, # thresh=0.0, # input_volumes=None): # # Path: ldif/util/camera_util.py # def look_at(eye, center, world_up): # def roll_pitch_yaw_to_rotation_matrices(roll_pitch_yaw): # # Path: ldif/util/tf_util.py # def assert_shape(tensor, shape, name): # def log(msg, t): # def tile_new_axis(t, axis, length): # def zero_by_mask(mask, vals, replace_with=0.0): # def remove_element(t, elt, axis): . Output only the next line.
pixel_coords = np_util.make_coordinate_grid(
Given the following code snippet before the placeholder: <|code_start|> assert isinstance(reflect_x, bool) assert isinstance(reflect_y, bool) assert isinstance(reflect_z, bool) floats = [-1.0 if ax else 1.0 for ax in [reflect_x, reflect_y, reflect_z]] mult = np.array(floats, dtype=np.float32) shape = samples.get_shape().as_list() leading_dims = shape[:-1] assert shape[-1] == 3 mult = mult.reshape([1] * len(leading_dims) + [3]) mult = tf.constant(mult, dtype=tf.float32) return mult * samples def z_reflect(samples): """Reflects the sample locations across the XY plane. Args: samples: Tensor with shape [..., 3] Returns: reflected: Tensor with shape [..., 3]. The reflected samples. """ return reflect(samples, reflect_z=True) def get_world_to_camera(idx): assert idx == 1 eye = tf.constant([[0.671273, 0.757946, -0.966907]], dtype=tf.float32) look_at = tf.zeros_like(eye) world_up = tf.constant([[0., 1., 0.]], dtype=tf.float32) <|code_end|> , predict the next line using imports from the current file: import math import numpy as np import tensorflow as tf from ldif.util import np_util from ldif.util import camera_util from ldif.util import tf_util and context including class names, function names, and sometimes code from other files: # Path: ldif/util/np_util.py # def batch_np(arr, batch_size): # def make_coordinate_grid(height, width, is_screen_space, is_homogeneous): # def make_coordinate_grid_3d(length, height, width, is_screen_space, # is_homogeneous): # def filter_valid(mask, vals): # def zero_by_mask(mask, vals, replace_with=0.0): # def make_mask(im, thresh=0.0): # def make_pixel_mask(im): # def thresh_and_radius_to_distance(radius, thresh): # def plot_rbfs_at_thresh(centers, radii, thresh=0.5): # def plot_rbfs(centers, radii, scale=10.0): # def cube_and_render(volume, thresh): # def sample_surface(quadrics, centers, radii, length, height, width, # renormalize): # def visualize_prediction(quadrics, # centers, # radii, # renormalize, # thresh=0.0, # input_volumes=None): # # Path: ldif/util/camera_util.py # def look_at(eye, center, world_up): # def roll_pitch_yaw_to_rotation_matrices(roll_pitch_yaw): # # Path: ldif/util/tf_util.py # def assert_shape(tensor, shape, name): # def log(msg, t): # def tile_new_axis(t, axis, length): # def zero_by_mask(mask, vals, replace_with=0.0): # def remove_element(t, elt, axis): . Output only the next line.
world_to_camera = camera_util.look_at(eye, look_at, world_up)
Predict the next line after this snippet: <|code_start|> axis=3) flat_camera_xyzw = tf.reshape(camera_xyz, [batch_size, height * width, 4]) flat_world_xyz = tf.matmul( flat_camera_xyzw, camera_to_world_mat, transpose_b=True) world_xyz = tf.reshape(flat_world_xyz, [batch_size, height, width, 4]) world_xyz = world_xyz[:, :, :, :3] return world_xyz, flat_camera_xyzw[:, :, :3], flat_nic_xyz def interpolate_from_grid_coordinates(samples, grid): """Performs trilinear interpolation to estimate the value of a grid function. This function makes several assumptions to do the lookup: 1) The grid is LHW and has evenly spaced samples in the range (0, 1), which is really the screen space range [0.5, {L, H, W}-0.5]. Args: samples: Tensor with shape [batch_size, sample_count, 3]. grid: Tensor with shape [batch_size, length, height, width, 1]. Returns: sample: Tensor with shape [batch_size, sample_count, 1] and type float32. mask: Tensor with shape [batch_size, sample_count, 1] and type float32 """ batch_size, length, height, width = grid.get_shape().as_list()[:4] # These asserts aren't required by the algorithm, but they are currently # true for the pipeline: assert length == height assert length == width sample_count = samples.get_shape().as_list()[1] <|code_end|> using the current file's imports: import math import numpy as np import tensorflow as tf from ldif.util import np_util from ldif.util import camera_util from ldif.util import tf_util and any relevant context from other files: # Path: ldif/util/np_util.py # def batch_np(arr, batch_size): # def make_coordinate_grid(height, width, is_screen_space, is_homogeneous): # def make_coordinate_grid_3d(length, height, width, is_screen_space, # is_homogeneous): # def filter_valid(mask, vals): # def zero_by_mask(mask, vals, replace_with=0.0): # def make_mask(im, thresh=0.0): # def make_pixel_mask(im): # def thresh_and_radius_to_distance(radius, thresh): # def plot_rbfs_at_thresh(centers, radii, thresh=0.5): # def plot_rbfs(centers, radii, scale=10.0): # def cube_and_render(volume, thresh): # def sample_surface(quadrics, centers, radii, length, height, width, # renormalize): # def visualize_prediction(quadrics, # centers, # radii, # renormalize, # thresh=0.0, # input_volumes=None): # # Path: ldif/util/camera_util.py # def look_at(eye, center, world_up): # def roll_pitch_yaw_to_rotation_matrices(roll_pitch_yaw): # # Path: ldif/util/tf_util.py # def assert_shape(tensor, shape, name): # def log(msg, t): # def tile_new_axis(t, axis, length): # def zero_by_mask(mask, vals, replace_with=0.0): # def remove_element(t, elt, axis): . Output only the next line.
tf_util.assert_shape(samples, [batch_size, sample_count, 3],
Next line prediction: <|code_start|> mean_max_weight = tf.reduce_mean(tf.reduce_max(five_dim_rbf, axis=1)) tf.summary.scalar('%s-mean_max_rbf_weight' % dataset_split, mean_max_weight) peak_weight = tf.reduce_max(five_dim_rbf) tf.summary.scalar('%s-peak_rbf_weight' % dataset_split, peak_weight) mean_total_weight = tf.reduce_mean(tf.reduce_sum(five_dim_rbf, axis=1)) tf.summary.scalar('%s-mean_total_rbf_weight' % dataset_split, mean_total_weight) frac_of_biggest = tf.divide( tf.reduce_max(five_dim_rbf, axis=1), tf.reduce_sum(five_dim_rbf, axis=1)) mean_frac_of_biggest = tf.reduce_mean(frac_of_biggest) tf.summary.scalar('%s-mean_plurality_frac' % dataset_split, mean_frac_of_biggest) pixel_count_above_half_weight = tf.count_nonzero( five_dim_rbf > 0.5, axis=[2, 3, 4]) / ( length * height * width) tf.summary.histogram('%s-pixel_count_above_half_weight' % dataset_split, pixel_count_above_half_weight) pixel_count_above_tenth_weight = tf.count_nonzero( five_dim_rbf > 0.1, axis=[2, 3, 4]) / ( length * height * width) tf.summary.histogram('%s-pixel_count_above_tenth_weight' % dataset_split, pixel_count_above_tenth_weight) # TODO(kgenova) Make a summarizer class that handles all this so the model # config doesn't need to get passed over and over, and so that it's easy to # deal with the tensorflow boilerplate. def summarize_in_out_image(model_config, prediction): # pylint:disable=unused-argument <|code_end|> . Use current file imports: (from matplotlib import cm from ldif.util.file_util import log import numpy as np import tensorflow as tf) and context including class names, function names, or small code snippets from other files: # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): . Output only the next line.
log.info('In-out image summaries have been removed.')
Next line prediction: <|code_start|> conv_layer_depths=conv_layer_depths, fc_layer_depths=[encoded_image_length], name='Encoder') if reencode_partial_outputs: encoded_partial_output, _, _ = net_util.encode( tf.ones_like(inputs), model_config, conv_layer_depths=conv_layer_depths, fc_layer_depths=[encoded_image_length], name='OutputReencoder') else: encoded_partial_output = None lstm = tf.contrib.rnn.MultiRNNCell([ tf.contrib.rnn.BasicLSTMCell(lstm_size) for _ in range(number_of_layers) ]) state = lstm.zero_state(batch_size, tf.float32) partial_images = [] for i in range(number_of_lines): if reencode_partial_outputs: embedding_in = tf.concat([encoded_image, encoded_partial_output], axis=-1) else: embedding_in = encoded_image output, state = lstm(embedding_in, state) line_parameters = tf.contrib.layers.fully_connected( inputs=output, num_outputs=line_embedding_size, activation_fn=None, normalizer_fn=None) <|code_end|> . Use current file imports: (import tensorflow as tf from ldif.util import line_util from ldif.util import net_util) and context including class names, function names, or small code snippets from other files: # Path: ldif/util/line_util.py # def line_to_image(line_parameters, height, width, falloff=2.0): # def fractional_vector_projection(e0, e1, p, falloff=2.0): # def rotate_about_point(angle_of_rotation, point, to_rotate): # def union_of_line_drawings(lines): # def network_line_parameters_to_line(line_parameters, height, width): # # Path: ldif/util/net_util.py # def twin_inference(inference_fun, observation, element_count, # flat_element_length, model_config): # def get_normalizer_and_mode(model_config): # def conv_layer(inputs, depth, model_config): # def maxpool2x2_layer(inputs): # def down_layer(inputs, depth, model_config): # def up_layer(inputs, spatial_dims, depth, model_config): # def encode(inputs, # model_config, # conv_layer_depths, # fc_layer_depths, # name='Encoder'): # def inputs_to_feature_vector(inputs, feature_length, model_config): # def decode(z, # model_config, # spatial_dims, # fc_layer_depths, # conv_layer_depths, # output_dim, # name='Decoder'): # def residual_layer(inputs, num_outputs, model_config): . Output only the next line.
current_image = line_util.network_line_parameters_to_line(
Based on the snippet: <|code_start|># https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Nets for predicting 2D lines.""" # LDIF is an internal package, should be imported last. # pylint: disable=g-bad-import-order # pylint: enable=g-bad-import-order def lstm_lines_transcoder(inputs, model_config): """A model that uses an LSTM to predict a sequence of lines.""" batch_size = model_config.hparams.bs height = model_config.hparams.h width = model_config.hparams.w conv_layer_depths = [16, 32, 64, 128, 128] number_of_lines = model_config.hparams.sc # Was 4! number_of_layers = model_config.hparams.cc line_embedding_size = 5 encoded_image_length = 1024 # embedding_size = line_embedding_size * number_of_lines lstm_size = model_config.hparams.hlw reencode_partial_outputs = True <|code_end|> , predict the immediate next line with the help of imports: import tensorflow as tf from ldif.util import line_util from ldif.util import net_util and context (classes, functions, sometimes code) from other files: # Path: ldif/util/line_util.py # def line_to_image(line_parameters, height, width, falloff=2.0): # def fractional_vector_projection(e0, e1, p, falloff=2.0): # def rotate_about_point(angle_of_rotation, point, to_rotate): # def union_of_line_drawings(lines): # def network_line_parameters_to_line(line_parameters, height, width): # # Path: ldif/util/net_util.py # def twin_inference(inference_fun, observation, element_count, # flat_element_length, model_config): # def get_normalizer_and_mode(model_config): # def conv_layer(inputs, depth, model_config): # def maxpool2x2_layer(inputs): # def down_layer(inputs, depth, model_config): # def up_layer(inputs, spatial_dims, depth, model_config): # def encode(inputs, # model_config, # conv_layer_depths, # fc_layer_depths, # name='Encoder'): # def inputs_to_feature_vector(inputs, feature_length, model_config): # def decode(z, # model_config, # spatial_dims, # fc_layer_depths, # conv_layer_depths, # output_dim, # name='Decoder'): # def residual_layer(inputs, num_outputs, model_config): . Output only the next line.
encoded_image, _, _ = net_util.encode(
Continue the code snippet: <|code_start|># # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Utilities for building neural networks.""" # LDIF is an internal package, should be imported last. # pylint: disable=g-bad-import-order # pylint: enable=g-bad-import-order def twin_inference(inference_fun, observation, element_count, flat_element_length, model_config): """Predicts both explicit and implicit parameters for each shape element.""" element_embedding_length = model_config.hparams.ips # if element_embedding_length == 0: # raise ValueError( # 'Twin Inference networks requires a nonzero imlicit parameter count.') remaining_length = flat_element_length - element_embedding_length if remaining_length <= 0: <|code_end|> . Use current file imports: import functools import tensorflow as tf import tensorflow.contrib.layers as contrib_layers from ldif.util.file_util import log and context (classes, functions, or code) from other files: # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): . Output only the next line.
log.warning('Using less-tested option: single-tower in twin-tower.')
Continue the code snippet: <|code_start|> d['arch'] = 'efcnn' d['samp'] = 'imdpn' d['cnna'] = 's50' d['hyo'] = 'f' d['hyp'] = 'f' d['sc'] = 32 d['lyr'] = 16 d['loss'] = 'unsbbgi' d['mfc'] = 512 d['ips'] = 0 d['ipe'] = 'f' return tf.contrib.training.HParams(**d) def build_singleview_depth_hparams(): """A singleview-depth architecture.""" d = tf_hparams_to_dict(autoencoder_hparams) d['h'] = 224 d['w'] = 224 d['cnna'] = 's50' d['samp'] = 'im1xyzpn' d['didx'] = 0 d['ia'] = 'p' d['sc'] = 32 d['lyr'] = 16 return tf.contrib.training.HParams(**d) def write_hparams(hparams, path): d = tf_hparams_to_dict(hparams) <|code_end|> . Use current file imports: import pickle import tensorflow as tf from ldif.util import file_util from ldif.util.file_util import log and context (classes, functions, or code) from other files: # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): . Output only the next line.
file_util.writebin(path, pickle.dumps(d))
Continue the code snippet: <|code_start|> d['loss'] = 'unsbbgi' d['mfc'] = 512 d['ips'] = 0 d['ipe'] = 'f' return tf.contrib.training.HParams(**d) def build_singleview_depth_hparams(): """A singleview-depth architecture.""" d = tf_hparams_to_dict(autoencoder_hparams) d['h'] = 224 d['w'] = 224 d['cnna'] = 's50' d['samp'] = 'im1xyzpn' d['didx'] = 0 d['ia'] = 'p' d['sc'] = 32 d['lyr'] = 16 return tf.contrib.training.HParams(**d) def write_hparams(hparams, path): d = tf_hparams_to_dict(hparams) file_util.writebin(path, pickle.dumps(d)) return def read_hparams_with_new_backwards_compatible_additions(path): """Reads hparams from a file and adds in any new backwards compatible ones.""" kvs = pickle.loads(file_util.readbin(path)) <|code_end|> . Use current file imports: import pickle import tensorflow as tf from ldif.util import file_util from ldif.util.file_util import log and context (classes, functions, or code) from other files: # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): . Output only the next line.
log.verbose('Loaded %s' % repr(kvs))
Based on the snippet: <|code_start|> Returns: Tensor with shape [batch_size, sample_count, 1]. """ if model_config.hparams.hyo == 't': samples = math_util.nerfify(samples, 10, flatten=True, interleave=True) sample_len = 60 else: sample_len = 3 if model_config.hparams.dd == 't': tf.logging.info( 'BID0: Running SS Occnet Decoder with input shapes embedding=%s, samples=%s', repr(embedding.get_shape().as_list()), repr(samples.get_shape().as_list())) ensure_shape(embedding, [1, -1]) ensure_shape(samples, [1, -1, 3]) vals = one_shape_occnet_decoder( remove_batch_dim(embedding), remove_batch_dim(samples), apply_sigmoid, model_config) return add_batch_dim(vals) batch_size, embedding_length = embedding.get_shape().as_list() ensure_shape(embedding, [batch_size, embedding_length]) ensure_shape(samples, [batch_size, -1, sample_len]) # Debugging: vals = multishape_occnet_decoder(embedding, samples, apply_sigmoid, model_config) return vals def occnet_encoder(inputs, model_config): ensure_rank(inputs, 5) <|code_end|> , predict the immediate next line with the help of imports: import tensorflow as tf from tensorflow.contrib import layers from ldif.util import net_util from ldif.util import math_util and context (classes, functions, sometimes code) from other files: # Path: ldif/util/net_util.py # def twin_inference(inference_fun, observation, element_count, # flat_element_length, model_config): # def get_normalizer_and_mode(model_config): # def conv_layer(inputs, depth, model_config): # def maxpool2x2_layer(inputs): # def down_layer(inputs, depth, model_config): # def up_layer(inputs, spatial_dims, depth, model_config): # def encode(inputs, # model_config, # conv_layer_depths, # fc_layer_depths, # name='Encoder'): # def inputs_to_feature_vector(inputs, feature_length, model_config): # def decode(z, # model_config, # spatial_dims, # fc_layer_depths, # conv_layer_depths, # output_dim, # name='Decoder'): # def residual_layer(inputs, num_outputs, model_config): # # Path: ldif/util/math_util.py # def int_log2(i): # def nonzero_mean(tensor): # def increase_frequency(t, out_dim, flatten=False, interleave=True): . Output only the next line.
return net_util.inputs_to_feature_vector(inputs, 256, model_config)
Given snippet: <|code_start|> def remove_batch_dim(tensor): shape = tensor.get_shape().as_list() rank = len(shape) ensure_shape(tensor, [1] + (rank-1)*[-1]) tensor = tf.reshape(tensor, shape[1:]) return tensor def add_batch_dim(tensor): shape = tensor.get_shape().as_list() tensor = tf.reshape(tensor, [1] + shape) return tensor def occnet_decoder(embedding, samples, apply_sigmoid, model_config): """Computes the OccNet output for the input embedding and its sample batch. Args: embedding: Tensor with shape [batch_size, shape_embedding_length]. samples: Tensor with shape [batch_size, sample_count, 3]. apply_sigmoid: Boolean. Whether to apply a sigmoid layer to the final linear activations. model_config: A ModelConfig object. Returns: Tensor with shape [batch_size, sample_count, 1]. """ if model_config.hparams.hyo == 't': <|code_end|> , continue by predicting the next line. Consider current file imports: import tensorflow as tf from tensorflow.contrib import layers from ldif.util import net_util from ldif.util import math_util and context: # Path: ldif/util/net_util.py # def twin_inference(inference_fun, observation, element_count, # flat_element_length, model_config): # def get_normalizer_and_mode(model_config): # def conv_layer(inputs, depth, model_config): # def maxpool2x2_layer(inputs): # def down_layer(inputs, depth, model_config): # def up_layer(inputs, spatial_dims, depth, model_config): # def encode(inputs, # model_config, # conv_layer_depths, # fc_layer_depths, # name='Encoder'): # def inputs_to_feature_vector(inputs, feature_length, model_config): # def decode(z, # model_config, # spatial_dims, # fc_layer_depths, # conv_layer_depths, # output_dim, # name='Decoder'): # def residual_layer(inputs, num_outputs, model_config): # # Path: ldif/util/math_util.py # def int_log2(i): # def nonzero_mean(tensor): # def increase_frequency(t, out_dim, flatten=False, interleave=True): which might include code, classes, or functions. Output only the next line.
samples = math_util.nerfify(samples, 10, flatten=True, interleave=True)
Given the code snippet: <|code_start|> Returns: sdf: Tensor with shape [batch_size, sample_count, 1]. The ground truth sdf at the sample locations. Differentiable w.r.t. samples. """ xyzw_samples = np.pad( samples, [[0, 0], [0, 1]], mode='constant', constant_values=1) grid_frame_samples = np.matmul(xyzw_samples, world2grid.T)[..., :3] lower_coords = np.floor(grid_frame_samples).astype(np.int32) upper_coords = np.ceil(grid_frame_samples).astype(np.int32) alpha = grid_frame_samples - lower_coords.astype(np.float32) lca = np.split(lower_coords, 3, axis=-1)[::-1] uca = np.split(upper_coords, 3, axis=-1)[::-1] aca = np.split(alpha, 3, axis=-1)[::-1] # ? c00 = grid[lca[0], lca[1], lca[2]] * (1 - aca[0]) + grid[uca[0], lca[1], lca[2]] * aca[0] c01 = grid[lca[0], lca[1], uca[2]] * (1 - aca[0]) + grid[uca[0], lca[1], uca[2]] * aca[0] c10 = grid[lca[0], uca[1], lca[2]] * (1 - aca[0]) + grid[uca[0], uca[1], lca[2]] * aca[0] c11 = grid[lca[0], uca[1], uca[2]] * (1 - aca[0]) + grid[uca[0], uca[1], uca[2]] * aca[0] c0 = c00 * (1 - aca[1]) + c10 * aca[1] c1 = c01 * (1 - aca[1]) + c11 * aca[1] interp = c0 * (1 - aca[2]) + c1 * aca[2] <|code_end|> , generate the next line using the imports in this file: import numpy as np import tensorflow as tf from ldif.util.file_util import log and context (functions, classes, or occasionally code) from other files: # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): . Output only the next line.
log.info('interpolated:')
Based on the snippet: <|code_start|> 'False to complete optimization if it was halted midway.') flags.DEFINE_boolean( 'optimize_only', False, 'Whether to skip dataset creation ' 'and only write tfrecords files.') def process_one(f, mesh_directory, dataset_directory, skip_existing, log_level): """Processes a single mesh, adding it to the dataset.""" relpath = f.replace(mesh_directory, '') assert relpath[0] == '/' relpath = relpath[1:] split, synset = relpath.split('/')[:2] log.verbose(f'The split is {split} and the synset is {synset}') name = os.path.basename(f) name, extension = os.path.splitext(name) valid_extensions = ['.ply'] if extension not in valid_extensions: raise ValueError(f'File with unsupported extension {extension} found: {f}.' f' Only {valid_extensions} are supported.') output_dir = f'{dataset_directory}/{split}/{synset}/{name}/' # This is the last file the processing writes, if it already exists the # example has already been processed. final_file_written = f'{output_dir}/depth_and_normals.npz' make_example.mesh_to_example( os.path.join(path_util.get_path_to_ldif_parent(), 'ldif'), f, f'{dataset_directory}/{split}/{synset}/{name}/', skip_existing, log_level) return output_dir def serialize(example_dir, log_level): <|code_end|> , predict the immediate next line with the help of imports: import glob import random import os import tqdm import tensorflow as tf from absl import app from absl import flags from joblib import Parallel, delayed from ldif.datasets import process_element from ldif.scripts import make_example from ldif.util import file_util from ldif.util import path_util from ldif.util.file_util import log and context (classes, functions, sometimes code) from other files: # Path: ldif/datasets/process_element.py # def load_example_dict(example_directory, log_level=None): # def _float_feature(value): # def _bytes_feature(value): # def make_tf_example(d): # def full_featurespec(): # def parse_tf_example(example_proto): # def _example_dict_tf_func_wrapper(mesh_orig_path): # def parse_example(filename): # # Path: ldif/scripts/make_example.py # def remove_png_dir(d): # def write_depth_and_normals_npz(dirpath, path_out): # def mesh_to_example(codebase_root_dir, mesh_path, dirpath, skip_existing, log_level): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): # # Path: ldif/util/path_util.py # def get_path_to_ldif_root(): # def get_path_to_ldif_parent(): # def package_to_abs(path): # def gaps_path(): # def test_data_path(): # def util_test_data_path(): # def create_test_output_dir(): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): . Output only the next line.
d = process_element.load_example_dict(example_dir, log_level)
Given the following code snippet before the placeholder: <|code_start|> 'on a local NVMe drive or similar.') flags.DEFINE_boolean( 'trample_optimized', True, 'Whether to erase and re-create ' 'optimized files. Set True if changes have been made to the ' 'dataset since the last time meshes2dataset was run; set ' 'False to complete optimization if it was halted midway.') flags.DEFINE_boolean( 'optimize_only', False, 'Whether to skip dataset creation ' 'and only write tfrecords files.') def process_one(f, mesh_directory, dataset_directory, skip_existing, log_level): """Processes a single mesh, adding it to the dataset.""" relpath = f.replace(mesh_directory, '') assert relpath[0] == '/' relpath = relpath[1:] split, synset = relpath.split('/')[:2] log.verbose(f'The split is {split} and the synset is {synset}') name = os.path.basename(f) name, extension = os.path.splitext(name) valid_extensions = ['.ply'] if extension not in valid_extensions: raise ValueError(f'File with unsupported extension {extension} found: {f}.' f' Only {valid_extensions} are supported.') output_dir = f'{dataset_directory}/{split}/{synset}/{name}/' # This is the last file the processing writes, if it already exists the # example has already been processed. final_file_written = f'{output_dir}/depth_and_normals.npz' <|code_end|> , predict the next line using imports from the current file: import glob import random import os import tqdm import tensorflow as tf from absl import app from absl import flags from joblib import Parallel, delayed from ldif.datasets import process_element from ldif.scripts import make_example from ldif.util import file_util from ldif.util import path_util from ldif.util.file_util import log and context including class names, function names, and sometimes code from other files: # Path: ldif/datasets/process_element.py # def load_example_dict(example_directory, log_level=None): # def _float_feature(value): # def _bytes_feature(value): # def make_tf_example(d): # def full_featurespec(): # def parse_tf_example(example_proto): # def _example_dict_tf_func_wrapper(mesh_orig_path): # def parse_example(filename): # # Path: ldif/scripts/make_example.py # def remove_png_dir(d): # def write_depth_and_normals_npz(dirpath, path_out): # def mesh_to_example(codebase_root_dir, mesh_path, dirpath, skip_existing, log_level): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): # # Path: ldif/util/path_util.py # def get_path_to_ldif_root(): # def get_path_to_ldif_parent(): # def package_to_abs(path): # def gaps_path(): # def test_data_path(): # def util_test_data_path(): # def create_test_output_dir(): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): . Output only the next line.
make_example.mesh_to_example(
Based on the snippet: <|code_start|> flags.DEFINE_boolean( 'trample_optimized', True, 'Whether to erase and re-create ' 'optimized files. Set True if changes have been made to the ' 'dataset since the last time meshes2dataset was run; set ' 'False to complete optimization if it was halted midway.') flags.DEFINE_boolean( 'optimize_only', False, 'Whether to skip dataset creation ' 'and only write tfrecords files.') def process_one(f, mesh_directory, dataset_directory, skip_existing, log_level): """Processes a single mesh, adding it to the dataset.""" relpath = f.replace(mesh_directory, '') assert relpath[0] == '/' relpath = relpath[1:] split, synset = relpath.split('/')[:2] log.verbose(f'The split is {split} and the synset is {synset}') name = os.path.basename(f) name, extension = os.path.splitext(name) valid_extensions = ['.ply'] if extension not in valid_extensions: raise ValueError(f'File with unsupported extension {extension} found: {f}.' f' Only {valid_extensions} are supported.') output_dir = f'{dataset_directory}/{split}/{synset}/{name}/' # This is the last file the processing writes, if it already exists the # example has already been processed. final_file_written = f'{output_dir}/depth_and_normals.npz' make_example.mesh_to_example( <|code_end|> , predict the immediate next line with the help of imports: import glob import random import os import tqdm import tensorflow as tf from absl import app from absl import flags from joblib import Parallel, delayed from ldif.datasets import process_element from ldif.scripts import make_example from ldif.util import file_util from ldif.util import path_util from ldif.util.file_util import log and context (classes, functions, sometimes code) from other files: # Path: ldif/datasets/process_element.py # def load_example_dict(example_directory, log_level=None): # def _float_feature(value): # def _bytes_feature(value): # def make_tf_example(d): # def full_featurespec(): # def parse_tf_example(example_proto): # def _example_dict_tf_func_wrapper(mesh_orig_path): # def parse_example(filename): # # Path: ldif/scripts/make_example.py # def remove_png_dir(d): # def write_depth_and_normals_npz(dirpath, path_out): # def mesh_to_example(codebase_root_dir, mesh_path, dirpath, skip_existing, log_level): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): # # Path: ldif/util/path_util.py # def get_path_to_ldif_root(): # def get_path_to_ldif_parent(): # def package_to_abs(path): # def gaps_path(): # def test_data_path(): # def util_test_data_path(): # def create_test_output_dir(): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): . Output only the next line.
os.path.join(path_util.get_path_to_ldif_parent(), 'ldif'), f,
Continue the code snippet: <|code_start|> flags.DEFINE_string('log_level', 'INFO', 'One of VERBOSE, INFO, WARNING, ERROR. Sets logs to print ' 'only at or above the specified level.') flags.DEFINE_boolean( 'optimize', True, 'Whether to create an optimized tfrecords ' 'dataset. This will substantially improve IO throughput, at ' 'the expense of approximately doubling disk usage and adding ' 'a moderate amount of additional dataset creation time. ' 'Recommended unless disk space is very tight or data is stored ' 'on a local NVMe drive or similar.') flags.DEFINE_boolean( 'trample_optimized', True, 'Whether to erase and re-create ' 'optimized files. Set True if changes have been made to the ' 'dataset since the last time meshes2dataset was run; set ' 'False to complete optimization if it was halted midway.') flags.DEFINE_boolean( 'optimize_only', False, 'Whether to skip dataset creation ' 'and only write tfrecords files.') def process_one(f, mesh_directory, dataset_directory, skip_existing, log_level): """Processes a single mesh, adding it to the dataset.""" relpath = f.replace(mesh_directory, '') assert relpath[0] == '/' relpath = relpath[1:] split, synset = relpath.split('/')[:2] <|code_end|> . Use current file imports: import glob import random import os import tqdm import tensorflow as tf from absl import app from absl import flags from joblib import Parallel, delayed from ldif.datasets import process_element from ldif.scripts import make_example from ldif.util import file_util from ldif.util import path_util from ldif.util.file_util import log and context (classes, functions, or code) from other files: # Path: ldif/datasets/process_element.py # def load_example_dict(example_directory, log_level=None): # def _float_feature(value): # def _bytes_feature(value): # def make_tf_example(d): # def full_featurespec(): # def parse_tf_example(example_proto): # def _example_dict_tf_func_wrapper(mesh_orig_path): # def parse_example(filename): # # Path: ldif/scripts/make_example.py # def remove_png_dir(d): # def write_depth_and_normals_npz(dirpath, path_out): # def mesh_to_example(codebase_root_dir, mesh_path, dirpath, skip_existing, log_level): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): # # Path: ldif/util/path_util.py # def get_path_to_ldif_root(): # def get_path_to_ldif_parent(): # def package_to_abs(path): # def gaps_path(): # def test_data_path(): # def util_test_data_path(): # def create_test_output_dir(): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): . Output only the next line.
log.verbose(f'The split is {split} and the synset is {synset}')
Predict the next line for this snippet: <|code_start|>def ensure_are_tensors(named_tensors): for name, tensor in named_tensors.items(): if not (torch.is_tensor(tensor)): raise ValueError(f'Argument {name} is not a tensor, it is a {type(tensor)}') def ensure_type(v, t, name): if not isinstance(v, t): raise ValueError(f'Error: variable {name} has type {type(v)}, not the expected type {t}') def _load_v1_txt(path): """Parses a SIF V1 text file, returning numpy arrays. Args: path: string containing the path to the ASCII file. Returns: A tuple of 4 elements: constants: A numpy array of shape (element_count). The constant associated with each SIF element. centers: A numpy array of shape (element_count, 3). The centers of the SIF elements. radii: A numpy array of shape (element_count, 3). The axis-aligned radii of the gaussian falloffs. rotations: A numpy array of shape (element_count, 3). The euler-angle rotations of the SIF elements. symmetry_count: An integer. The number of elements which are left-right symmetric. features: A numpy array of shape (element_count, implicit_len). The LDIF neural features, if they are present. """ <|code_end|> with the help of current file imports: import numpy as np import torch import sif_evaluation from ldif.util import file_util from ldif.util.file_util import log and context from other files: # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): , which may contain function names, class names, or code. Output only the next line.
lines = file_util.readlines(path)
Using the snippet: <|code_start|> # the batching dimensions broadcast up the coordinate grid, and the # coordinate center broadcasts up along the height and width. # Per-pixel, the algebraic distance is v^T * M * v, where M is the matrix # of the conic section, and v is the homogeneous column vector [x y z 1]^T. half_distance = tf.matmul( quadric, homogeneous_sample_coords, transpose_b=True) rank = batching_rank + 2 half_distance = tf.transpose( half_distance, perm=list(range(rank - 2)) + [rank - 1, rank - 2]) algebraic_distance = tf.reduce_sum( tf.multiply(homogeneous_sample_coords, half_distance), axis=-1) return tf.reshape(algebraic_distance, batching_dimensions + [sample_count, 1]) def decode_covariance_roll_pitch_yaw(radius, invert=False): """Converts 6-D radus vectors to the corresponding covariance matrices. Args: radius: Tensor with shape [..., 6]. First three numbers are covariances of the three Gaussian axes. Second three numbers are the roll-pitch-yaw rotation angles of the Gaussian frame. invert: Whether to return the inverse covariance. Returns: Tensor with shape [..., 3, 3]. The 3x3 (optionally inverted) covariance matrices corresponding to the input radius vectors. """ d = 1.0 / (radius[..., 0:3] + DIV_EPSILON) if invert else radius[..., 0:3] diag = tf.matrix_diag(d) <|code_end|> , determine the next line of code. You have imports: from ldif.util import camera_util from ldif.util import tf_util import tensorflow as tf and context (class names, function names, or code) available: # Path: ldif/util/camera_util.py # def look_at(eye, center, world_up): # def roll_pitch_yaw_to_rotation_matrices(roll_pitch_yaw): # # Path: ldif/util/tf_util.py # def assert_shape(tensor, shape, name): # def log(msg, t): # def tile_new_axis(t, axis, length): # def zero_by_mask(mask, vals, replace_with=0.0): # def remove_element(t, elt, axis): . Output only the next line.
rotation = camera_util.roll_pitch_yaw_to_rotation_matrices(radius[..., 3:6])
Based on the snippet: <|code_start|> NORMALIZATION_EPS = 1e-8 SQRT_NORMALIZATION_EPS = 1e-4 DIV_EPSILON = 1e-8 def sample_quadric_surface(quadric, center, samples): """Samples the algebraic distance to the input quadric at sparse locations. Args: quadric: Tensor with shape [..., 4, 4]. Contains the matrix of the quadric surface. center: Tensor with shape [..., 3]. Contains the [x,y,z] coordinates of the center of the coordinate frame of the quadric surface in NIC space with a top-left origin. samples: Tensor with shape [..., N, 3], where N is the number of samples to evaluate. These are the sample locations in the same space in which the quadric surface center is defined. Supports broadcasting the batching dimensions. Returns: distances: Tensor with shape [..., N, 1]. Contains the algebraic distance to the surface at each sample. """ with tf.name_scope('sample_quadric_surface'): batching_dimensions = quadric.get_shape().as_list()[:-2] batching_rank = len(batching_dimensions) <|code_end|> , predict the immediate next line with the help of imports: from ldif.util import camera_util from ldif.util import tf_util import tensorflow as tf and context (classes, functions, sometimes code) from other files: # Path: ldif/util/camera_util.py # def look_at(eye, center, world_up): # def roll_pitch_yaw_to_rotation_matrices(roll_pitch_yaw): # # Path: ldif/util/tf_util.py # def assert_shape(tensor, shape, name): # def log(msg, t): # def tile_new_axis(t, axis, length): # def zero_by_mask(mask, vals, replace_with=0.0): # def remove_element(t, elt, axis): . Output only the next line.
tf_util.assert_shape(quadric, batching_dimensions + [4, 4],
Based on the snippet: <|code_start|> # ldif is an internal package, should be imported last. # pylint: disable=g-bad-import-order # pylint: enable=g-bad-import-order DISTANCE_EPS = 1e-6 def write_points(points, fname, validity=None): output_dir = path_util.create_test_output_dir() output_fname = os.path.join(output_dir, fname) points = np.reshape(points, [-1, 3]) if validity is not None: validity = np.reshape(validity, [-1, 1]) log.info(f'Points, validity shape: {points.shape}, {validity.shape}') assert validity.shape[0] == points.shape[0] validity = np.tile(validity, [1, 3]) valid_points = points[validity] points = np.reshape(valid_points, [-1, 3]) normals = np.zeros_like(points) log.info(f'Points shape: {points.shape}') log.info(f'Normals shape: {normals.shape}') np.savetxt(output_fname + '.pts', np.concatenate([points, normals], axis=1)) def validate_zero_set_interpolation(zero_set_points, target_volume, model_config): <|code_end|> , predict the immediate next line with the help of imports: import os import numpy as np import tensorflow as tf from tensorflow.python.platform import googletest from ldif.util import file_util from ldif.util import geom_util from ldif.util import path_util from ldif.util.file_util import log and context (classes, functions, sometimes code) from other files: # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): # # Path: ldif/util/geom_util.py # def ray_sphere_intersect(ray_start, ray_direction, sphere_center, sphere_radius, # max_t): # def to_homogeneous(t, is_point): # def transform_points_with_normals(points, tx, normals=None): # def transform_featured_points(points, tx): # def rotation_to_tx(rot): # def extract_points_near_origin(points, count, features=None): # def local_views_of_shape(global_points, # world2local, # local_point_count, # global_normals=None, # global_features=None, # zeros_invalid=False, # zero_threshold=1e-6, # expand_region=True, # threshold=4.0): # def chamfer_distance(pred, target): # def dodeca_parameters(dodeca_idx): # def get_camera_to_world(viewpoint, center, world_up): # def get_dodeca_camera_to_worlds(): # def gaps_depth_render_to_xyz(model_config, depth_image, camera_parameters): # def angle_of_rotation_to_2d_rotation_matrix(angle_of_rotation): # def fractional_vector_projection(e0, e1, p, falloff=2.0): # def rotate_about_point(angle_of_rotation, point, to_rotate): # def interpolate_from_grid(samples, grid): # def reflect(samples, reflect_x=False, reflect_y=False, reflect_z=False): # def z_reflect(samples): # def get_world_to_camera(idx): # def transform_depth_dodeca_to_xyz_dodeca(depth_dodeca): # def transform_depth_dodeca_to_xyz_dodeca_np(depth_dodeca): # def _unbatch(arr): # def to_homogenous_np(arr, is_point=True): # def depth_to_cam_np(im, xfov=0.5): # def apply_tx_np(samples, tx, is_point=True): # def depth_image_to_sdf_constraints(im, cam2world, xfov=0.5): # def depth_dodeca_to_sdf_constraints(depth_ims): # def depth_dodeca_to_samples(dodeca): # def depth_image_to_class_constraints(im, cam2world, xfov=0.5): # def depth_image_to_samples(im, cam2world, xfov=0.5): # pylint:disable=unused-argument # def apply_4x4(tensor, tx, are_points=True, batch_rank=None, sample_rank=None): # def depth_image_to_xyz_image(depth_images, world_to_camera, xfov=0.5): # def interpolate_from_grid_coordinates(samples, grid): # # Path: ldif/util/path_util.py # def get_path_to_ldif_root(): # def get_path_to_ldif_parent(): # def package_to_abs(path): # def gaps_path(): # def test_data_path(): # def util_test_data_path(): # def create_test_output_dir(): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): . Output only the next line.
basic_interp, basic_validity_mask = geom_util.interpolate_from_grid(
Given snippet: <|code_start|># you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Tests for ldif.util.geom_util.""" # ldif is an internal package, should be imported last. # pylint: disable=g-bad-import-order # pylint: enable=g-bad-import-order DISTANCE_EPS = 1e-6 def write_points(points, fname, validity=None): output_dir = path_util.create_test_output_dir() output_fname = os.path.join(output_dir, fname) points = np.reshape(points, [-1, 3]) if validity is not None: validity = np.reshape(validity, [-1, 1]) <|code_end|> , continue by predicting the next line. Consider current file imports: import os import numpy as np import tensorflow as tf from tensorflow.python.platform import googletest from ldif.util import file_util from ldif.util import geom_util from ldif.util import path_util from ldif.util.file_util import log and context: # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): # # Path: ldif/util/geom_util.py # def ray_sphere_intersect(ray_start, ray_direction, sphere_center, sphere_radius, # max_t): # def to_homogeneous(t, is_point): # def transform_points_with_normals(points, tx, normals=None): # def transform_featured_points(points, tx): # def rotation_to_tx(rot): # def extract_points_near_origin(points, count, features=None): # def local_views_of_shape(global_points, # world2local, # local_point_count, # global_normals=None, # global_features=None, # zeros_invalid=False, # zero_threshold=1e-6, # expand_region=True, # threshold=4.0): # def chamfer_distance(pred, target): # def dodeca_parameters(dodeca_idx): # def get_camera_to_world(viewpoint, center, world_up): # def get_dodeca_camera_to_worlds(): # def gaps_depth_render_to_xyz(model_config, depth_image, camera_parameters): # def angle_of_rotation_to_2d_rotation_matrix(angle_of_rotation): # def fractional_vector_projection(e0, e1, p, falloff=2.0): # def rotate_about_point(angle_of_rotation, point, to_rotate): # def interpolate_from_grid(samples, grid): # def reflect(samples, reflect_x=False, reflect_y=False, reflect_z=False): # def z_reflect(samples): # def get_world_to_camera(idx): # def transform_depth_dodeca_to_xyz_dodeca(depth_dodeca): # def transform_depth_dodeca_to_xyz_dodeca_np(depth_dodeca): # def _unbatch(arr): # def to_homogenous_np(arr, is_point=True): # def depth_to_cam_np(im, xfov=0.5): # def apply_tx_np(samples, tx, is_point=True): # def depth_image_to_sdf_constraints(im, cam2world, xfov=0.5): # def depth_dodeca_to_sdf_constraints(depth_ims): # def depth_dodeca_to_samples(dodeca): # def depth_image_to_class_constraints(im, cam2world, xfov=0.5): # def depth_image_to_samples(im, cam2world, xfov=0.5): # pylint:disable=unused-argument # def apply_4x4(tensor, tx, are_points=True, batch_rank=None, sample_rank=None): # def depth_image_to_xyz_image(depth_images, world_to_camera, xfov=0.5): # def interpolate_from_grid_coordinates(samples, grid): # # Path: ldif/util/path_util.py # def get_path_to_ldif_root(): # def get_path_to_ldif_parent(): # def package_to_abs(path): # def gaps_path(): # def test_data_path(): # def util_test_data_path(): # def create_test_output_dir(): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): which might include code, classes, or functions. Output only the next line.
log.info(f'Points, validity shape: {points.shape}, {validity.shape}')
Here is a snippet: <|code_start|># Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """A simple feed forward CNN.""" # LDIF is an internal package, should be imported last. # pylint: disable=g-bad-import-order # pylint: enable=g-bad-import-order def early_fusion_cnn(observation, element_count, element_length, model_config): """A cnn that maps 1+ images with 1+ chanels to a feature vector.""" inputs = observation.tensor if model_config.hparams.cnna == 'cnn': <|code_end|> . Write the next line using the current file imports: import functools import tensorflow as tf import tensorflow.contrib.layers as contrib_layers import tensorflow.contrib.slim as slim import tensorflow_hub as hub from tensorflow.contrib.slim.nets import resnet_utils from tensorflow.contrib.slim.nets import resnet_v2 as contrib_slim_resnet_v2 from ldif.util import net_util from ldif.util.file_util import log and context from other files: # Path: ldif/util/net_util.py # def twin_inference(inference_fun, observation, element_count, # flat_element_length, model_config): # def get_normalizer_and_mode(model_config): # def conv_layer(inputs, depth, model_config): # def maxpool2x2_layer(inputs): # def down_layer(inputs, depth, model_config): # def up_layer(inputs, spatial_dims, depth, model_config): # def encode(inputs, # model_config, # conv_layer_depths, # fc_layer_depths, # name='Encoder'): # def inputs_to_feature_vector(inputs, feature_length, model_config): # def decode(z, # model_config, # spatial_dims, # fc_layer_depths, # conv_layer_depths, # output_dim, # name='Decoder'): # def residual_layer(inputs, num_outputs, model_config): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): , which may include functions, classes, or code. Output only the next line.
embedding = net_util.inputs_to_feature_vector(inputs, 1024, model_config)
Based on the snippet: <|code_start|># # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """A simple feed forward CNN.""" # LDIF is an internal package, should be imported last. # pylint: disable=g-bad-import-order # pylint: enable=g-bad-import-order def early_fusion_cnn(observation, element_count, element_length, model_config): """A cnn that maps 1+ images with 1+ chanels to a feature vector.""" inputs = observation.tensor if model_config.hparams.cnna == 'cnn': embedding = net_util.inputs_to_feature_vector(inputs, 1024, model_config) elif model_config.hparams.cnna in ['r18', 'r50', 'h50', 'k50', 's50']: batch_size, image_count, height, width, channel_count = ( inputs.get_shape().as_list()) <|code_end|> , predict the immediate next line with the help of imports: import functools import tensorflow as tf import tensorflow.contrib.layers as contrib_layers import tensorflow.contrib.slim as slim import tensorflow_hub as hub from tensorflow.contrib.slim.nets import resnet_utils from tensorflow.contrib.slim.nets import resnet_v2 as contrib_slim_resnet_v2 from ldif.util import net_util from ldif.util.file_util import log and context (classes, functions, sometimes code) from other files: # Path: ldif/util/net_util.py # def twin_inference(inference_fun, observation, element_count, # flat_element_length, model_config): # def get_normalizer_and_mode(model_config): # def conv_layer(inputs, depth, model_config): # def maxpool2x2_layer(inputs): # def down_layer(inputs, depth, model_config): # def up_layer(inputs, spatial_dims, depth, model_config): # def encode(inputs, # model_config, # conv_layer_depths, # fc_layer_depths, # name='Encoder'): # def inputs_to_feature_vector(inputs, feature_length, model_config): # def decode(z, # model_config, # spatial_dims, # fc_layer_depths, # conv_layer_depths, # output_dim, # name='Decoder'): # def residual_layer(inputs, num_outputs, model_config): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): . Output only the next line.
log.verbose('Input shape to early-fusion cnn: %s' %
Predict the next line for this snippet: <|code_start|># LDIF is an internal package, should be imported last. # pylint: disable=g-bad-import-order # pylint: enable=g-bad-import-order def _setup_cam(camera): """Generates a -camera input string for GAPS viewers.""" if camera == 'fixed': init_camera = ('1.0451 1.17901 0.630437 ' '-0.614259 -0.695319 -0.373119 ' '-0.547037 0.715996 -0.433705') elif camera == 'default': init_camera = None else: init_camera = camera if init_camera is not None: init_camera = ' -camera %s' % init_camera else: init_camera = '' return init_camera def ptsview(pts, mesh=None, camera='fixed'): """Interactively visualizes a pointcloud alongside an optional mesh.""" with py_util.py2_temporary_directory() as d: ptspath = _make_pts_input_str(d, pts, allow_none=False) init_camera = _setup_cam(camera) mshpath = '' if mesh: mshpath = d + '/m.ply' <|code_end|> with the help of current file imports: import math import os import subprocess as sp import tempfile import numpy as np from ldif.util import file_util from ldif.util import geom_util_np from ldif.util import np_util from ldif.util import py_util from ldif.util import path_util from ldif.util.file_util import log and context from other files: # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): # # Path: ldif/util/geom_util_np.py # def apply_4x4(arr, m, are_points=True, feature_count=0): # def batch_apply_4x4(arrs, ms, are_points=True): # def transform_normals(normals, tx): # def world_xyzn_im_to_pts(world_xyz, world_n): # def transform_r2n2_normal_cam_image_to_world_frame(normal_im, idx, e): # def compute_argmax_image(xyz_image, decoder, embedding, k=1): # def tile_world2local_frames(world2local, lyr): # def extract_local_frame_images(world_xyz_im, world_normal_im, embedding, # decoder): # def select_top_k(argmax_im, xyzn_images): # def make_r2n2_gt_top_k_image(e, idx, encoder, decoder, k=2): # def depth_to_xyz_image(depth_image, intrinsics, extrinsics): # def depth_to_point_cloud(depth_image, intrinsics, extrinsics): # def depth_image_to_cam_image(depth_image, # fx=585.0, # fy=585.0, # cx=255.5, # cy=255.5): # def depth_images_to_cam_images(depth_images, # fx=585.0, # fy=585.0, # cx=255.5, # cy=255.5): # # Path: ldif/util/np_util.py # def batch_np(arr, batch_size): # def make_coordinate_grid(height, width, is_screen_space, is_homogeneous): # def make_coordinate_grid_3d(length, height, width, is_screen_space, # is_homogeneous): # def filter_valid(mask, vals): # def zero_by_mask(mask, vals, replace_with=0.0): # def make_mask(im, thresh=0.0): # def make_pixel_mask(im): # def thresh_and_radius_to_distance(radius, thresh): # def plot_rbfs_at_thresh(centers, radii, thresh=0.5): # def plot_rbfs(centers, radii, scale=10.0): # def cube_and_render(volume, thresh): # def sample_surface(quadrics, centers, radii, length, height, width, # renormalize): # def visualize_prediction(quadrics, # centers, # radii, # renormalize, # thresh=0.0, # input_volumes=None): # # Path: ldif/util/py_util.py # def compose(*fs): # def maybe(x, f): # def py2_temporary_directory(): # def x11_server(): # def merge(x, y): # def merge_into(x, ys): # # Path: ldif/util/path_util.py # def get_path_to_ldif_root(): # def get_path_to_ldif_parent(): # def package_to_abs(path): # def gaps_path(): # def test_data_path(): # def util_test_data_path(): # def create_test_output_dir(): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): , which may contain function names, class names, or code. Output only the next line.
file_util.write_mesh(mshpath, mesh)
Predict the next line for this snippet: <|code_start|> """Reads the images in a directory of depth images made by scn2img. Args: depth_dir: Path to the root directory containing the scn2img output images. im_count: The number of images to read. Will read images with indices range(im_count). Returns: Numpy array with shape [im_count, height, width]. Dimensions determined from file. """ depth_ims = [] for i in range(im_count): path = depth_path_name(depth_dir, i) depth_ims.append(read_depth_im(path)) depth_ims = np.stack(depth_ims) assert len(depth_ims.shape) == 3 return depth_ims def transform_r2n2_depth_image_to_gaps_frame(depth_im, idx, e): """Transforms a depth image predicted in the r2n2 space to the GAPS space.""" # depth_im = self.r2n2_depth_images[idx, ...] # TODO(kgenova) Add support for predicted extrinsics. is_valid = depth_im != 0.0 is_valid = np.reshape(is_valid, [224, 224]) # Depth2cam: cam_im = gaps_depth_image_to_cam_image(depth_im, e.r2n2_xfov[idx]) # Cam2world <|code_end|> with the help of current file imports: import math import os import subprocess as sp import tempfile import numpy as np from ldif.util import file_util from ldif.util import geom_util_np from ldif.util import np_util from ldif.util import py_util from ldif.util import path_util from ldif.util.file_util import log and context from other files: # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): # # Path: ldif/util/geom_util_np.py # def apply_4x4(arr, m, are_points=True, feature_count=0): # def batch_apply_4x4(arrs, ms, are_points=True): # def transform_normals(normals, tx): # def world_xyzn_im_to_pts(world_xyz, world_n): # def transform_r2n2_normal_cam_image_to_world_frame(normal_im, idx, e): # def compute_argmax_image(xyz_image, decoder, embedding, k=1): # def tile_world2local_frames(world2local, lyr): # def extract_local_frame_images(world_xyz_im, world_normal_im, embedding, # decoder): # def select_top_k(argmax_im, xyzn_images): # def make_r2n2_gt_top_k_image(e, idx, encoder, decoder, k=2): # def depth_to_xyz_image(depth_image, intrinsics, extrinsics): # def depth_to_point_cloud(depth_image, intrinsics, extrinsics): # def depth_image_to_cam_image(depth_image, # fx=585.0, # fy=585.0, # cx=255.5, # cy=255.5): # def depth_images_to_cam_images(depth_images, # fx=585.0, # fy=585.0, # cx=255.5, # cy=255.5): # # Path: ldif/util/np_util.py # def batch_np(arr, batch_size): # def make_coordinate_grid(height, width, is_screen_space, is_homogeneous): # def make_coordinate_grid_3d(length, height, width, is_screen_space, # is_homogeneous): # def filter_valid(mask, vals): # def zero_by_mask(mask, vals, replace_with=0.0): # def make_mask(im, thresh=0.0): # def make_pixel_mask(im): # def thresh_and_radius_to_distance(radius, thresh): # def plot_rbfs_at_thresh(centers, radii, thresh=0.5): # def plot_rbfs(centers, radii, scale=10.0): # def cube_and_render(volume, thresh): # def sample_surface(quadrics, centers, radii, length, height, width, # renormalize): # def visualize_prediction(quadrics, # centers, # radii, # renormalize, # thresh=0.0, # input_volumes=None): # # Path: ldif/util/py_util.py # def compose(*fs): # def maybe(x, f): # def py2_temporary_directory(): # def x11_server(): # def merge(x, y): # def merge_into(x, ys): # # Path: ldif/util/path_util.py # def get_path_to_ldif_root(): # def get_path_to_ldif_parent(): # def package_to_abs(path): # def gaps_path(): # def test_data_path(): # def util_test_data_path(): # def create_test_output_dir(): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): , which may contain function names, class names, or code. Output only the next line.
xyz_im = geom_util_np.apply_4x4(
Continue the code snippet: <|code_start|> xfov = 0.5 if isinstance(xfov, float): xfov = np.ones([batch_size], dtype=np.float32) * xfov else: assert len(xfov.shape) in [0, 1] if not xfov.shape: xfov = np.reshape(xfov, [1]) if xfov.shape[0] == 1: xfov = np.tile(xfov, [batch_size]) assert xfov.shape[0] == batch_size out = [] for i in range(batch_size): out.append(gaps_depth_image_to_cam_image(depth_image[i, ...], xfov[i])) return np.stack(out) def gaps_depth_image_to_cam_image(depth_image, xfov=0.5): """Converts a GAPS depth image to a camera-space image. Args: depth_image: Numpy array with shape [height, width] or [height, width, 1]. The depth in units (not in 1000ths of units, which is what GAPS writes). xfov: The xfov of the image in the GAPS format (half-angle in radians). Returns: cam_image: array with shape [height, width, 3]. """ height, width = depth_image.shape[0:2] depth_image = np.reshape(depth_image, [height, width]) <|code_end|> . Use current file imports: import math import os import subprocess as sp import tempfile import numpy as np from ldif.util import file_util from ldif.util import geom_util_np from ldif.util import np_util from ldif.util import py_util from ldif.util import path_util from ldif.util.file_util import log and context (classes, functions, or code) from other files: # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): # # Path: ldif/util/geom_util_np.py # def apply_4x4(arr, m, are_points=True, feature_count=0): # def batch_apply_4x4(arrs, ms, are_points=True): # def transform_normals(normals, tx): # def world_xyzn_im_to_pts(world_xyz, world_n): # def transform_r2n2_normal_cam_image_to_world_frame(normal_im, idx, e): # def compute_argmax_image(xyz_image, decoder, embedding, k=1): # def tile_world2local_frames(world2local, lyr): # def extract_local_frame_images(world_xyz_im, world_normal_im, embedding, # decoder): # def select_top_k(argmax_im, xyzn_images): # def make_r2n2_gt_top_k_image(e, idx, encoder, decoder, k=2): # def depth_to_xyz_image(depth_image, intrinsics, extrinsics): # def depth_to_point_cloud(depth_image, intrinsics, extrinsics): # def depth_image_to_cam_image(depth_image, # fx=585.0, # fy=585.0, # cx=255.5, # cy=255.5): # def depth_images_to_cam_images(depth_images, # fx=585.0, # fy=585.0, # cx=255.5, # cy=255.5): # # Path: ldif/util/np_util.py # def batch_np(arr, batch_size): # def make_coordinate_grid(height, width, is_screen_space, is_homogeneous): # def make_coordinate_grid_3d(length, height, width, is_screen_space, # is_homogeneous): # def filter_valid(mask, vals): # def zero_by_mask(mask, vals, replace_with=0.0): # def make_mask(im, thresh=0.0): # def make_pixel_mask(im): # def thresh_and_radius_to_distance(radius, thresh): # def plot_rbfs_at_thresh(centers, radii, thresh=0.5): # def plot_rbfs(centers, radii, scale=10.0): # def cube_and_render(volume, thresh): # def sample_surface(quadrics, centers, radii, length, height, width, # renormalize): # def visualize_prediction(quadrics, # centers, # radii, # renormalize, # thresh=0.0, # input_volumes=None): # # Path: ldif/util/py_util.py # def compose(*fs): # def maybe(x, f): # def py2_temporary_directory(): # def x11_server(): # def merge(x, y): # def merge_into(x, ys): # # Path: ldif/util/path_util.py # def get_path_to_ldif_root(): # def get_path_to_ldif_parent(): # def package_to_abs(path): # def gaps_path(): # def test_data_path(): # def util_test_data_path(): # def create_test_output_dir(): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): . Output only the next line.
pixel_coords = np_util.make_coordinate_grid(
Predict the next line after this snippet: <|code_start|># Lint as: python3 """Utilties for working with the GAPS geometric processing library.""" # LDIF is an internal package, should be imported last. # pylint: disable=g-bad-import-order # pylint: enable=g-bad-import-order def _setup_cam(camera): """Generates a -camera input string for GAPS viewers.""" if camera == 'fixed': init_camera = ('1.0451 1.17901 0.630437 ' '-0.614259 -0.695319 -0.373119 ' '-0.547037 0.715996 -0.433705') elif camera == 'default': init_camera = None else: init_camera = camera if init_camera is not None: init_camera = ' -camera %s' % init_camera else: init_camera = '' return init_camera def ptsview(pts, mesh=None, camera='fixed'): """Interactively visualizes a pointcloud alongside an optional mesh.""" <|code_end|> using the current file's imports: import math import os import subprocess as sp import tempfile import numpy as np from ldif.util import file_util from ldif.util import geom_util_np from ldif.util import np_util from ldif.util import py_util from ldif.util import path_util from ldif.util.file_util import log and any relevant context from other files: # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): # # Path: ldif/util/geom_util_np.py # def apply_4x4(arr, m, are_points=True, feature_count=0): # def batch_apply_4x4(arrs, ms, are_points=True): # def transform_normals(normals, tx): # def world_xyzn_im_to_pts(world_xyz, world_n): # def transform_r2n2_normal_cam_image_to_world_frame(normal_im, idx, e): # def compute_argmax_image(xyz_image, decoder, embedding, k=1): # def tile_world2local_frames(world2local, lyr): # def extract_local_frame_images(world_xyz_im, world_normal_im, embedding, # decoder): # def select_top_k(argmax_im, xyzn_images): # def make_r2n2_gt_top_k_image(e, idx, encoder, decoder, k=2): # def depth_to_xyz_image(depth_image, intrinsics, extrinsics): # def depth_to_point_cloud(depth_image, intrinsics, extrinsics): # def depth_image_to_cam_image(depth_image, # fx=585.0, # fy=585.0, # cx=255.5, # cy=255.5): # def depth_images_to_cam_images(depth_images, # fx=585.0, # fy=585.0, # cx=255.5, # cy=255.5): # # Path: ldif/util/np_util.py # def batch_np(arr, batch_size): # def make_coordinate_grid(height, width, is_screen_space, is_homogeneous): # def make_coordinate_grid_3d(length, height, width, is_screen_space, # is_homogeneous): # def filter_valid(mask, vals): # def zero_by_mask(mask, vals, replace_with=0.0): # def make_mask(im, thresh=0.0): # def make_pixel_mask(im): # def thresh_and_radius_to_distance(radius, thresh): # def plot_rbfs_at_thresh(centers, radii, thresh=0.5): # def plot_rbfs(centers, radii, scale=10.0): # def cube_and_render(volume, thresh): # def sample_surface(quadrics, centers, radii, length, height, width, # renormalize): # def visualize_prediction(quadrics, # centers, # radii, # renormalize, # thresh=0.0, # input_volumes=None): # # Path: ldif/util/py_util.py # def compose(*fs): # def maybe(x, f): # def py2_temporary_directory(): # def x11_server(): # def merge(x, y): # def merge_into(x, ys): # # Path: ldif/util/path_util.py # def get_path_to_ldif_root(): # def get_path_to_ldif_parent(): # def package_to_abs(path): # def gaps_path(): # def test_data_path(): # def util_test_data_path(): # def create_test_output_dir(): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): . Output only the next line.
with py_util.py2_temporary_directory() as d:
Continue the code snippet: <|code_start|># pylint: enable=g-bad-import-order def _setup_cam(camera): """Generates a -camera input string for GAPS viewers.""" if camera == 'fixed': init_camera = ('1.0451 1.17901 0.630437 ' '-0.614259 -0.695319 -0.373119 ' '-0.547037 0.715996 -0.433705') elif camera == 'default': init_camera = None else: init_camera = camera if init_camera is not None: init_camera = ' -camera %s' % init_camera else: init_camera = '' return init_camera def ptsview(pts, mesh=None, camera='fixed'): """Interactively visualizes a pointcloud alongside an optional mesh.""" with py_util.py2_temporary_directory() as d: ptspath = _make_pts_input_str(d, pts, allow_none=False) init_camera = _setup_cam(camera) mshpath = '' if mesh: mshpath = d + '/m.ply' file_util.write_mesh(mshpath, mesh) mshpath = ' ' + mshpath <|code_end|> . Use current file imports: import math import os import subprocess as sp import tempfile import numpy as np from ldif.util import file_util from ldif.util import geom_util_np from ldif.util import np_util from ldif.util import py_util from ldif.util import path_util from ldif.util.file_util import log and context (classes, functions, or code) from other files: # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): # # Path: ldif/util/geom_util_np.py # def apply_4x4(arr, m, are_points=True, feature_count=0): # def batch_apply_4x4(arrs, ms, are_points=True): # def transform_normals(normals, tx): # def world_xyzn_im_to_pts(world_xyz, world_n): # def transform_r2n2_normal_cam_image_to_world_frame(normal_im, idx, e): # def compute_argmax_image(xyz_image, decoder, embedding, k=1): # def tile_world2local_frames(world2local, lyr): # def extract_local_frame_images(world_xyz_im, world_normal_im, embedding, # decoder): # def select_top_k(argmax_im, xyzn_images): # def make_r2n2_gt_top_k_image(e, idx, encoder, decoder, k=2): # def depth_to_xyz_image(depth_image, intrinsics, extrinsics): # def depth_to_point_cloud(depth_image, intrinsics, extrinsics): # def depth_image_to_cam_image(depth_image, # fx=585.0, # fy=585.0, # cx=255.5, # cy=255.5): # def depth_images_to_cam_images(depth_images, # fx=585.0, # fy=585.0, # cx=255.5, # cy=255.5): # # Path: ldif/util/np_util.py # def batch_np(arr, batch_size): # def make_coordinate_grid(height, width, is_screen_space, is_homogeneous): # def make_coordinate_grid_3d(length, height, width, is_screen_space, # is_homogeneous): # def filter_valid(mask, vals): # def zero_by_mask(mask, vals, replace_with=0.0): # def make_mask(im, thresh=0.0): # def make_pixel_mask(im): # def thresh_and_radius_to_distance(radius, thresh): # def plot_rbfs_at_thresh(centers, radii, thresh=0.5): # def plot_rbfs(centers, radii, scale=10.0): # def cube_and_render(volume, thresh): # def sample_surface(quadrics, centers, radii, length, height, width, # renormalize): # def visualize_prediction(quadrics, # centers, # radii, # renormalize, # thresh=0.0, # input_volumes=None): # # Path: ldif/util/py_util.py # def compose(*fs): # def maybe(x, f): # def py2_temporary_directory(): # def x11_server(): # def merge(x, y): # def merge_into(x, ys): # # Path: ldif/util/path_util.py # def get_path_to_ldif_root(): # def get_path_to_ldif_parent(): # def package_to_abs(path): # def gaps_path(): # def test_data_path(): # def util_test_data_path(): # def create_test_output_dir(): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): . Output only the next line.
cmd = '%s/ptsview %s%s%s' % (path_util.gaps_path(), ptspath, mshpath,
Here is a snippet: <|code_start|> def _setup_cam(camera): """Generates a -camera input string for GAPS viewers.""" if camera == 'fixed': init_camera = ('1.0451 1.17901 0.630437 ' '-0.614259 -0.695319 -0.373119 ' '-0.547037 0.715996 -0.433705') elif camera == 'default': init_camera = None else: init_camera = camera if init_camera is not None: init_camera = ' -camera %s' % init_camera else: init_camera = '' return init_camera def ptsview(pts, mesh=None, camera='fixed'): """Interactively visualizes a pointcloud alongside an optional mesh.""" with py_util.py2_temporary_directory() as d: ptspath = _make_pts_input_str(d, pts, allow_none=False) init_camera = _setup_cam(camera) mshpath = '' if mesh: mshpath = d + '/m.ply' file_util.write_mesh(mshpath, mesh) mshpath = ' ' + mshpath cmd = '%s/ptsview %s%s%s' % (path_util.gaps_path(), ptspath, mshpath, init_camera) <|code_end|> . Write the next line using the current file imports: import math import os import subprocess as sp import tempfile import numpy as np from ldif.util import file_util from ldif.util import geom_util_np from ldif.util import np_util from ldif.util import py_util from ldif.util import path_util from ldif.util.file_util import log and context from other files: # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): # # Path: ldif/util/geom_util_np.py # def apply_4x4(arr, m, are_points=True, feature_count=0): # def batch_apply_4x4(arrs, ms, are_points=True): # def transform_normals(normals, tx): # def world_xyzn_im_to_pts(world_xyz, world_n): # def transform_r2n2_normal_cam_image_to_world_frame(normal_im, idx, e): # def compute_argmax_image(xyz_image, decoder, embedding, k=1): # def tile_world2local_frames(world2local, lyr): # def extract_local_frame_images(world_xyz_im, world_normal_im, embedding, # decoder): # def select_top_k(argmax_im, xyzn_images): # def make_r2n2_gt_top_k_image(e, idx, encoder, decoder, k=2): # def depth_to_xyz_image(depth_image, intrinsics, extrinsics): # def depth_to_point_cloud(depth_image, intrinsics, extrinsics): # def depth_image_to_cam_image(depth_image, # fx=585.0, # fy=585.0, # cx=255.5, # cy=255.5): # def depth_images_to_cam_images(depth_images, # fx=585.0, # fy=585.0, # cx=255.5, # cy=255.5): # # Path: ldif/util/np_util.py # def batch_np(arr, batch_size): # def make_coordinate_grid(height, width, is_screen_space, is_homogeneous): # def make_coordinate_grid_3d(length, height, width, is_screen_space, # is_homogeneous): # def filter_valid(mask, vals): # def zero_by_mask(mask, vals, replace_with=0.0): # def make_mask(im, thresh=0.0): # def make_pixel_mask(im): # def thresh_and_radius_to_distance(radius, thresh): # def plot_rbfs_at_thresh(centers, radii, thresh=0.5): # def plot_rbfs(centers, radii, scale=10.0): # def cube_and_render(volume, thresh): # def sample_surface(quadrics, centers, radii, length, height, width, # renormalize): # def visualize_prediction(quadrics, # centers, # radii, # renormalize, # thresh=0.0, # input_volumes=None): # # Path: ldif/util/py_util.py # def compose(*fs): # def maybe(x, f): # def py2_temporary_directory(): # def x11_server(): # def merge(x, y): # def merge_into(x, ys): # # Path: ldif/util/path_util.py # def get_path_to_ldif_root(): # def get_path_to_ldif_parent(): # def package_to_abs(path): # def gaps_path(): # def test_data_path(): # def util_test_data_path(): # def create_test_output_dir(): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): , which may include functions, classes, or code. Output only the next line.
log.info(cmd)
Here is a snippet: <|code_start|> data_format) for _ in range(1, blocks): inputs = block_fn(inputs, filters, training, None, 1, data_format) return tf.identity(inputs, name) def resize(inputs, height, width, data_format): if data_format == 'channels_first': inputs = tf.transpose(inputs, perm=[0, 2, 3, 1]) else: assert data_format == 'channels_last' output_res = tf.stack([height, width]) output = tf.image.resize_images(inputs, output_res, align_corners=True) if data_format == 'channels_first': output = tf.transpose(output, perm=[0, 3, 1, 2]) return output def assert_shape(tensor, shape, name): """Fails an assert if the tensor fails the shape compatibility check.""" real_shape = tensor.get_shape().as_list() same_rank = len(real_shape) == len(shape) values_different = [ 1 for i in range(min(len(shape), len(real_shape))) if shape[i] != real_shape[i] and shape[i] != -1 ] all_equal = not values_different if not same_rank or not all_equal: <|code_end|> . Write the next line using the current file imports: import tensorflow as tf from ldif.util.file_util import log and context from other files: # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): , which may include functions, classes, or code. Output only the next line.
log.info(
Using the snippet: <|code_start|> max reduce. Only still an option for compatibility with existing trained networks. nerfify: Whether to apply the math_util.nerfify function to the features (all of them, not just the points) after the initial transform step. maxpool_feature_count: Integer. The number of features in the vector before doing a global maxpool. This is the main computational bottleneck, so reducing it is good for training time. Returns: embedding: Tensor with shape [batch_size, embedding_length]. """ batch_size, point_count, feature_count = points.get_shape().as_list() point_positions = points[..., 0:3] point_features = points[..., 3:] feature_count = points.get_shape().as_list()[-1] - 3 with tf.variable_scope('pointnet', reuse=tf.AUTO_REUSE): if apply_learned_ortho_tx: with tf.variable_scope('learned_transformation'): transformation, translation = point_set_to_transformation(points) transformed_points = tf.matmul(point_positions + translation, transformation) if feature_count > 0: transformed_points = tf.concat([transformed_points, point_features], axis=2) net = tf.expand_dims(transformed_points, axis=2) else: net = tf.expand_dims(points, axis=2) if nerfify: <|code_end|> , determine the next line of code. You have imports: import numpy as np import tensorflow as tf import tensorflow.contrib.layers as contrib_layers from ldif.util import math_util and context (class names, function names, or code) available: # Path: ldif/util/math_util.py # def int_log2(i): # def nonzero_mean(tensor): # def increase_frequency(t, out_dim, flatten=False, interleave=True): . Output only the next line.
net = math_util.nerfify(net, 10, flatten=True, interleave=False)
Given snippet: <|code_start|># https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Prints a merged summary table from a variety of XIDs.""" # LDIF is an internal package, should be imported last. # pylint: disable=g-bad-import-order # pylint: enable=g-bad-import-order FLAGS = flags.FLAGS flags.DEFINE_string('input_dir', None, 'The input directory with results.') flags.mark_flag_as_required('input_dir') flags.DEFINE_string('xids', None, 'The XIDs to evaluate on.') flags.mark_flag_as_required('xids') def main(argv): if len(argv) > 1: raise app.UsageError('Too many command-line arguments.') <|code_end|> , continue by predicting the next line. Consider current file imports: from absl import app from absl import flags from ldif.inference import util as inference_util from ldif.util import file_util from ldif.util.file_util import log import pandas as pd import tabulate and context: # Path: ldif/inference/util.py # def parse_xid_str(xidstr): # def ensure_split_valid(split): # def ensure_category_valid(category): # def ensure_synset_valid(synset): # def ensure_hash_valid(h): # def parse_xid_to_ckpt(xid_to_ckpt): # def get_npz_paths(split, category, modifier=''): # def get_mesh_identifiers(split, category): # def get_rgb_paths(split, category, modifier=''): # def rgb_path_to_synset_and_hash(rgb_path): # def rgb_path_to_npz_path(rgb_path, split, dataset='shapenet-occnet'): # def parse_npz_path(path): # def read_png_to_float_npy_with_reraising(path): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): which might include code, classes, or functions. Output only the next line.
xids = inference_util.parse_xid_str(FLAGS.xids)
Given snippet: <|code_start|>flags.DEFINE_string('input_dir', None, 'The input directory with results.') flags.mark_flag_as_required('input_dir') flags.DEFINE_string('xids', None, 'The XIDs to evaluate on.') flags.mark_flag_as_required('xids') def main(argv): if len(argv) > 1: raise app.UsageError('Too many command-line arguments.') xids = inference_util.parse_xid_str(FLAGS.xids) log.info(f'XIDS: {xids}') names = [] ious = [] fscores = [] chamfers = [] xid_to_name = { 1: 'CRS SIF', 2: 'CRS ldif', 3: 'CR SIF', 4: 'CR ldif', 5: 'CRS PT SIF', 6: 'CRS PT ldif', 7: 'CR PT SIF', 8: 'CR PT ldif' } for xid in xids: path = f'{FLAGS.input_dir}/extracted/XID{xid}_metric_summary-v2.csv' <|code_end|> , continue by predicting the next line. Consider current file imports: from absl import app from absl import flags from ldif.inference import util as inference_util from ldif.util import file_util from ldif.util.file_util import log import pandas as pd import tabulate and context: # Path: ldif/inference/util.py # def parse_xid_str(xidstr): # def ensure_split_valid(split): # def ensure_category_valid(category): # def ensure_synset_valid(synset): # def ensure_hash_valid(h): # def parse_xid_to_ckpt(xid_to_ckpt): # def get_npz_paths(split, category, modifier=''): # def get_mesh_identifiers(split, category): # def get_rgb_paths(split, category, modifier=''): # def rgb_path_to_synset_and_hash(rgb_path): # def rgb_path_to_npz_path(rgb_path, split, dataset='shapenet-occnet'): # def parse_npz_path(path): # def read_png_to_float_npy_with_reraising(path): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): which might include code, classes, or functions. Output only the next line.
df = file_util.read_csv(path)
Continue the code snippet: <|code_start|># # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Prints a merged summary table from a variety of XIDs.""" # LDIF is an internal package, should be imported last. # pylint: disable=g-bad-import-order # pylint: enable=g-bad-import-order FLAGS = flags.FLAGS flags.DEFINE_string('input_dir', None, 'The input directory with results.') flags.mark_flag_as_required('input_dir') flags.DEFINE_string('xids', None, 'The XIDs to evaluate on.') flags.mark_flag_as_required('xids') def main(argv): if len(argv) > 1: raise app.UsageError('Too many command-line arguments.') xids = inference_util.parse_xid_str(FLAGS.xids) <|code_end|> . Use current file imports: from absl import app from absl import flags from ldif.inference import util as inference_util from ldif.util import file_util from ldif.util.file_util import log import pandas as pd import tabulate and context (classes, functions, or code) from other files: # Path: ldif/inference/util.py # def parse_xid_str(xidstr): # def ensure_split_valid(split): # def ensure_category_valid(category): # def ensure_synset_valid(synset): # def ensure_hash_valid(h): # def parse_xid_to_ckpt(xid_to_ckpt): # def get_npz_paths(split, category, modifier=''): # def get_mesh_identifiers(split, category): # def get_rgb_paths(split, category, modifier=''): # def rgb_path_to_synset_and_hash(rgb_path): # def rgb_path_to_npz_path(rgb_path, split, dataset='shapenet-occnet'): # def parse_npz_path(path): # def read_png_to_float_npy_with_reraising(path): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): . Output only the next line.
log.info(f'XIDS: {xids}')
Given the code snippet: <|code_start|>def world_xyzn_im_to_pts(world_xyz, world_n): """Makes a 10K long XYZN pointcloud from an XYZ image and a normal image.""" # world im + world normals -> world points+normals is_valid = np.logical_not(np.all(world_xyz == 0.0, axis=-1)) world_xyzn = np.concatenate([world_xyz, world_n], axis=-1) world_xyzn = world_xyzn[is_valid, :] world_xyzn = np.reshape(world_xyzn, [-1, 6]) np.random.shuffle(world_xyzn) point_count = world_xyzn.shape[0] assert point_count > 0 log.info('The number of valid samples is: %i' % point_count) while point_count < 10000: world_xyzn = np.tile(world_xyzn, [2, 1]) point_count = world_xyzn.shape[0] return world_xyzn[:10000, :] def transform_r2n2_normal_cam_image_to_world_frame(normal_im, idx, e): is_valid = np.all(normal_im == 0.0, axis=-1) log.info(is_valid.shape) is_valid = is_valid.reshape([224, 224]) world_im = apply_4x4( normal_im, np.linalg.inv(e.r2n2_cam2world[idx, ...]).T, are_points=False) world_im /= (np.linalg.norm(world_im, axis=-1, keepdims=True) + 1e-8) # world_im = np_util.zero_by_mask(is_valid, world_im).astype(np.float32) return world_im def compute_argmax_image(xyz_image, decoder, embedding, k=1): """Uses the world space XYZ image to compute the maxblob influence image.""" <|code_end|> , generate the next line using the imports in this file: import numpy as np from ldif.util import np_util from ldif.util.file_util import log and context (functions, classes, or occasionally code) from other files: # Path: ldif/util/np_util.py # def batch_np(arr, batch_size): # def make_coordinate_grid(height, width, is_screen_space, is_homogeneous): # def make_coordinate_grid_3d(length, height, width, is_screen_space, # is_homogeneous): # def filter_valid(mask, vals): # def zero_by_mask(mask, vals, replace_with=0.0): # def make_mask(im, thresh=0.0): # def make_pixel_mask(im): # def thresh_and_radius_to_distance(radius, thresh): # def plot_rbfs_at_thresh(centers, radii, thresh=0.5): # def plot_rbfs(centers, radii, scale=10.0): # def cube_and_render(volume, thresh): # def sample_surface(quadrics, centers, radii, length, height, width, # renormalize): # def visualize_prediction(quadrics, # centers, # radii, # renormalize, # thresh=0.0, # input_volumes=None): # # Path: ldif/util/file_util.py # def readlines(p): # def readbin(p): # def writebin(p, s): # def writetxt(p, s): # def write_np(path, arr): # def read_grd(path): # def read_sif_v1(path, verbose=False): # def read_lines(p): # def read_image(p): # def read_npz(p): # def read_np(p): # def read_txt_to_np(p): # def read_py2_pkl(p): # def write_mesh(path, mesh): # def read_mesh(path): # def read_csv(path): # def read_normals(path_to_dir, im_count=20, leading='_depth'): # def write_points(path_ext_optional, points): # def write_grd(path, volume, world2grid=None): # def write_depth_image(path, depth_image): . Output only the next line.
mask = np_util.make_pixel_mask(xyz_image) # TODO(kgenova) Figure this out...