{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \n \"\"\",\n decimal=\"#\",\n )[0]\n\n expected = DataFrame(data={\"Header\": 1100.101}, index=[0])\n\n assert result[\"Header\"].dtype == np.dtype(\"float64\")\n tm.assert_frame_equal(result, expected)\n\n def test_bool_header_arg(self):\n # GH 6114\n for arg in [True, False]:\n with pytest.raises(TypeError):\n self.read_html(self.spam_data, header=arg)\n\n def test_converters(self):\n # GH 13461\n result = self.read_html(\n \"\"\"\n \n \n \n \n \n \n \n \n \n \n \n \n \n
a
0.763
0.244
\"\"\",\n converters={\"a\": str},\n )[0]\n\n expected = DataFrame({\"a\": [\"0.763\", \"0.244\"]})\n\n tm.assert_frame_equal(result, expected)\n\n def test_na_values(self):\n # GH 13461\n result = self.read_html(\n \"\"\"\n \n \n \n \n \n \n \n \n \n \n \n \n \n
a
0.763
0.244
\"\"\",\n na_values=[0.244],\n )[0]\n\n expected = DataFrame({\"a\": [0.763, np.nan]})\n\n tm.assert_frame_equal(result, expected)\n\n def test_keep_default_na(self):\n html_data = \"\"\"\n \n \n \n \n \n \n \n \n \n \n \n \n \n
a
N/A
NA
\"\"\"\n\n expected_df = DataFrame({\"a\": [\"N/A\", \"NA\"]})\n html_df = self.read_html(html_data, keep_default_na=False)[0]\n tm.assert_frame_equal(expected_df, html_df)\n\n expected_df = DataFrame({\"a\": [np.nan, np.nan]})\n html_df = self.read_html(html_data, keep_default_na=True)[0]\n tm.assert_frame_equal(expected_df, html_df)\n\n def test_preserve_empty_rows(self):\n result = self.read_html(\n \"\"\"\n \n \n \n \n \n \n \n \n \n \n \n \n \n
AB
ab
\n \"\"\"\n )[0]\n\n expected = DataFrame(data=[[\"a\", \"b\"], [np.nan, np.nan]], columns=[\"A\", \"B\"])\n\n tm.assert_frame_equal(result, expected)\n\n def test_ignore_empty_rows_when_inferring_header(self):\n result = self.read_html(\n \"\"\"\n \n \n \n \n \n \n \n \n \n
AB
ab
12
\n \"\"\"\n )[0]\n\n columns = MultiIndex(levels=[[\"A\", \"B\"], [\"a\", \"b\"]], codes=[[0, 1], [0, 1]])\n expected = DataFrame(data=[[1, 2]], columns=columns)\n\n tm.assert_frame_equal(result, expected)\n\n def test_multiple_header_rows(self):\n # Issue #13434\n expected_df = DataFrame(\n data=[(\"Hillary\", 68, \"D\"), (\"Bernie\", 74, \"D\"), (\"Donald\", 69, \"R\")]\n )\n expected_df.columns = [\n [\"Unnamed: 0_level_0\", \"Age\", \"Party\"],\n [\"Name\", \"Unnamed: 1_level_1\", \"Unnamed: 2_level_1\"],\n ]\n html = expected_df.to_html(index=False)\n html_df = self.read_html(html)[0]\n tm.assert_frame_equal(expected_df, html_df)\n\n def test_works_on_valid_markup(self, datapath):\n filename = datapath(\"io\", \"data\", \"html\", \"valid_markup.html\")\n dfs = self.read_html(filename, index_col=0)\n assert isinstance(dfs, list)\n assert isinstance(dfs[0], DataFrame)\n\n @pytest.mark.slow\n def test_fallback_success(self, datapath):\n banklist_data = datapath(\"io\", \"data\", \"html\", \"banklist.html\")\n self.read_html(banklist_data, \".*Water.*\", flavor=[\"lxml\", \"html5lib\"])\n\n def test_to_html_timestamp(self):\n rng = date_range(\"2000-01-01\", periods=10)\n df = DataFrame(np.random.randn(10, 4), index=rng)\n\n result = df.to_html()\n assert \"2000-01-01\" in result\n\n @pytest.mark.parametrize(\n \"displayed_only,exp0,exp1\",\n [\n (True, DataFrame([\"foo\"]), None),\n (False, DataFrame([\"foo bar baz qux\"]), DataFrame([\"foo\"])),\n ],\n )\n def test_displayed_only(self, displayed_only, exp0, exp1):\n # GH 20027\n data = StringIO(\n \"\"\"\n \n \n \n \n \n
\n foo\n bar\n baz\n qux\n
\n \n \n \n \n
foo
\n \n \"\"\"\n )\n\n dfs = self.read_html(data, displayed_only=displayed_only)\n tm.assert_frame_equal(dfs[0], exp0)\n\n if exp1 is not None:\n tm.assert_frame_equal(dfs[1], exp1)\n else:\n assert len(dfs) == 1 # Should not parse hidden table\n\n def test_encode(self, html_encoding_file):\n _, encoding = os.path.splitext(os.path.basename(html_encoding_file))[0].split(\n \"_\"\n )\n\n try:\n with open(html_encoding_file, \"rb\") as fobj:\n from_string = self.read_html(\n fobj.read(), encoding=encoding, index_col=0\n ).pop()\n\n with open(html_encoding_file, \"rb\") as fobj:\n from_file_like = self.read_html(\n BytesIO(fobj.read()), encoding=encoding, index_col=0\n ).pop()\n\n from_filename = self.read_html(\n html_encoding_file, encoding=encoding, index_col=0\n ).pop()\n tm.assert_frame_equal(from_string, from_file_like)\n tm.assert_frame_equal(from_string, from_filename)\n except Exception:\n # seems utf-16/32 fail on windows\n if is_platform_windows():\n if \"16\" in encoding or \"32\" in encoding:\n pytest.skip()\n raise\n\n def test_parse_failure_unseekable(self):\n # Issue #17975\n\n if self.read_html.keywords.get(\"flavor\") == \"lxml\":\n pytest.skip(\"Not applicable for lxml\")\n\n class UnseekableStringIO(StringIO):\n def seekable(self):\n return False\n\n bad = UnseekableStringIO(\n \"\"\"\n
spameggs
\"\"\"\n )\n\n assert self.read_html(bad)\n\n with pytest.raises(ValueError, match=\"passed a non-rewindable file object\"):\n self.read_html(bad)\n\n def test_parse_failure_rewinds(self):\n # Issue #17975\n\n class MockFile:\n def __init__(self, data):\n self.data = data\n self.at_end = False\n\n def read(self, size=None):\n data = \"\" if self.at_end else self.data\n self.at_end = True\n return data\n\n def seek(self, offset):\n self.at_end = False\n\n def seekable(self):\n return True\n\n good = MockFile(\"
spam
eggs
\")\n bad = MockFile(\"
spameggs
\")\n\n assert self.read_html(good)\n assert self.read_html(bad)\n\n @pytest.mark.slow\n def test_importcheck_thread_safety(self, datapath):\n # see gh-16928\n\n class ErrorThread(threading.Thread):\n def run(self):\n try:\n super().run()\n except Exception as err:\n self.err = err\n else:\n self.err = None\n\n # force import check by reinitalising global vars in html.py\n reload(pandas.io.html)\n\n filename = datapath(\"io\", \"data\", \"html\", \"valid_markup.html\")\n helper_thread1 = ErrorThread(target=self.read_html, args=(filename,))\n helper_thread2 = ErrorThread(target=self.read_html, args=(filename,))\n\n helper_thread1.start()\n helper_thread2.start()\n\n while helper_thread1.is_alive() or helper_thread2.is_alive():\n pass\n assert None is helper_thread1.err is helper_thread2.err\n"],"string":"[\n \"from functools import partial\\nfrom importlib import reload\\nfrom io import BytesIO, StringIO\\nimport os\\nimport re\\nimport threading\\nfrom urllib.error import URLError\\n\\nimport numpy as np\\nfrom numpy.random import rand\\nimport pytest\\n\\nfrom pandas.compat import is_platform_windows\\nfrom pandas.errors import ParserError\\nimport pandas.util._test_decorators as td\\n\\nfrom pandas import DataFrame, Index, MultiIndex, Series, Timestamp, date_range, read_csv\\nimport pandas.util.testing as tm\\n\\nfrom pandas.io.common import file_path_to_url\\nimport pandas.io.html\\nfrom pandas.io.html import read_html\\n\\nHERE = os.path.dirname(__file__)\\n\\n\\n@pytest.fixture(\\n params=[\\n \\\"chinese_utf-16.html\\\",\\n \\\"chinese_utf-32.html\\\",\\n \\\"chinese_utf-8.html\\\",\\n \\\"letz_latin1.html\\\",\\n ]\\n)\\ndef html_encoding_file(request, datapath):\\n \\\"\\\"\\\"Parametrized fixture for HTML encoding test filenames.\\\"\\\"\\\"\\n return datapath(\\\"io\\\", \\\"data\\\", \\\"html_encoding\\\", request.param)\\n\\n\\ndef assert_framelist_equal(list1, list2, *args, **kwargs):\\n assert len(list1) == len(list2), (\\n \\\"lists are not of equal size \\\"\\n \\\"len(list1) == {0}, \\\"\\n \\\"len(list2) == {1}\\\".format(len(list1), len(list2))\\n )\\n msg = \\\"not all list elements are DataFrames\\\"\\n both_frames = all(\\n map(\\n lambda x, y: isinstance(x, DataFrame) and isinstance(y, DataFrame),\\n list1,\\n list2,\\n )\\n )\\n assert both_frames, msg\\n for frame_i, frame_j in zip(list1, list2):\\n tm.assert_frame_equal(frame_i, frame_j, *args, **kwargs)\\n assert not frame_i.empty, \\\"frames are both empty\\\"\\n\\n\\n@td.skip_if_no(\\\"bs4\\\")\\ndef test_bs4_version_fails(monkeypatch, datapath):\\n import bs4\\n\\n monkeypatch.setattr(bs4, \\\"__version__\\\", \\\"4.2\\\")\\n with pytest.raises(ImportError, match=\\\"Pandas requires version\\\"):\\n read_html(datapath(\\\"io\\\", \\\"data\\\", \\\"html\\\", \\\"spam.html\\\"), flavor=\\\"bs4\\\")\\n\\n\\ndef test_invalid_flavor():\\n url = \\\"google.com\\\"\\n flavor = \\\"invalid flavor\\\"\\n msg = r\\\"\\\\{\\\" + flavor + r\\\"\\\\} is not a valid set of flavors\\\"\\n\\n with pytest.raises(ValueError, match=msg):\\n read_html(url, \\\"google\\\", flavor=flavor)\\n\\n\\n@td.skip_if_no(\\\"bs4\\\")\\n@td.skip_if_no(\\\"lxml\\\")\\ndef test_same_ordering(datapath):\\n filename = datapath(\\\"io\\\", \\\"data\\\", \\\"html\\\", \\\"valid_markup.html\\\")\\n dfs_lxml = read_html(filename, index_col=0, flavor=[\\\"lxml\\\"])\\n dfs_bs4 = read_html(filename, index_col=0, flavor=[\\\"bs4\\\"])\\n assert_framelist_equal(dfs_lxml, dfs_bs4)\\n\\n\\n@pytest.mark.parametrize(\\n \\\"flavor\\\",\\n [\\n pytest.param(\\\"bs4\\\", marks=td.skip_if_no(\\\"lxml\\\")),\\n pytest.param(\\\"lxml\\\", marks=td.skip_if_no(\\\"lxml\\\")),\\n ],\\n scope=\\\"class\\\",\\n)\\nclass TestReadHtml:\\n @pytest.fixture(autouse=True)\\n def set_files(self, datapath):\\n self.spam_data = datapath(\\\"io\\\", \\\"data\\\", \\\"html\\\", \\\"spam.html\\\")\\n self.spam_data_kwargs = {}\\n self.spam_data_kwargs[\\\"encoding\\\"] = \\\"UTF-8\\\"\\n self.banklist_data = datapath(\\\"io\\\", \\\"data\\\", \\\"html\\\", \\\"banklist.html\\\")\\n\\n @pytest.fixture(autouse=True, scope=\\\"function\\\")\\n def set_defaults(self, flavor, request):\\n self.read_html = partial(read_html, flavor=flavor)\\n yield\\n\\n def test_to_html_compat(self):\\n df = (\\n tm.makeCustomDataframe(\\n 4,\\n 3,\\n data_gen_f=lambda *args: rand(),\\n c_idx_names=False,\\n r_idx_names=False,\\n )\\n .applymap(\\\"{0:.3f}\\\".format)\\n .astype(float)\\n )\\n out = df.to_html()\\n res = self.read_html(out, attrs={\\\"class\\\": \\\"dataframe\\\"}, index_col=0)[0]\\n tm.assert_frame_equal(res, df)\\n\\n @tm.network\\n def test_banklist_url(self):\\n url = \\\"http://www.fdic.gov/bank/individual/failed/banklist.html\\\"\\n df1 = self.read_html(\\n url, \\\"First Federal Bank of Florida\\\", attrs={\\\"id\\\": \\\"table\\\"}\\n )\\n df2 = self.read_html(url, \\\"Metcalf Bank\\\", attrs={\\\"id\\\": \\\"table\\\"})\\n\\n assert_framelist_equal(df1, df2)\\n\\n @tm.network\\n def test_spam_url(self):\\n # TODO: alimcmaster1 - revert to master\\n url = (\\n \\\"https://raw.githubusercontent.com/alimcmaster1/\\\"\\n \\\"pandas/mcmali-tests-dir-struct/\\\"\\n \\\"pandas/tests/io/data/html/spam.html\\\"\\n )\\n df1 = self.read_html(url, \\\".*Water.*\\\")\\n df2 = self.read_html(url, \\\"Unit\\\")\\n\\n assert_framelist_equal(df1, df2)\\n\\n @pytest.mark.slow\\n def test_banklist(self):\\n df1 = self.read_html(self.banklist_data, \\\".*Florida.*\\\", attrs={\\\"id\\\": \\\"table\\\"})\\n df2 = self.read_html(self.banklist_data, \\\"Metcalf Bank\\\", attrs={\\\"id\\\": \\\"table\\\"})\\n\\n assert_framelist_equal(df1, df2)\\n\\n def test_spam(self):\\n df1 = self.read_html(self.spam_data, \\\".*Water.*\\\")\\n df2 = self.read_html(self.spam_data, \\\"Unit\\\")\\n assert_framelist_equal(df1, df2)\\n\\n assert df1[0].iloc[0, 0] == \\\"Proximates\\\"\\n assert df1[0].columns[0] == \\\"Nutrient\\\"\\n\\n def test_spam_no_match(self):\\n dfs = self.read_html(self.spam_data)\\n for df in dfs:\\n assert isinstance(df, DataFrame)\\n\\n def test_banklist_no_match(self):\\n dfs = self.read_html(self.banklist_data, attrs={\\\"id\\\": \\\"table\\\"})\\n for df in dfs:\\n assert isinstance(df, DataFrame)\\n\\n def test_spam_header(self):\\n df = self.read_html(self.spam_data, \\\".*Water.*\\\", header=2)[0]\\n assert df.columns[0] == \\\"Proximates\\\"\\n assert not df.empty\\n\\n def test_skiprows_int(self):\\n df1 = self.read_html(self.spam_data, \\\".*Water.*\\\", skiprows=1)\\n df2 = self.read_html(self.spam_data, \\\"Unit\\\", skiprows=1)\\n\\n assert_framelist_equal(df1, df2)\\n\\n def test_skiprows_xrange(self):\\n df1 = self.read_html(self.spam_data, \\\".*Water.*\\\", skiprows=range(2))[0]\\n df2 = self.read_html(self.spam_data, \\\"Unit\\\", skiprows=range(2))[0]\\n tm.assert_frame_equal(df1, df2)\\n\\n def test_skiprows_list(self):\\n df1 = self.read_html(self.spam_data, \\\".*Water.*\\\", skiprows=[1, 2])\\n df2 = self.read_html(self.spam_data, \\\"Unit\\\", skiprows=[2, 1])\\n\\n assert_framelist_equal(df1, df2)\\n\\n def test_skiprows_set(self):\\n df1 = self.read_html(self.spam_data, \\\".*Water.*\\\", skiprows={1, 2})\\n df2 = self.read_html(self.spam_data, \\\"Unit\\\", skiprows={2, 1})\\n\\n assert_framelist_equal(df1, df2)\\n\\n def test_skiprows_slice(self):\\n df1 = self.read_html(self.spam_data, \\\".*Water.*\\\", skiprows=1)\\n df2 = self.read_html(self.spam_data, \\\"Unit\\\", skiprows=1)\\n\\n assert_framelist_equal(df1, df2)\\n\\n def test_skiprows_slice_short(self):\\n df1 = self.read_html(self.spam_data, \\\".*Water.*\\\", skiprows=slice(2))\\n df2 = self.read_html(self.spam_data, \\\"Unit\\\", skiprows=slice(2))\\n\\n assert_framelist_equal(df1, df2)\\n\\n def test_skiprows_slice_long(self):\\n df1 = self.read_html(self.spam_data, \\\".*Water.*\\\", skiprows=slice(2, 5))\\n df2 = self.read_html(self.spam_data, \\\"Unit\\\", skiprows=slice(4, 1, -1))\\n\\n assert_framelist_equal(df1, df2)\\n\\n def test_skiprows_ndarray(self):\\n df1 = self.read_html(self.spam_data, \\\".*Water.*\\\", skiprows=np.arange(2))\\n df2 = self.read_html(self.spam_data, \\\"Unit\\\", skiprows=np.arange(2))\\n\\n assert_framelist_equal(df1, df2)\\n\\n def test_skiprows_invalid(self):\\n with pytest.raises(TypeError, match=(\\\"is not a valid type for skipping rows\\\")):\\n self.read_html(self.spam_data, \\\".*Water.*\\\", skiprows=\\\"asdf\\\")\\n\\n def test_index(self):\\n df1 = self.read_html(self.spam_data, \\\".*Water.*\\\", index_col=0)\\n df2 = self.read_html(self.spam_data, \\\"Unit\\\", index_col=0)\\n assert_framelist_equal(df1, df2)\\n\\n def test_header_and_index_no_types(self):\\n df1 = self.read_html(self.spam_data, \\\".*Water.*\\\", header=1, index_col=0)\\n df2 = self.read_html(self.spam_data, \\\"Unit\\\", header=1, index_col=0)\\n assert_framelist_equal(df1, df2)\\n\\n def test_header_and_index_with_types(self):\\n df1 = self.read_html(self.spam_data, \\\".*Water.*\\\", header=1, index_col=0)\\n df2 = self.read_html(self.spam_data, \\\"Unit\\\", header=1, index_col=0)\\n assert_framelist_equal(df1, df2)\\n\\n def test_infer_types(self):\\n\\n # 10892 infer_types removed\\n df1 = self.read_html(self.spam_data, \\\".*Water.*\\\", index_col=0)\\n df2 = self.read_html(self.spam_data, \\\"Unit\\\", index_col=0)\\n assert_framelist_equal(df1, df2)\\n\\n def test_string_io(self):\\n with open(self.spam_data, **self.spam_data_kwargs) as f:\\n data1 = StringIO(f.read())\\n\\n with open(self.spam_data, **self.spam_data_kwargs) as f:\\n data2 = StringIO(f.read())\\n\\n df1 = self.read_html(data1, \\\".*Water.*\\\")\\n df2 = self.read_html(data2, \\\"Unit\\\")\\n assert_framelist_equal(df1, df2)\\n\\n def test_string(self):\\n with open(self.spam_data, **self.spam_data_kwargs) as f:\\n data = f.read()\\n\\n df1 = self.read_html(data, \\\".*Water.*\\\")\\n df2 = self.read_html(data, \\\"Unit\\\")\\n\\n assert_framelist_equal(df1, df2)\\n\\n def test_file_like(self):\\n with open(self.spam_data, **self.spam_data_kwargs) as f:\\n df1 = self.read_html(f, \\\".*Water.*\\\")\\n\\n with open(self.spam_data, **self.spam_data_kwargs) as f:\\n df2 = self.read_html(f, \\\"Unit\\\")\\n\\n assert_framelist_equal(df1, df2)\\n\\n @tm.network\\n def test_bad_url_protocol(self):\\n with pytest.raises(URLError):\\n self.read_html(\\\"git://github.com\\\", match=\\\".*Water.*\\\")\\n\\n @tm.network\\n @pytest.mark.slow\\n def test_invalid_url(self):\\n try:\\n with pytest.raises(URLError):\\n self.read_html(\\\"http://www.a23950sdfa908sd.com\\\", match=\\\".*Water.*\\\")\\n except ValueError as e:\\n assert \\\"No tables found\\\" in str(e)\\n\\n @pytest.mark.slow\\n def test_file_url(self):\\n url = self.banklist_data\\n dfs = self.read_html(\\n file_path_to_url(os.path.abspath(url)), \\\"First\\\", attrs={\\\"id\\\": \\\"table\\\"}\\n )\\n assert isinstance(dfs, list)\\n for df in dfs:\\n assert isinstance(df, DataFrame)\\n\\n @pytest.mark.slow\\n def test_invalid_table_attrs(self):\\n url = self.banklist_data\\n with pytest.raises(ValueError, match=\\\"No tables found\\\"):\\n self.read_html(\\n url, \\\"First Federal Bank of Florida\\\", attrs={\\\"id\\\": \\\"tasdfable\\\"}\\n )\\n\\n def _bank_data(self, *args, **kwargs):\\n return self.read_html(\\n self.banklist_data, \\\"Metcalf\\\", attrs={\\\"id\\\": \\\"table\\\"}, *args, **kwargs\\n )\\n\\n @pytest.mark.slow\\n def test_multiindex_header(self):\\n df = self._bank_data(header=[0, 1])[0]\\n assert isinstance(df.columns, MultiIndex)\\n\\n @pytest.mark.slow\\n def test_multiindex_index(self):\\n df = self._bank_data(index_col=[0, 1])[0]\\n assert isinstance(df.index, MultiIndex)\\n\\n @pytest.mark.slow\\n def test_multiindex_header_index(self):\\n df = self._bank_data(header=[0, 1], index_col=[0, 1])[0]\\n assert isinstance(df.columns, MultiIndex)\\n assert isinstance(df.index, MultiIndex)\\n\\n @pytest.mark.slow\\n def test_multiindex_header_skiprows_tuples(self):\\n df = self._bank_data(header=[0, 1], skiprows=1)[0]\\n assert isinstance(df.columns, MultiIndex)\\n\\n @pytest.mark.slow\\n def test_multiindex_header_skiprows(self):\\n df = self._bank_data(header=[0, 1], skiprows=1)[0]\\n assert isinstance(df.columns, MultiIndex)\\n\\n @pytest.mark.slow\\n def test_multiindex_header_index_skiprows(self):\\n df = self._bank_data(header=[0, 1], index_col=[0, 1], skiprows=1)[0]\\n assert isinstance(df.index, MultiIndex)\\n assert isinstance(df.columns, MultiIndex)\\n\\n @pytest.mark.slow\\n def test_regex_idempotency(self):\\n url = self.banklist_data\\n dfs = self.read_html(\\n file_path_to_url(os.path.abspath(url)),\\n match=re.compile(re.compile(\\\"Florida\\\")),\\n attrs={\\\"id\\\": \\\"table\\\"},\\n )\\n assert isinstance(dfs, list)\\n for df in dfs:\\n assert isinstance(df, DataFrame)\\n\\n def test_negative_skiprows(self):\\n msg = r\\\"\\\\(you passed a negative value\\\\)\\\"\\n with pytest.raises(ValueError, match=msg):\\n self.read_html(self.spam_data, \\\"Water\\\", skiprows=-1)\\n\\n @tm.network\\n def test_multiple_matches(self):\\n url = \\\"https://docs.python.org/2/\\\"\\n dfs = self.read_html(url, match=\\\"Python\\\")\\n assert len(dfs) > 1\\n\\n @tm.network\\n def test_python_docs_table(self):\\n url = \\\"https://docs.python.org/2/\\\"\\n dfs = self.read_html(url, match=\\\"Python\\\")\\n zz = [df.iloc[0, 0][0:4] for df in dfs]\\n assert sorted(zz) == sorted([\\\"Repo\\\", \\\"What\\\"])\\n\\n @pytest.mark.slow\\n def test_thousands_macau_stats(self, datapath):\\n all_non_nan_table_index = -2\\n macau_data = datapath(\\\"io\\\", \\\"data\\\", \\\"html\\\", \\\"macau.html\\\")\\n dfs = self.read_html(macau_data, index_col=0, attrs={\\\"class\\\": \\\"style1\\\"})\\n df = dfs[all_non_nan_table_index]\\n\\n assert not any(s.isna().any() for _, s in df.items())\\n\\n @pytest.mark.slow\\n def test_thousands_macau_index_col(self, datapath):\\n all_non_nan_table_index = -2\\n macau_data = datapath(\\\"io\\\", \\\"data\\\", \\\"html\\\", \\\"macau.html\\\")\\n dfs = self.read_html(macau_data, index_col=0, header=0)\\n df = dfs[all_non_nan_table_index]\\n\\n assert not any(s.isna().any() for _, s in df.items())\\n\\n def test_empty_tables(self):\\n \\\"\\\"\\\"\\n Make sure that read_html ignores empty tables.\\n \\\"\\\"\\\"\\n result = self.read_html(\\n \\\"\\\"\\\"\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n
AB
12
\\n \\n \\n \\n
\\n \\\"\\\"\\\"\\n )\\n\\n assert len(result) == 1\\n\\n def test_multiple_tbody(self):\\n # GH-20690\\n # Read all tbody tags within a single table.\\n result = self.read_html(\\n \\\"\\\"\\\"\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n
AB
12
34
\\\"\\\"\\\"\\n )[0]\\n\\n expected = DataFrame(data=[[1, 2], [3, 4]], columns=[\\\"A\\\", \\\"B\\\"])\\n\\n tm.assert_frame_equal(result, expected)\\n\\n def test_header_and_one_column(self):\\n \\\"\\\"\\\"\\n Don't fail with bs4 when there is a header and only one column\\n as described in issue #9178\\n \\\"\\\"\\\"\\n result = self.read_html(\\n \\\"\\\"\\\"\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n
Header
first
\\\"\\\"\\\"\\n )[0]\\n\\n expected = DataFrame(data={\\\"Header\\\": \\\"first\\\"}, index=[0])\\n\\n tm.assert_frame_equal(result, expected)\\n\\n def test_thead_without_tr(self):\\n \\\"\\\"\\\"\\n Ensure parser adds within on malformed HTML.\\n \\\"\\\"\\\"\\n result = self.read_html(\\n \\\"\\\"\\\"\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n
CountryMunicipalityYear
UkraineOdessa1944
\\\"\\\"\\\"\\n )[0]\\n\\n expected = DataFrame(\\n data=[[\\\"Ukraine\\\", \\\"Odessa\\\", 1944]],\\n columns=[\\\"Country\\\", \\\"Municipality\\\", \\\"Year\\\"],\\n )\\n\\n tm.assert_frame_equal(result, expected)\\n\\n def test_tfoot_read(self):\\n \\\"\\\"\\\"\\n Make sure that read_html reads tfoot, containing td or th.\\n Ignores empty tfoot\\n \\\"\\\"\\\"\\n data_template = \\\"\\\"\\\"\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n {footer}\\n \\n
AB
bodyAbodyB
\\\"\\\"\\\"\\n\\n expected1 = DataFrame(data=[[\\\"bodyA\\\", \\\"bodyB\\\"]], columns=[\\\"A\\\", \\\"B\\\"])\\n\\n expected2 = DataFrame(\\n data=[[\\\"bodyA\\\", \\\"bodyB\\\"], [\\\"footA\\\", \\\"footB\\\"]], columns=[\\\"A\\\", \\\"B\\\"]\\n )\\n\\n data1 = data_template.format(footer=\\\"\\\")\\n data2 = data_template.format(footer=\\\"footAfootB\\\")\\n\\n result1 = self.read_html(data1)[0]\\n result2 = self.read_html(data2)[0]\\n\\n tm.assert_frame_equal(result1, expected1)\\n tm.assert_frame_equal(result2, expected2)\\n\\n def test_parse_header_of_non_string_column(self):\\n # GH5048: if header is specified explicitly, an int column should be\\n # parsed as int while its header is parsed as str\\n result = self.read_html(\\n \\\"\\\"\\\"\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n
SI
text1944
\\n \\\"\\\"\\\",\\n header=0,\\n )[0]\\n\\n expected = DataFrame([[\\\"text\\\", 1944]], columns=(\\\"S\\\", \\\"I\\\"))\\n\\n tm.assert_frame_equal(result, expected)\\n\\n def test_nyse_wsj_commas_table(self, datapath):\\n data = datapath(\\\"io\\\", \\\"data\\\", \\\"html\\\", \\\"nyse_wsj.html\\\")\\n df = self.read_html(data, index_col=0, header=0, attrs={\\\"class\\\": \\\"mdcTable\\\"})[0]\\n\\n expected = Index(\\n [\\n \\\"Issue(Roll over for charts and headlines)\\\",\\n \\\"Volume\\\",\\n \\\"Price\\\",\\n \\\"Chg\\\",\\n \\\"% Chg\\\",\\n ]\\n )\\n nrows = 100\\n assert df.shape[0] == nrows\\n tm.assert_index_equal(df.columns, expected)\\n\\n @pytest.mark.slow\\n def test_banklist_header(self, datapath):\\n from pandas.io.html import _remove_whitespace\\n\\n def try_remove_ws(x):\\n try:\\n return _remove_whitespace(x)\\n except AttributeError:\\n return x\\n\\n df = self.read_html(self.banklist_data, \\\"Metcalf\\\", attrs={\\\"id\\\": \\\"table\\\"})[0]\\n ground_truth = read_csv(\\n datapath(\\\"io\\\", \\\"data\\\", \\\"csv\\\", \\\"banklist.csv\\\"),\\n converters={\\\"Updated Date\\\": Timestamp, \\\"Closing Date\\\": Timestamp},\\n )\\n assert df.shape == ground_truth.shape\\n old = [\\n \\\"First Vietnamese American BankIn Vietnamese\\\",\\n \\\"Westernbank Puerto RicoEn Espanol\\\",\\n \\\"R-G Premier Bank of Puerto RicoEn Espanol\\\",\\n \\\"EurobankEn Espanol\\\",\\n \\\"Sanderson State BankEn Espanol\\\",\\n \\\"Washington Mutual Bank(Including its subsidiary Washington \\\"\\n \\\"Mutual Bank FSB)\\\",\\n \\\"Silver State BankEn Espanol\\\",\\n \\\"AmTrade International BankEn Espanol\\\",\\n \\\"Hamilton Bank, NAEn Espanol\\\",\\n \\\"The Citizens Savings BankPioneer Community Bank, Inc.\\\",\\n ]\\n new = [\\n \\\"First Vietnamese American Bank\\\",\\n \\\"Westernbank Puerto Rico\\\",\\n \\\"R-G Premier Bank of Puerto Rico\\\",\\n \\\"Eurobank\\\",\\n \\\"Sanderson State Bank\\\",\\n \\\"Washington Mutual Bank\\\",\\n \\\"Silver State Bank\\\",\\n \\\"AmTrade International Bank\\\",\\n \\\"Hamilton Bank, NA\\\",\\n \\\"The Citizens Savings Bank\\\",\\n ]\\n dfnew = df.applymap(try_remove_ws).replace(old, new)\\n gtnew = ground_truth.applymap(try_remove_ws)\\n converted = dfnew._convert(datetime=True, numeric=True)\\n date_cols = [\\\"Closing Date\\\", \\\"Updated Date\\\"]\\n converted[date_cols] = converted[date_cols]._convert(datetime=True, coerce=True)\\n tm.assert_frame_equal(converted, gtnew)\\n\\n @pytest.mark.slow\\n def test_gold_canyon(self):\\n gc = \\\"Gold Canyon\\\"\\n with open(self.banklist_data, \\\"r\\\") as f:\\n raw_text = f.read()\\n\\n assert gc in raw_text\\n df = self.read_html(self.banklist_data, \\\"Gold Canyon\\\", attrs={\\\"id\\\": \\\"table\\\"})[0]\\n assert gc in df.to_string()\\n\\n def test_different_number_of_cols(self):\\n expected = self.read_html(\\n \\\"\\\"\\\"\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n
C_l0_g0C_l0_g1C_l0_g2C_l0_g3C_l0_g4
R_l0_g0 0.763 0.233 nan nan nan
R_l0_g1 0.244 0.285 0.392 0.137 0.222
\\\"\\\"\\\",\\n index_col=0,\\n )[0]\\n\\n result = self.read_html(\\n \\\"\\\"\\\"\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n
C_l0_g0C_l0_g1C_l0_g2C_l0_g3C_l0_g4
R_l0_g0 0.763 0.233
R_l0_g1 0.244 0.285 0.392 0.137 0.222
\\\"\\\"\\\",\\n index_col=0,\\n )[0]\\n\\n tm.assert_frame_equal(result, expected)\\n\\n def test_colspan_rowspan_1(self):\\n # GH17054\\n result = self.read_html(\\n \\\"\\\"\\\"\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n
ABC
abc
\\n \\\"\\\"\\\"\\n )[0]\\n\\n expected = DataFrame([[\\\"a\\\", \\\"b\\\", \\\"c\\\"]], columns=[\\\"A\\\", \\\"B\\\", \\\"C\\\"])\\n\\n tm.assert_frame_equal(result, expected)\\n\\n def test_colspan_rowspan_copy_values(self):\\n # GH17054\\n\\n # In ASCII, with lowercase letters being copies:\\n #\\n # X x Y Z W\\n # A B b z C\\n\\n result = self.read_html(\\n \\\"\\\"\\\"\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n
XYZW
ABC
\\n \\\"\\\"\\\",\\n header=0,\\n )[0]\\n\\n expected = DataFrame(\\n data=[[\\\"A\\\", \\\"B\\\", \\\"B\\\", \\\"Z\\\", \\\"C\\\"]], columns=[\\\"X\\\", \\\"X.1\\\", \\\"Y\\\", \\\"Z\\\", \\\"W\\\"]\\n )\\n\\n tm.assert_frame_equal(result, expected)\\n\\n def test_colspan_rowspan_both_not_1(self):\\n # GH17054\\n\\n # In ASCII, with lowercase letters being copies:\\n #\\n # A B b b C\\n # a b b b D\\n\\n result = self.read_html(\\n \\\"\\\"\\\"\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n
ABC
D
\\n \\\"\\\"\\\",\\n header=0,\\n )[0]\\n\\n expected = DataFrame(\\n data=[[\\\"A\\\", \\\"B\\\", \\\"B\\\", \\\"B\\\", \\\"D\\\"]], columns=[\\\"A\\\", \\\"B\\\", \\\"B.1\\\", \\\"B.2\\\", \\\"C\\\"]\\n )\\n\\n tm.assert_frame_equal(result, expected)\\n\\n def test_rowspan_at_end_of_row(self):\\n # GH17054\\n\\n # In ASCII, with lowercase letters being copies:\\n #\\n # A B\\n # C b\\n\\n result = self.read_html(\\n \\\"\\\"\\\"\\n \\n \\n \\n \\n \\n \\n \\n \\n
AB
C
\\n \\\"\\\"\\\",\\n header=0,\\n )[0]\\n\\n expected = DataFrame(data=[[\\\"C\\\", \\\"B\\\"]], columns=[\\\"A\\\", \\\"B\\\"])\\n\\n tm.assert_frame_equal(result, expected)\\n\\n def test_rowspan_only_rows(self):\\n # GH17054\\n\\n result = self.read_html(\\n \\\"\\\"\\\"\\n \\n \\n \\n \\n \\n
AB
\\n \\\"\\\"\\\",\\n header=0,\\n )[0]\\n\\n expected = DataFrame(data=[[\\\"A\\\", \\\"B\\\"], [\\\"A\\\", \\\"B\\\"]], columns=[\\\"A\\\", \\\"B\\\"])\\n\\n tm.assert_frame_equal(result, expected)\\n\\n def test_header_inferred_from_rows_with_only_th(self):\\n # GH17054\\n result = self.read_html(\\n \\\"\\\"\\\"\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n
AB
ab
12
\\n \\\"\\\"\\\"\\n )[0]\\n\\n columns = MultiIndex(levels=[[\\\"A\\\", \\\"B\\\"], [\\\"a\\\", \\\"b\\\"]], codes=[[0, 1], [0, 1]])\\n expected = DataFrame(data=[[1, 2]], columns=columns)\\n\\n tm.assert_frame_equal(result, expected)\\n\\n def test_parse_dates_list(self):\\n df = DataFrame({\\\"date\\\": date_range(\\\"1/1/2001\\\", periods=10)})\\n expected = df.to_html()\\n res = self.read_html(expected, parse_dates=[1], index_col=0)\\n tm.assert_frame_equal(df, res[0])\\n res = self.read_html(expected, parse_dates=[\\\"date\\\"], index_col=0)\\n tm.assert_frame_equal(df, res[0])\\n\\n def test_parse_dates_combine(self):\\n raw_dates = Series(date_range(\\\"1/1/2001\\\", periods=10))\\n df = DataFrame(\\n {\\n \\\"date\\\": raw_dates.map(lambda x: str(x.date())),\\n \\\"time\\\": raw_dates.map(lambda x: str(x.time())),\\n }\\n )\\n res = self.read_html(\\n df.to_html(), parse_dates={\\\"datetime\\\": [1, 2]}, index_col=1\\n )\\n newdf = DataFrame({\\\"datetime\\\": raw_dates})\\n tm.assert_frame_equal(newdf, res[0])\\n\\n def test_computer_sales_page(self, datapath):\\n data = datapath(\\\"io\\\", \\\"data\\\", \\\"html\\\", \\\"computer_sales_page.html\\\")\\n msg = (\\n r\\\"Passed header=\\\\[0,1\\\\] are too many \\\"\\n r\\\"rows for this multi_index of columns\\\"\\n )\\n with pytest.raises(ParserError, match=msg):\\n self.read_html(data, header=[0, 1])\\n\\n data = datapath(\\\"io\\\", \\\"data\\\", \\\"html\\\", \\\"computer_sales_page.html\\\")\\n assert self.read_html(data, header=[1, 2])\\n\\n def test_wikipedia_states_table(self, datapath):\\n data = datapath(\\\"io\\\", \\\"data\\\", \\\"html\\\", \\\"wikipedia_states.html\\\")\\n assert os.path.isfile(data), \\\"{data!r} is not a file\\\".format(data=data)\\n assert os.path.getsize(data), \\\"{data!r} is an empty file\\\".format(data=data)\\n result = self.read_html(data, \\\"Arizona\\\", header=1)[0]\\n assert result[\\\"sq mi\\\"].dtype == np.dtype(\\\"float64\\\")\\n\\n def test_parser_error_on_empty_header_row(self):\\n msg = (\\n r\\\"Passed header=\\\\[0,1\\\\] are too many \\\"\\n r\\\"rows for this multi_index of columns\\\"\\n )\\n with pytest.raises(ParserError, match=msg):\\n self.read_html(\\n \\\"\\\"\\\"\\n \\n \\n \\n \\n \\n \\n \\n \\n
AB
ab
\\n \\\"\\\"\\\",\\n header=[0, 1],\\n )\\n\\n def test_decimal_rows(self):\\n # GH 12907\\n result = self.read_html(\\n \\\"\\\"\\\"\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n
Header
1100#101
\\n \\n \\\"\\\"\\\",\\n decimal=\\\"#\\\",\\n )[0]\\n\\n expected = DataFrame(data={\\\"Header\\\": 1100.101}, index=[0])\\n\\n assert result[\\\"Header\\\"].dtype == np.dtype(\\\"float64\\\")\\n tm.assert_frame_equal(result, expected)\\n\\n def test_bool_header_arg(self):\\n # GH 6114\\n for arg in [True, False]:\\n with pytest.raises(TypeError):\\n self.read_html(self.spam_data, header=arg)\\n\\n def test_converters(self):\\n # GH 13461\\n result = self.read_html(\\n \\\"\\\"\\\"\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n
a
0.763
0.244
\\\"\\\"\\\",\\n converters={\\\"a\\\": str},\\n )[0]\\n\\n expected = DataFrame({\\\"a\\\": [\\\"0.763\\\", \\\"0.244\\\"]})\\n\\n tm.assert_frame_equal(result, expected)\\n\\n def test_na_values(self):\\n # GH 13461\\n result = self.read_html(\\n \\\"\\\"\\\"\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n
a
0.763
0.244
\\\"\\\"\\\",\\n na_values=[0.244],\\n )[0]\\n\\n expected = DataFrame({\\\"a\\\": [0.763, np.nan]})\\n\\n tm.assert_frame_equal(result, expected)\\n\\n def test_keep_default_na(self):\\n html_data = \\\"\\\"\\\"\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n
a
N/A
NA
\\\"\\\"\\\"\\n\\n expected_df = DataFrame({\\\"a\\\": [\\\"N/A\\\", \\\"NA\\\"]})\\n html_df = self.read_html(html_data, keep_default_na=False)[0]\\n tm.assert_frame_equal(expected_df, html_df)\\n\\n expected_df = DataFrame({\\\"a\\\": [np.nan, np.nan]})\\n html_df = self.read_html(html_data, keep_default_na=True)[0]\\n tm.assert_frame_equal(expected_df, html_df)\\n\\n def test_preserve_empty_rows(self):\\n result = self.read_html(\\n \\\"\\\"\\\"\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n
AB
ab
\\n \\\"\\\"\\\"\\n )[0]\\n\\n expected = DataFrame(data=[[\\\"a\\\", \\\"b\\\"], [np.nan, np.nan]], columns=[\\\"A\\\", \\\"B\\\"])\\n\\n tm.assert_frame_equal(result, expected)\\n\\n def test_ignore_empty_rows_when_inferring_header(self):\\n result = self.read_html(\\n \\\"\\\"\\\"\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n
AB
ab
12
\\n \\\"\\\"\\\"\\n )[0]\\n\\n columns = MultiIndex(levels=[[\\\"A\\\", \\\"B\\\"], [\\\"a\\\", \\\"b\\\"]], codes=[[0, 1], [0, 1]])\\n expected = DataFrame(data=[[1, 2]], columns=columns)\\n\\n tm.assert_frame_equal(result, expected)\\n\\n def test_multiple_header_rows(self):\\n # Issue #13434\\n expected_df = DataFrame(\\n data=[(\\\"Hillary\\\", 68, \\\"D\\\"), (\\\"Bernie\\\", 74, \\\"D\\\"), (\\\"Donald\\\", 69, \\\"R\\\")]\\n )\\n expected_df.columns = [\\n [\\\"Unnamed: 0_level_0\\\", \\\"Age\\\", \\\"Party\\\"],\\n [\\\"Name\\\", \\\"Unnamed: 1_level_1\\\", \\\"Unnamed: 2_level_1\\\"],\\n ]\\n html = expected_df.to_html(index=False)\\n html_df = self.read_html(html)[0]\\n tm.assert_frame_equal(expected_df, html_df)\\n\\n def test_works_on_valid_markup(self, datapath):\\n filename = datapath(\\\"io\\\", \\\"data\\\", \\\"html\\\", \\\"valid_markup.html\\\")\\n dfs = self.read_html(filename, index_col=0)\\n assert isinstance(dfs, list)\\n assert isinstance(dfs[0], DataFrame)\\n\\n @pytest.mark.slow\\n def test_fallback_success(self, datapath):\\n banklist_data = datapath(\\\"io\\\", \\\"data\\\", \\\"html\\\", \\\"banklist.html\\\")\\n self.read_html(banklist_data, \\\".*Water.*\\\", flavor=[\\\"lxml\\\", \\\"html5lib\\\"])\\n\\n def test_to_html_timestamp(self):\\n rng = date_range(\\\"2000-01-01\\\", periods=10)\\n df = DataFrame(np.random.randn(10, 4), index=rng)\\n\\n result = df.to_html()\\n assert \\\"2000-01-01\\\" in result\\n\\n @pytest.mark.parametrize(\\n \\\"displayed_only,exp0,exp1\\\",\\n [\\n (True, DataFrame([\\\"foo\\\"]), None),\\n (False, DataFrame([\\\"foo bar baz qux\\\"]), DataFrame([\\\"foo\\\"])),\\n ],\\n )\\n def test_displayed_only(self, displayed_only, exp0, exp1):\\n # GH 20027\\n data = StringIO(\\n \\\"\\\"\\\"\\n \\n \\n \\n \\n \\n
\\n foo\\n bar\\n baz\\n qux\\n
\\n \\n \\n \\n \\n
foo
\\n \\n \\\"\\\"\\\"\\n )\\n\\n dfs = self.read_html(data, displayed_only=displayed_only)\\n tm.assert_frame_equal(dfs[0], exp0)\\n\\n if exp1 is not None:\\n tm.assert_frame_equal(dfs[1], exp1)\\n else:\\n assert len(dfs) == 1 # Should not parse hidden table\\n\\n def test_encode(self, html_encoding_file):\\n _, encoding = os.path.splitext(os.path.basename(html_encoding_file))[0].split(\\n \\\"_\\\"\\n )\\n\\n try:\\n with open(html_encoding_file, \\\"rb\\\") as fobj:\\n from_string = self.read_html(\\n fobj.read(), encoding=encoding, index_col=0\\n ).pop()\\n\\n with open(html_encoding_file, \\\"rb\\\") as fobj:\\n from_file_like = self.read_html(\\n BytesIO(fobj.read()), encoding=encoding, index_col=0\\n ).pop()\\n\\n from_filename = self.read_html(\\n html_encoding_file, encoding=encoding, index_col=0\\n ).pop()\\n tm.assert_frame_equal(from_string, from_file_like)\\n tm.assert_frame_equal(from_string, from_filename)\\n except Exception:\\n # seems utf-16/32 fail on windows\\n if is_platform_windows():\\n if \\\"16\\\" in encoding or \\\"32\\\" in encoding:\\n pytest.skip()\\n raise\\n\\n def test_parse_failure_unseekable(self):\\n # Issue #17975\\n\\n if self.read_html.keywords.get(\\\"flavor\\\") == \\\"lxml\\\":\\n pytest.skip(\\\"Not applicable for lxml\\\")\\n\\n class UnseekableStringIO(StringIO):\\n def seekable(self):\\n return False\\n\\n bad = UnseekableStringIO(\\n \\\"\\\"\\\"\\n
spameggs
\\\"\\\"\\\"\\n )\\n\\n assert self.read_html(bad)\\n\\n with pytest.raises(ValueError, match=\\\"passed a non-rewindable file object\\\"):\\n self.read_html(bad)\\n\\n def test_parse_failure_rewinds(self):\\n # Issue #17975\\n\\n class MockFile:\\n def __init__(self, data):\\n self.data = data\\n self.at_end = False\\n\\n def read(self, size=None):\\n data = \\\"\\\" if self.at_end else self.data\\n self.at_end = True\\n return data\\n\\n def seek(self, offset):\\n self.at_end = False\\n\\n def seekable(self):\\n return True\\n\\n good = MockFile(\\\"
spam
eggs
\\\")\\n bad = MockFile(\\\"
spameggs
\\\")\\n\\n assert self.read_html(good)\\n assert self.read_html(bad)\\n\\n @pytest.mark.slow\\n def test_importcheck_thread_safety(self, datapath):\\n # see gh-16928\\n\\n class ErrorThread(threading.Thread):\\n def run(self):\\n try:\\n super().run()\\n except Exception as err:\\n self.err = err\\n else:\\n self.err = None\\n\\n # force import check by reinitalising global vars in html.py\\n reload(pandas.io.html)\\n\\n filename = datapath(\\\"io\\\", \\\"data\\\", \\\"html\\\", \\\"valid_markup.html\\\")\\n helper_thread1 = ErrorThread(target=self.read_html, args=(filename,))\\n helper_thread2 = ErrorThread(target=self.read_html, args=(filename,))\\n\\n helper_thread1.start()\\n helper_thread2.start()\\n\\n while helper_thread1.is_alive() or helper_thread2.is_alive():\\n pass\\n assert None is helper_thread1.err is helper_thread2.err\\n\"\n]"},"apis":{"kind":"list like","value":[["pandas.io.html._remove_whitespace","pandas.MultiIndex","pandas.compat.is_platform_windows","numpy.arange","pandas.Index","pandas.DataFrame","pandas.io.html.read_html","pandas.util.testing.assert_frame_equal","numpy.dtype","pandas.util.testing.assert_index_equal","numpy.random.randn","numpy.random.rand","pandas.date_range","pandas.util._test_decorators.skip_if_no"]],"string":"[\n [\n \"pandas.io.html._remove_whitespace\",\n \"pandas.MultiIndex\",\n \"pandas.compat.is_platform_windows\",\n \"numpy.arange\",\n \"pandas.Index\",\n \"pandas.DataFrame\",\n \"pandas.io.html.read_html\",\n \"pandas.util.testing.assert_frame_equal\",\n \"numpy.dtype\",\n \"pandas.util.testing.assert_index_equal\",\n \"numpy.random.randn\",\n \"numpy.random.rand\",\n \"pandas.date_range\",\n \"pandas.util._test_decorators.skip_if_no\"\n ]\n]"},"possible_versions":{"kind":"list like","value":[{"matplotlib":[],"numpy":[],"pandas":[],"scipy":[],"tensorflow":[]}],"string":"[\n {\n \"matplotlib\": [],\n \"numpy\": [],\n \"pandas\": [],\n \"scipy\": [],\n \"tensorflow\": []\n }\n]"}}},{"rowIdx":72518,"cells":{"repo_name":{"kind":"string","value":"LFElodie/CarND-Behavioral-Cloning-P3"},"hexsha":{"kind":"list like","value":["9d2db7d3ce7be8700fa359a3b11a21c44d199d50"],"string":"[\n \"9d2db7d3ce7be8700fa359a3b11a21c44d199d50\"\n]"},"file_path":{"kind":"list like","value":["utils.py"],"string":"[\n \"utils.py\"\n]"},"code":{"kind":"list like","value":["import os\nimport numpy as np\nimport pandas as pd\nfrom sklearn.utils import shuffle\nimport matplotlib.image as mpimg\n\nCORRECTION = 0.2\n\n\ndef load_data(data_folders):\n '''\n Read driving_log.csv from data folders \n '''\n samples = []\n for data_folder in data_folders:\n # Raw sample contains [center,left,right,steering,throttle,brake,speed] each row\n raw_sample = pd.read_csv(os.path.join(data_folder, 'driving_log.csv'))\n # Extract filenames and convert to right image path\n image_path = raw_sample.iloc[:, :3].applymap(\n lambda x: os.path.join(data_folder, 'IMG', os.path.basename(x)))\n sample = pd.concat([image_path, raw_sample.iloc[:, 3]], axis=1)\n samples.append(sample)\n samples = pd.concat(samples, axis=0)\n return samples\n\n\ndef training_generator(samples, batch_size=32):\n '''\n Generator for training data\n '''\n num_samples = samples.shape[0]\n while 1:\n samples = shuffle(samples)\n for offset in range(0, num_samples, batch_size):\n batch_samples = samples.iloc[offset:offset + batch_size]\n\n images = []\n angles = []\n for index, batch_sample in batch_samples.iterrows():\n # read in images from center, left and right cameras\n for i in range(3):\n image = mpimg.imread(batch_sample[i])\n images.append(image)\n # steering center\n angles.append(batch_sample[3])\n # steering left\n angles.append(batch_sample[3] + CORRECTION)\n # steering right\n angles.append(batch_sample[3] - CORRECTION)\n\n # data augment flip the image\n augmented_images, augmented_angles = [], []\n for image, angle in zip(images, angles):\n augmented_images.append(image)\n augmented_angles.append(angle)\n # flip the image only if angle is larger than 0.1\n if angle > 0.1:\n augmented_images.append(np.fliplr(image))\n augmented_angles.append(-angle)\n X_train = np.array(augmented_images)\n y_train = np.array(augmented_angles)\n\n yield shuffle(X_train, y_train)\n\n\ndef validation_generator(samples, batch_size=32):\n '''\n Generator for validation data\n '''\n num_samples = samples.shape[0]\n while 1:\n for offset in range(0, num_samples, batch_size):\n batch_samples = samples.iloc[offset:offset + batch_size]\n images = []\n angles = []\n for index, batch_sample in batch_samples.iterrows():\n image = mpimg.imread(batch_sample[0])\n images.append(image)\n angles.append(batch_sample[3])\n X_train = np.array(images)\n y_train = np.array(images)\n\n yield X_train, y_train\n"],"string":"[\n \"import os\\nimport numpy as np\\nimport pandas as pd\\nfrom sklearn.utils import shuffle\\nimport matplotlib.image as mpimg\\n\\nCORRECTION = 0.2\\n\\n\\ndef load_data(data_folders):\\n '''\\n Read driving_log.csv from data folders \\n '''\\n samples = []\\n for data_folder in data_folders:\\n # Raw sample contains [center,left,right,steering,throttle,brake,speed] each row\\n raw_sample = pd.read_csv(os.path.join(data_folder, 'driving_log.csv'))\\n # Extract filenames and convert to right image path\\n image_path = raw_sample.iloc[:, :3].applymap(\\n lambda x: os.path.join(data_folder, 'IMG', os.path.basename(x)))\\n sample = pd.concat([image_path, raw_sample.iloc[:, 3]], axis=1)\\n samples.append(sample)\\n samples = pd.concat(samples, axis=0)\\n return samples\\n\\n\\ndef training_generator(samples, batch_size=32):\\n '''\\n Generator for training data\\n '''\\n num_samples = samples.shape[0]\\n while 1:\\n samples = shuffle(samples)\\n for offset in range(0, num_samples, batch_size):\\n batch_samples = samples.iloc[offset:offset + batch_size]\\n\\n images = []\\n angles = []\\n for index, batch_sample in batch_samples.iterrows():\\n # read in images from center, left and right cameras\\n for i in range(3):\\n image = mpimg.imread(batch_sample[i])\\n images.append(image)\\n # steering center\\n angles.append(batch_sample[3])\\n # steering left\\n angles.append(batch_sample[3] + CORRECTION)\\n # steering right\\n angles.append(batch_sample[3] - CORRECTION)\\n\\n # data augment flip the image\\n augmented_images, augmented_angles = [], []\\n for image, angle in zip(images, angles):\\n augmented_images.append(image)\\n augmented_angles.append(angle)\\n # flip the image only if angle is larger than 0.1\\n if angle > 0.1:\\n augmented_images.append(np.fliplr(image))\\n augmented_angles.append(-angle)\\n X_train = np.array(augmented_images)\\n y_train = np.array(augmented_angles)\\n\\n yield shuffle(X_train, y_train)\\n\\n\\ndef validation_generator(samples, batch_size=32):\\n '''\\n Generator for validation data\\n '''\\n num_samples = samples.shape[0]\\n while 1:\\n for offset in range(0, num_samples, batch_size):\\n batch_samples = samples.iloc[offset:offset + batch_size]\\n images = []\\n angles = []\\n for index, batch_sample in batch_samples.iterrows():\\n image = mpimg.imread(batch_sample[0])\\n images.append(image)\\n angles.append(batch_sample[3])\\n X_train = np.array(images)\\n y_train = np.array(images)\\n\\n yield X_train, y_train\\n\"\n]"},"apis":{"kind":"list like","value":[["pandas.concat","numpy.fliplr","sklearn.utils.shuffle","matplotlib.image.imread","numpy.array"]],"string":"[\n [\n \"pandas.concat\",\n \"numpy.fliplr\",\n \"sklearn.utils.shuffle\",\n \"matplotlib.image.imread\",\n \"numpy.array\"\n ]\n]"},"possible_versions":{"kind":"list like","value":[{"matplotlib":[],"numpy":[],"pandas":["0.23","0.21","2.0","1.4","0.19","1.1","1.5","1.2","0.24","0.20","1.0","0.25","1.3"],"scipy":[],"tensorflow":[]}],"string":"[\n {\n \"matplotlib\": [],\n \"numpy\": [],\n \"pandas\": [\n \"0.23\",\n \"0.21\",\n \"2.0\",\n \"1.4\",\n \"0.19\",\n \"1.1\",\n \"1.5\",\n \"1.2\",\n \"0.24\",\n \"0.20\",\n \"1.0\",\n \"0.25\",\n \"1.3\"\n ],\n \"scipy\": [],\n \"tensorflow\": []\n }\n]"}}},{"rowIdx":72519,"cells":{"repo_name":{"kind":"string","value":"rac2030/OnFire"},"hexsha":{"kind":"list like","value":["7fba89681ed20a37581d09d81d2099c9bc242423"],"string":"[\n \"7fba89681ed20a37581d09d81d2099c9bc242423\"\n]"},"file_path":{"kind":"list like","value":["bin/Vectorizer.py"],"string":"[\n \"bin/Vectorizer.py\"\n]"},"code":{"kind":"list like","value":["import numpy as np\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\nlist = [\"India\"]\n\nwith open('new300.csv') as f:\n for line in f:\n list.append(line)\n\nvect = TfidfVectorizer(min_df=1)\n\ntfidf = vect.fit_transform(list)\nprint(tfidf.toarray())\nprint ((tfidf * tfidf.T).A)\n\nprint(vect.get_feature_names())\nfout = open(\"vector-matrix.txt\",encoding='utf8',mode='w') \nfout.write(tfidf.toarray())\nfout.close()\n\n"],"string":"[\n \"import numpy as np\\n\\nfrom sklearn.feature_extraction.text import TfidfVectorizer\\n\\nlist = [\\\"India\\\"]\\n\\nwith open('new300.csv') as f:\\n for line in f:\\n list.append(line)\\n\\nvect = TfidfVectorizer(min_df=1)\\n\\ntfidf = vect.fit_transform(list)\\nprint(tfidf.toarray())\\nprint ((tfidf * tfidf.T).A)\\n\\nprint(vect.get_feature_names())\\nfout = open(\\\"vector-matrix.txt\\\",encoding='utf8',mode='w') \\nfout.write(tfidf.toarray())\\nfout.close()\\n\\n\"\n]"},"apis":{"kind":"list like","value":[["sklearn.feature_extraction.text.TfidfVectorizer"]],"string":"[\n [\n \"sklearn.feature_extraction.text.TfidfVectorizer\"\n ]\n]"},"possible_versions":{"kind":"list like","value":[{"matplotlib":[],"numpy":[],"pandas":[],"scipy":[],"tensorflow":[]}],"string":"[\n {\n \"matplotlib\": [],\n \"numpy\": [],\n \"pandas\": [],\n \"scipy\": [],\n \"tensorflow\": []\n }\n]"}}},{"rowIdx":72520,"cells":{"repo_name":{"kind":"string","value":"JulienPeloton/gcr-catalogs"},"hexsha":{"kind":"list like","value":["1e8ba090ed42b32c2b7cfed2b3227611e093d76e"],"string":"[\n \"1e8ba090ed42b32c2b7cfed2b3227611e093d76e\"\n]"},"file_path":{"kind":"list like","value":["GCRCatalogs/alphaq.py"],"string":"[\n \"GCRCatalogs/alphaq.py\"\n]"},"code":{"kind":"list like","value":["\"\"\"\nAlpha Q galaxy catalog class.\n\"\"\"\nfrom __future__ import division\nimport os\nimport re\nimport warnings\nfrom distutils.version import StrictVersion # pylint: disable=no-name-in-module,import-error\nimport numpy as np\nimport h5py\nfrom astropy.cosmology import FlatLambdaCDM\nfrom GCR import BaseGenericCatalog\nfrom .utils import md5\n\n__all__ = ['AlphaQGalaxyCatalog']\n__version__ = '5.0.0'\n\n\ndef _calc_weighted_size(size1, size2, lum1, lum2):\n return ((size1*lum1) + (size2*lum2)) / (lum1+lum2)\n\n\ndef _calc_weighted_size_minor(size1, size2, lum1, lum2, ell):\n size = _calc_weighted_size(size1, size2, lum1, lum2)\n return size * (1.0 - ell) / (1.0 + ell)\n\n\ndef _calc_conv(mag, shear1, shear2):\n slct = mag < 0.2\n mag_corr = np.copy(mag)\n mag_corr[slct] = 1.0 # manually changing the values for when magnification is near zero.\n conv = 1.0 - np.sqrt(1.0/mag_corr + shear1**2 + shear2**2)\n return conv\n\n\ndef _calc_Rv(lum_v, lum_v_dust, lum_b, lum_b_dust):\n v = lum_v_dust/lum_v\n b = lum_b_dust/lum_b\n bv = b/v\n Rv = np.log10(v) / np.log10(bv)\n Rv[(v == 1) & (b == 1)] = 1.0\n Rv[v == b] = np.nan\n return Rv\n\n\ndef _calc_Av(lum_v, lum_v_dust):\n Av = -2.5*(np.log10(lum_v_dust/lum_v))\n Av[lum_v_dust == 0] = np.nan\n return Av\n\n\ndef _gen_position_angle(size_reference):\n # pylint: disable=protected-access\n size = size_reference.size\n if not hasattr(_gen_position_angle, \"_pos_angle\") or _gen_position_angle._pos_angle.size != size:\n _gen_position_angle._pos_angle = np.random.RandomState(123497).uniform(0, 180, size)\n return _gen_position_angle._pos_angle\n\n\ndef _calc_ellipticity_1(ellipticity):\n # position angle using ellipticity as reference for the size or\n # the array. The angle is converted from degrees to radians\n pos_angle = _gen_position_angle(ellipticity)*np.pi/180.0\n # use the correct conversion for ellipticity 1 from ellipticity\n # and position angle\n return ellipticity*np.cos(2.0*pos_angle)\n\n\ndef _calc_ellipticity_2(ellipticity):\n # position angle using ellipticity as reference for the size or\n # the array. The angle is converted from degrees to radians\n pos_angle = _gen_position_angle(ellipticity)*np.pi/180.0\n # use the correct conversion for ellipticity 2 from ellipticity\n # and position angle\n return ellipticity*np.sin(2.0*pos_angle)\n\n\ndef _gen_galaxy_id(size_reference):\n # pylint: disable=protected-access\n size = size_reference.size\n if not hasattr(_gen_galaxy_id, \"_galaxy_id\") or _gen_galaxy_id._galaxy_id.size != size:\n _gen_galaxy_id._galaxy_id = np.arange(size, dtype='i8')\n return _gen_galaxy_id._galaxy_id\n\ndef _calc_lensed_magnitude(magnitude, magnification):\n magnification[magnification==0]=1.0\n return magnitude -2.5*np.log10(magnification)\n\nclass AlphaQGalaxyCatalog(BaseGenericCatalog):\n \"\"\"\n Alpha Q galaxy catalog class. Uses generic quantity and filter mechanisms\n defined by BaseGenericCatalog class.\n \"\"\"\n\n def _subclass_init(self, filename, **kwargs): #pylint: disable=W0221\n\n if not os.path.isfile(filename):\n raise ValueError('Catalog file {} does not exist'.format(filename))\n self._file = filename\n\n if kwargs.get('md5'):\n if md5(self._file) != kwargs['md5']:\n raise ValueError('md5 sum does not match!')\n else:\n warnings.warn('No md5 sum specified in the config file')\n\n self.lightcone = kwargs.get('lightcone')\n\n with h5py.File(self._file, 'r') as fh:\n # pylint: disable=no-member\n # get version\n catalog_version = list()\n for version_label in ('Major', 'Minor', 'MinorMinor'):\n try:\n catalog_version.append(fh['/metaData/version' + version_label].value)\n except KeyError:\n break\n catalog_version = StrictVersion('.'.join(map(str, catalog_version or (2, 0))))\n\n # get cosmology\n self.cosmology = FlatLambdaCDM(\n H0=fh['metaData/simulationParameters/H_0'].value,\n Om0=fh['metaData/simulationParameters/Omega_matter'].value,\n Ob0=fh['metaData/simulationParameters/Omega_b'].value,\n )\n self.cosmology.sigma8 = fh['metaData/simulationParameters/sigma_8'].value\n self.cosmology.n_s = fh['metaData/simulationParameters/N_s'].value\n self.halo_mass_def = fh['metaData/simulationParameters/haloMassDefinition'].value\n\n # get sky area\n if catalog_version >= StrictVersion(\"2.1.1\"):\n self.sky_area = float(fh['metaData/skyArea'].value)\n else:\n self.sky_area = 25.0 #If the sky area isn't specified use the default value of the sky area.\n\n # get native quantities\n self._native_quantities = set()\n def _collect_native_quantities(name, obj):\n if isinstance(obj, h5py.Dataset):\n self._native_quantities.add(name)\n fh['galaxyProperties'].visititems(_collect_native_quantities)\n\n # check versions\n self.version = kwargs.get('version', '0.0.0')\n config_version = StrictVersion(self.version)\n if config_version != catalog_version:\n raise ValueError('Catalog file version {} does not match config version {}'.format(catalog_version, config_version))\n if StrictVersion(__version__) < config_version:\n raise ValueError('Reader version {} is less than config version {}'.format(__version__, catalog_version))\n\n # specify quantity modifiers\n self._quantity_modifiers = {\n 'galaxy_id' : 'galaxyID',\n 'ra': 'ra',\n 'dec': 'dec',\n 'ra_true': 'ra_true',\n 'dec_true': 'dec_true',\n 'redshift': 'redshift',\n 'redshift_true': 'redshiftHubble',\n 'shear_1': 'shear1',\n 'shear_2': (np.negative, 'shear2'),\n 'shear_2_treecorr': (np.negative, 'shear2'),\n 'shear_2_phosim': 'shear2',\n 'convergence': (\n _calc_conv,\n 'magnification',\n 'shear1',\n 'shear2',\n ),\n 'magnification': (lambda mag: np.where(mag < 0.2, 1.0, mag), 'magnification'),\n 'halo_id': 'hostHaloTag',\n 'halo_mass': 'hostHaloMass',\n 'is_central': (lambda x: x.astype(np.bool), 'isCentral'),\n 'stellar_mass': 'totalMassStellar',\n 'stellar_mass_disk': 'diskMassStellar',\n 'stellar_mass_bulge': 'spheroidMassStellar',\n 'size_disk_true': 'morphology/diskMajorAxisArcsec',\n 'size_bulge_true': 'morphology/spheroidMajorAxisArcsec',\n 'size_minor_disk_true': 'morphology/diskMinorAxisArcsec',\n 'size_minor_bulge_true': 'morphology/spheroidMinorAxisArcsec',\n 'position_angle_true': (_gen_position_angle, 'morphology/positionAngle'),\n 'sersic_disk': 'morphology/diskSersicIndex',\n 'sersic_bulge': 'morphology/spheroidSersicIndex',\n 'ellipticity_true': 'morphology/totalEllipticity',\n 'ellipticity_1_true': (_calc_ellipticity_1, 'morphology/totalEllipticity'),\n 'ellipticity_2_true': (_calc_ellipticity_2, 'morphology/totalEllipticity'),\n 'ellipticity_disk_true': 'morphology/diskEllipticity',\n 'ellipticity_1_disk_true': (_calc_ellipticity_1, 'morphology/diskEllipticity'),\n 'ellipticity_2_disk_true': (_calc_ellipticity_2, 'morphology/diskEllipticity'),\n 'ellipticity_bulge_true': 'morphology/spheroidEllipticity',\n 'ellipticity_1_bulge_true': (_calc_ellipticity_1, 'morphology/spheroidEllipticity'),\n 'ellipticity_2_bulge_true': (_calc_ellipticity_2, 'morphology/spheroidEllipticity'),\n 'size_true': (\n _calc_weighted_size,\n 'morphology/diskMajorAxisArcsec',\n 'morphology/spheroidMajorAxisArcsec',\n 'LSST_filters/diskLuminositiesStellar:LSST_r:rest',\n 'LSST_filters/spheroidLuminositiesStellar:LSST_r:rest',\n ),\n 'size_minor_true': (\n _calc_weighted_size_minor,\n 'morphology/diskMajorAxisArcsec',\n 'morphology/spheroidMajorAxisArcsec',\n 'LSST_filters/diskLuminositiesStellar:LSST_r:rest',\n 'LSST_filters/spheroidLuminositiesStellar:LSST_r:rest',\n 'morphology/totalEllipticity',\n ),\n 'bulge_to_total_ratio_i': (\n lambda x, y: x/(x+y),\n 'SDSS_filters/spheroidLuminositiesStellar:SDSS_i:observed',\n 'SDSS_filters/diskLuminositiesStellar:SDSS_i:observed',\n ),\n 'A_v': (\n _calc_Av,\n 'otherLuminosities/totalLuminositiesStellar:V:rest',\n 'otherLuminosities/totalLuminositiesStellar:V:rest:dustAtlas',\n ),\n 'A_v_disk': (\n _calc_Av,\n 'otherLuminosities/diskLuminositiesStellar:V:rest',\n 'otherLuminosities/diskLuminositiesStellar:V:rest:dustAtlas',\n ),\n 'A_v_bulge': (\n _calc_Av,\n 'otherLuminosities/spheroidLuminositiesStellar:V:rest',\n 'otherLuminosities/spheroidLuminositiesStellar:V:rest:dustAtlas',\n ),\n 'R_v': (\n _calc_Rv,\n 'otherLuminosities/totalLuminositiesStellar:V:rest',\n 'otherLuminosities/totalLuminositiesStellar:V:rest:dustAtlas',\n 'otherLuminosities/totalLuminositiesStellar:B:rest',\n 'otherLuminosities/totalLuminositiesStellar:B:rest:dustAtlas',\n ),\n 'R_v_disk': (\n _calc_Rv,\n 'otherLuminosities/diskLuminositiesStellar:V:rest',\n 'otherLuminosities/diskLuminositiesStellar:V:rest:dustAtlas',\n 'otherLuminosities/diskLuminositiesStellar:B:rest',\n 'otherLuminosities/diskLuminositiesStellar:B:rest:dustAtlas',\n ),\n 'R_v_bulge': (\n _calc_Rv,\n 'otherLuminosities/spheroidLuminositiesStellar:V:rest',\n 'otherLuminosities/spheroidLuminositiesStellar:V:rest:dustAtlas',\n 'otherLuminosities/spheroidLuminositiesStellar:B:rest',\n 'otherLuminosities/spheroidLuminositiesStellar:B:rest:dustAtlas',\n ),\n 'position_x': 'x',\n 'position_y': 'y',\n 'position_z': 'z',\n 'velocity_x': 'vx',\n 'velocity_y': 'vy',\n 'velocity_z': 'vz',\n }\n\n # add magnitudes\n for band in 'ugrizyY':\n if band != 'y' and band != 'Y':\n self._quantity_modifiers['mag_{}_sdss'.format(band)] = (_calc_lensed_magnitude, 'SDSS_filters/magnitude:SDSS_{}:observed:dustAtlas'.format(band), 'magnification',)\n self._quantity_modifiers['mag_{}_sdss_no_host_extinction'.format(band)] = (_calc_lensed_magnitude, 'SDSS_filters/magnitude:SDSS_{}:observed'.format(band), 'magnification',)\n self._quantity_modifiers['mag_true_{}_sdss'.format(band)] = 'SDSS_filters/magnitude:SDSS_{}:observed:dustAtlas'.format(band)\n self._quantity_modifiers['mag_true_{}_sdss_no_host_extinction'.format(band)] = 'SDSS_filters/magnitude:SDSS_{}:observed'.format(band)\n self._quantity_modifiers['Mag_true_{}_sdss_z0'.format(band)] = 'SDSS_filters/magnitude:SDSS_{}:rest:dustAtlas'.format(band)\n self._quantity_modifiers['Mag_true_{}_sdss_z0_no_host_extinction'.format(band)] = 'SDSS_filters/magnitude:SDSS_{}:rest'.format(band)\n\n self._quantity_modifiers['mag_{}_lsst'.format(band)] = (_calc_lensed_magnitude, 'LSST_filters/magnitude:LSST_{}:observed:dustAtlas'.format(band.lower()), 'magnification',)\n self._quantity_modifiers['mag_{}_lsst_no_host_extinction'.format(band)] = (_calc_lensed_magnitude, 'LSST_filters/magnitude:LSST_{}:observed'.format(band.lower()), 'magnification',)\n self._quantity_modifiers['mag_true_{}_lsst'.format(band)] = 'LSST_filters/magnitude:LSST_{}:observed:dustAtlas'.format(band.lower())\n self._quantity_modifiers['mag_true_{}_lsst_no_host_extinction'.format(band)] = 'LSST_filters/magnitude:LSST_{}:observed'.format(band.lower())\n self._quantity_modifiers['Mag_true_{}_lsst_z0'.format(band)] = 'LSST_filters/magnitude:LSST_{}:rest:dustAtlas'.format(band.lower())\n self._quantity_modifiers['Mag_true_{}_lsst_z0_no_host_extinction'.format(band)] = 'LSST_filters/magnitude:LSST_{}:rest'.format(band.lower())\n\n if band != 'Y':\n self._quantity_modifiers['mag_{}'.format(band)] = self._quantity_modifiers['mag_{}_lsst'.format(band)]\n self._quantity_modifiers['mag_true_{}'.format(band)] = self._quantity_modifiers['mag_true_{}_lsst'.format(band)]\n\n\n # add SEDs\n translate_component_name = {'total': '', 'disk': '_disk', 'spheroid': '_bulge'}\n sed_re = re.compile(r'^SEDs/([a-z]+)LuminositiesStellar:SED_(\\d+)_(\\d+):rest((?::dustAtlas)?)$')\n for quantity in self._native_quantities:\n m = sed_re.match(quantity)\n if m is None:\n continue\n component, start, width, dust = m.groups()\n key = 'sed_{}_{}{}{}'.format(start, width, translate_component_name[component], '' if dust else '_no_host_extinction')\n self._quantity_modifiers[key] = quantity\n\n # make quantity modifiers work in older versions\n if catalog_version < StrictVersion('4.0'):\n self._quantity_modifiers.update({\n 'galaxy_id' : (_gen_galaxy_id, 'galaxyID'),\n })\n\n if catalog_version < StrictVersion('3.0'):\n self._quantity_modifiers.update({\n 'galaxy_id' : 'galaxyID',\n 'host_id': 'hostIndex',\n 'position_angle_true': 'morphology/positionAngle',\n 'ellipticity_1_true': 'morphology/totalEllipticity1',\n 'ellipticity_2_true': 'morphology/totalEllipticity2',\n 'ellipticity_1_disk_true': 'morphology/diskEllipticity1',\n 'ellipticity_2_disk_true': 'morphology/diskEllipticity2',\n 'ellipticity_1_bulge_true': 'morphology/spheroidEllipticity1',\n 'ellipticity_2_bulge_true': 'morphology/spheroidEllipticity2',\n })\n\n if catalog_version < StrictVersion('2.1.2'):\n self._quantity_modifiers.update({\n 'position_angle_true': (lambda pos_angle: np.rad2deg(np.rad2deg(pos_angle)), 'morphology/positionAngle'), #I converted the units the wrong way, so a double conversion is required.\n })\n\n if catalog_version < StrictVersion('2.1.1'):\n self._quantity_modifiers.update({\n 'sersic_disk': 'diskSersicIndex',\n 'sersic_bulge': 'spheroidSersicIndex',\n })\n for key in (\n 'size_minor_true',\n 'ellipticity_true',\n 'ellipticity_1_true',\n 'ellipticity_2_true',\n 'ellipticity_1_disk_true',\n 'ellipticity_2_disk_true',\n 'ellipticity_1_bulge_true',\n 'ellipticity_2_bulge_true',\n ):\n if key in self._quantity_modifiers:\n del self._quantity_modifiers[key]\n\n if catalog_version == StrictVersion('2.0'): # to be backward compatible\n self._quantity_modifiers.update({\n 'ra': (lambda x: x/3600, 'ra'),\n 'ra_true': (lambda x: x/3600, 'ra_true'),\n 'dec': (lambda x: x/3600, 'dec'),\n 'dec_true': (lambda x: x/3600, 'dec_true'),\n })\n\n\n def _generate_native_quantity_list(self):\n return self._native_quantities\n\n\n def _iter_native_dataset(self, native_filters=None):\n if native_filters is not None:\n raise ValueError('*native_filters* is not supported')\n with h5py.File(self._file, 'r') as fh:\n def _native_quantity_getter(native_quantity):\n return fh['galaxyProperties/{}'.format(native_quantity)].value # pylint: disable=no-member\n yield _native_quantity_getter\n\n\n def _get_native_quantity_info_dict(self, quantity, default=None):\n with h5py.File(self._file, 'r') as fh:\n quantity_key = 'galaxyProperties/' + quantity\n if quantity_key not in fh:\n return default\n modifier = lambda k, v: None if k == 'description' and v == b'None given' else v.decode()\n return {k: modifier(k, v) for k, v in fh[quantity_key].attrs.items()}\n\n\n def _get_quantity_info_dict(self, quantity, default=None):\n q_mod = self.get_quantity_modifier(quantity)\n if callable(q_mod) or (isinstance(q_mod, (tuple, list)) and len(q_mod) > 1 and callable(q_mod[0])):\n warnings.warn('This value is composed of a function on native quantities. So we have no idea what the units are')\n return default\n return self._get_native_quantity_info_dict(q_mod or quantity, default=default)\n"],"string":"[\n \"\\\"\\\"\\\"\\nAlpha Q galaxy catalog class.\\n\\\"\\\"\\\"\\nfrom __future__ import division\\nimport os\\nimport re\\nimport warnings\\nfrom distutils.version import StrictVersion # pylint: disable=no-name-in-module,import-error\\nimport numpy as np\\nimport h5py\\nfrom astropy.cosmology import FlatLambdaCDM\\nfrom GCR import BaseGenericCatalog\\nfrom .utils import md5\\n\\n__all__ = ['AlphaQGalaxyCatalog']\\n__version__ = '5.0.0'\\n\\n\\ndef _calc_weighted_size(size1, size2, lum1, lum2):\\n return ((size1*lum1) + (size2*lum2)) / (lum1+lum2)\\n\\n\\ndef _calc_weighted_size_minor(size1, size2, lum1, lum2, ell):\\n size = _calc_weighted_size(size1, size2, lum1, lum2)\\n return size * (1.0 - ell) / (1.0 + ell)\\n\\n\\ndef _calc_conv(mag, shear1, shear2):\\n slct = mag < 0.2\\n mag_corr = np.copy(mag)\\n mag_corr[slct] = 1.0 # manually changing the values for when magnification is near zero.\\n conv = 1.0 - np.sqrt(1.0/mag_corr + shear1**2 + shear2**2)\\n return conv\\n\\n\\ndef _calc_Rv(lum_v, lum_v_dust, lum_b, lum_b_dust):\\n v = lum_v_dust/lum_v\\n b = lum_b_dust/lum_b\\n bv = b/v\\n Rv = np.log10(v) / np.log10(bv)\\n Rv[(v == 1) & (b == 1)] = 1.0\\n Rv[v == b] = np.nan\\n return Rv\\n\\n\\ndef _calc_Av(lum_v, lum_v_dust):\\n Av = -2.5*(np.log10(lum_v_dust/lum_v))\\n Av[lum_v_dust == 0] = np.nan\\n return Av\\n\\n\\ndef _gen_position_angle(size_reference):\\n # pylint: disable=protected-access\\n size = size_reference.size\\n if not hasattr(_gen_position_angle, \\\"_pos_angle\\\") or _gen_position_angle._pos_angle.size != size:\\n _gen_position_angle._pos_angle = np.random.RandomState(123497).uniform(0, 180, size)\\n return _gen_position_angle._pos_angle\\n\\n\\ndef _calc_ellipticity_1(ellipticity):\\n # position angle using ellipticity as reference for the size or\\n # the array. The angle is converted from degrees to radians\\n pos_angle = _gen_position_angle(ellipticity)*np.pi/180.0\\n # use the correct conversion for ellipticity 1 from ellipticity\\n # and position angle\\n return ellipticity*np.cos(2.0*pos_angle)\\n\\n\\ndef _calc_ellipticity_2(ellipticity):\\n # position angle using ellipticity as reference for the size or\\n # the array. The angle is converted from degrees to radians\\n pos_angle = _gen_position_angle(ellipticity)*np.pi/180.0\\n # use the correct conversion for ellipticity 2 from ellipticity\\n # and position angle\\n return ellipticity*np.sin(2.0*pos_angle)\\n\\n\\ndef _gen_galaxy_id(size_reference):\\n # pylint: disable=protected-access\\n size = size_reference.size\\n if not hasattr(_gen_galaxy_id, \\\"_galaxy_id\\\") or _gen_galaxy_id._galaxy_id.size != size:\\n _gen_galaxy_id._galaxy_id = np.arange(size, dtype='i8')\\n return _gen_galaxy_id._galaxy_id\\n\\ndef _calc_lensed_magnitude(magnitude, magnification):\\n magnification[magnification==0]=1.0\\n return magnitude -2.5*np.log10(magnification)\\n\\nclass AlphaQGalaxyCatalog(BaseGenericCatalog):\\n \\\"\\\"\\\"\\n Alpha Q galaxy catalog class. Uses generic quantity and filter mechanisms\\n defined by BaseGenericCatalog class.\\n \\\"\\\"\\\"\\n\\n def _subclass_init(self, filename, **kwargs): #pylint: disable=W0221\\n\\n if not os.path.isfile(filename):\\n raise ValueError('Catalog file {} does not exist'.format(filename))\\n self._file = filename\\n\\n if kwargs.get('md5'):\\n if md5(self._file) != kwargs['md5']:\\n raise ValueError('md5 sum does not match!')\\n else:\\n warnings.warn('No md5 sum specified in the config file')\\n\\n self.lightcone = kwargs.get('lightcone')\\n\\n with h5py.File(self._file, 'r') as fh:\\n # pylint: disable=no-member\\n # get version\\n catalog_version = list()\\n for version_label in ('Major', 'Minor', 'MinorMinor'):\\n try:\\n catalog_version.append(fh['/metaData/version' + version_label].value)\\n except KeyError:\\n break\\n catalog_version = StrictVersion('.'.join(map(str, catalog_version or (2, 0))))\\n\\n # get cosmology\\n self.cosmology = FlatLambdaCDM(\\n H0=fh['metaData/simulationParameters/H_0'].value,\\n Om0=fh['metaData/simulationParameters/Omega_matter'].value,\\n Ob0=fh['metaData/simulationParameters/Omega_b'].value,\\n )\\n self.cosmology.sigma8 = fh['metaData/simulationParameters/sigma_8'].value\\n self.cosmology.n_s = fh['metaData/simulationParameters/N_s'].value\\n self.halo_mass_def = fh['metaData/simulationParameters/haloMassDefinition'].value\\n\\n # get sky area\\n if catalog_version >= StrictVersion(\\\"2.1.1\\\"):\\n self.sky_area = float(fh['metaData/skyArea'].value)\\n else:\\n self.sky_area = 25.0 #If the sky area isn't specified use the default value of the sky area.\\n\\n # get native quantities\\n self._native_quantities = set()\\n def _collect_native_quantities(name, obj):\\n if isinstance(obj, h5py.Dataset):\\n self._native_quantities.add(name)\\n fh['galaxyProperties'].visititems(_collect_native_quantities)\\n\\n # check versions\\n self.version = kwargs.get('version', '0.0.0')\\n config_version = StrictVersion(self.version)\\n if config_version != catalog_version:\\n raise ValueError('Catalog file version {} does not match config version {}'.format(catalog_version, config_version))\\n if StrictVersion(__version__) < config_version:\\n raise ValueError('Reader version {} is less than config version {}'.format(__version__, catalog_version))\\n\\n # specify quantity modifiers\\n self._quantity_modifiers = {\\n 'galaxy_id' : 'galaxyID',\\n 'ra': 'ra',\\n 'dec': 'dec',\\n 'ra_true': 'ra_true',\\n 'dec_true': 'dec_true',\\n 'redshift': 'redshift',\\n 'redshift_true': 'redshiftHubble',\\n 'shear_1': 'shear1',\\n 'shear_2': (np.negative, 'shear2'),\\n 'shear_2_treecorr': (np.negative, 'shear2'),\\n 'shear_2_phosim': 'shear2',\\n 'convergence': (\\n _calc_conv,\\n 'magnification',\\n 'shear1',\\n 'shear2',\\n ),\\n 'magnification': (lambda mag: np.where(mag < 0.2, 1.0, mag), 'magnification'),\\n 'halo_id': 'hostHaloTag',\\n 'halo_mass': 'hostHaloMass',\\n 'is_central': (lambda x: x.astype(np.bool), 'isCentral'),\\n 'stellar_mass': 'totalMassStellar',\\n 'stellar_mass_disk': 'diskMassStellar',\\n 'stellar_mass_bulge': 'spheroidMassStellar',\\n 'size_disk_true': 'morphology/diskMajorAxisArcsec',\\n 'size_bulge_true': 'morphology/spheroidMajorAxisArcsec',\\n 'size_minor_disk_true': 'morphology/diskMinorAxisArcsec',\\n 'size_minor_bulge_true': 'morphology/spheroidMinorAxisArcsec',\\n 'position_angle_true': (_gen_position_angle, 'morphology/positionAngle'),\\n 'sersic_disk': 'morphology/diskSersicIndex',\\n 'sersic_bulge': 'morphology/spheroidSersicIndex',\\n 'ellipticity_true': 'morphology/totalEllipticity',\\n 'ellipticity_1_true': (_calc_ellipticity_1, 'morphology/totalEllipticity'),\\n 'ellipticity_2_true': (_calc_ellipticity_2, 'morphology/totalEllipticity'),\\n 'ellipticity_disk_true': 'morphology/diskEllipticity',\\n 'ellipticity_1_disk_true': (_calc_ellipticity_1, 'morphology/diskEllipticity'),\\n 'ellipticity_2_disk_true': (_calc_ellipticity_2, 'morphology/diskEllipticity'),\\n 'ellipticity_bulge_true': 'morphology/spheroidEllipticity',\\n 'ellipticity_1_bulge_true': (_calc_ellipticity_1, 'morphology/spheroidEllipticity'),\\n 'ellipticity_2_bulge_true': (_calc_ellipticity_2, 'morphology/spheroidEllipticity'),\\n 'size_true': (\\n _calc_weighted_size,\\n 'morphology/diskMajorAxisArcsec',\\n 'morphology/spheroidMajorAxisArcsec',\\n 'LSST_filters/diskLuminositiesStellar:LSST_r:rest',\\n 'LSST_filters/spheroidLuminositiesStellar:LSST_r:rest',\\n ),\\n 'size_minor_true': (\\n _calc_weighted_size_minor,\\n 'morphology/diskMajorAxisArcsec',\\n 'morphology/spheroidMajorAxisArcsec',\\n 'LSST_filters/diskLuminositiesStellar:LSST_r:rest',\\n 'LSST_filters/spheroidLuminositiesStellar:LSST_r:rest',\\n 'morphology/totalEllipticity',\\n ),\\n 'bulge_to_total_ratio_i': (\\n lambda x, y: x/(x+y),\\n 'SDSS_filters/spheroidLuminositiesStellar:SDSS_i:observed',\\n 'SDSS_filters/diskLuminositiesStellar:SDSS_i:observed',\\n ),\\n 'A_v': (\\n _calc_Av,\\n 'otherLuminosities/totalLuminositiesStellar:V:rest',\\n 'otherLuminosities/totalLuminositiesStellar:V:rest:dustAtlas',\\n ),\\n 'A_v_disk': (\\n _calc_Av,\\n 'otherLuminosities/diskLuminositiesStellar:V:rest',\\n 'otherLuminosities/diskLuminositiesStellar:V:rest:dustAtlas',\\n ),\\n 'A_v_bulge': (\\n _calc_Av,\\n 'otherLuminosities/spheroidLuminositiesStellar:V:rest',\\n 'otherLuminosities/spheroidLuminositiesStellar:V:rest:dustAtlas',\\n ),\\n 'R_v': (\\n _calc_Rv,\\n 'otherLuminosities/totalLuminositiesStellar:V:rest',\\n 'otherLuminosities/totalLuminositiesStellar:V:rest:dustAtlas',\\n 'otherLuminosities/totalLuminositiesStellar:B:rest',\\n 'otherLuminosities/totalLuminositiesStellar:B:rest:dustAtlas',\\n ),\\n 'R_v_disk': (\\n _calc_Rv,\\n 'otherLuminosities/diskLuminositiesStellar:V:rest',\\n 'otherLuminosities/diskLuminositiesStellar:V:rest:dustAtlas',\\n 'otherLuminosities/diskLuminositiesStellar:B:rest',\\n 'otherLuminosities/diskLuminositiesStellar:B:rest:dustAtlas',\\n ),\\n 'R_v_bulge': (\\n _calc_Rv,\\n 'otherLuminosities/spheroidLuminositiesStellar:V:rest',\\n 'otherLuminosities/spheroidLuminositiesStellar:V:rest:dustAtlas',\\n 'otherLuminosities/spheroidLuminositiesStellar:B:rest',\\n 'otherLuminosities/spheroidLuminositiesStellar:B:rest:dustAtlas',\\n ),\\n 'position_x': 'x',\\n 'position_y': 'y',\\n 'position_z': 'z',\\n 'velocity_x': 'vx',\\n 'velocity_y': 'vy',\\n 'velocity_z': 'vz',\\n }\\n\\n # add magnitudes\\n for band in 'ugrizyY':\\n if band != 'y' and band != 'Y':\\n self._quantity_modifiers['mag_{}_sdss'.format(band)] = (_calc_lensed_magnitude, 'SDSS_filters/magnitude:SDSS_{}:observed:dustAtlas'.format(band), 'magnification',)\\n self._quantity_modifiers['mag_{}_sdss_no_host_extinction'.format(band)] = (_calc_lensed_magnitude, 'SDSS_filters/magnitude:SDSS_{}:observed'.format(band), 'magnification',)\\n self._quantity_modifiers['mag_true_{}_sdss'.format(band)] = 'SDSS_filters/magnitude:SDSS_{}:observed:dustAtlas'.format(band)\\n self._quantity_modifiers['mag_true_{}_sdss_no_host_extinction'.format(band)] = 'SDSS_filters/magnitude:SDSS_{}:observed'.format(band)\\n self._quantity_modifiers['Mag_true_{}_sdss_z0'.format(band)] = 'SDSS_filters/magnitude:SDSS_{}:rest:dustAtlas'.format(band)\\n self._quantity_modifiers['Mag_true_{}_sdss_z0_no_host_extinction'.format(band)] = 'SDSS_filters/magnitude:SDSS_{}:rest'.format(band)\\n\\n self._quantity_modifiers['mag_{}_lsst'.format(band)] = (_calc_lensed_magnitude, 'LSST_filters/magnitude:LSST_{}:observed:dustAtlas'.format(band.lower()), 'magnification',)\\n self._quantity_modifiers['mag_{}_lsst_no_host_extinction'.format(band)] = (_calc_lensed_magnitude, 'LSST_filters/magnitude:LSST_{}:observed'.format(band.lower()), 'magnification',)\\n self._quantity_modifiers['mag_true_{}_lsst'.format(band)] = 'LSST_filters/magnitude:LSST_{}:observed:dustAtlas'.format(band.lower())\\n self._quantity_modifiers['mag_true_{}_lsst_no_host_extinction'.format(band)] = 'LSST_filters/magnitude:LSST_{}:observed'.format(band.lower())\\n self._quantity_modifiers['Mag_true_{}_lsst_z0'.format(band)] = 'LSST_filters/magnitude:LSST_{}:rest:dustAtlas'.format(band.lower())\\n self._quantity_modifiers['Mag_true_{}_lsst_z0_no_host_extinction'.format(band)] = 'LSST_filters/magnitude:LSST_{}:rest'.format(band.lower())\\n\\n if band != 'Y':\\n self._quantity_modifiers['mag_{}'.format(band)] = self._quantity_modifiers['mag_{}_lsst'.format(band)]\\n self._quantity_modifiers['mag_true_{}'.format(band)] = self._quantity_modifiers['mag_true_{}_lsst'.format(band)]\\n\\n\\n # add SEDs\\n translate_component_name = {'total': '', 'disk': '_disk', 'spheroid': '_bulge'}\\n sed_re = re.compile(r'^SEDs/([a-z]+)LuminositiesStellar:SED_(\\\\d+)_(\\\\d+):rest((?::dustAtlas)?)$')\\n for quantity in self._native_quantities:\\n m = sed_re.match(quantity)\\n if m is None:\\n continue\\n component, start, width, dust = m.groups()\\n key = 'sed_{}_{}{}{}'.format(start, width, translate_component_name[component], '' if dust else '_no_host_extinction')\\n self._quantity_modifiers[key] = quantity\\n\\n # make quantity modifiers work in older versions\\n if catalog_version < StrictVersion('4.0'):\\n self._quantity_modifiers.update({\\n 'galaxy_id' : (_gen_galaxy_id, 'galaxyID'),\\n })\\n\\n if catalog_version < StrictVersion('3.0'):\\n self._quantity_modifiers.update({\\n 'galaxy_id' : 'galaxyID',\\n 'host_id': 'hostIndex',\\n 'position_angle_true': 'morphology/positionAngle',\\n 'ellipticity_1_true': 'morphology/totalEllipticity1',\\n 'ellipticity_2_true': 'morphology/totalEllipticity2',\\n 'ellipticity_1_disk_true': 'morphology/diskEllipticity1',\\n 'ellipticity_2_disk_true': 'morphology/diskEllipticity2',\\n 'ellipticity_1_bulge_true': 'morphology/spheroidEllipticity1',\\n 'ellipticity_2_bulge_true': 'morphology/spheroidEllipticity2',\\n })\\n\\n if catalog_version < StrictVersion('2.1.2'):\\n self._quantity_modifiers.update({\\n 'position_angle_true': (lambda pos_angle: np.rad2deg(np.rad2deg(pos_angle)), 'morphology/positionAngle'), #I converted the units the wrong way, so a double conversion is required.\\n })\\n\\n if catalog_version < StrictVersion('2.1.1'):\\n self._quantity_modifiers.update({\\n 'sersic_disk': 'diskSersicIndex',\\n 'sersic_bulge': 'spheroidSersicIndex',\\n })\\n for key in (\\n 'size_minor_true',\\n 'ellipticity_true',\\n 'ellipticity_1_true',\\n 'ellipticity_2_true',\\n 'ellipticity_1_disk_true',\\n 'ellipticity_2_disk_true',\\n 'ellipticity_1_bulge_true',\\n 'ellipticity_2_bulge_true',\\n ):\\n if key in self._quantity_modifiers:\\n del self._quantity_modifiers[key]\\n\\n if catalog_version == StrictVersion('2.0'): # to be backward compatible\\n self._quantity_modifiers.update({\\n 'ra': (lambda x: x/3600, 'ra'),\\n 'ra_true': (lambda x: x/3600, 'ra_true'),\\n 'dec': (lambda x: x/3600, 'dec'),\\n 'dec_true': (lambda x: x/3600, 'dec_true'),\\n })\\n\\n\\n def _generate_native_quantity_list(self):\\n return self._native_quantities\\n\\n\\n def _iter_native_dataset(self, native_filters=None):\\n if native_filters is not None:\\n raise ValueError('*native_filters* is not supported')\\n with h5py.File(self._file, 'r') as fh:\\n def _native_quantity_getter(native_quantity):\\n return fh['galaxyProperties/{}'.format(native_quantity)].value # pylint: disable=no-member\\n yield _native_quantity_getter\\n\\n\\n def _get_native_quantity_info_dict(self, quantity, default=None):\\n with h5py.File(self._file, 'r') as fh:\\n quantity_key = 'galaxyProperties/' + quantity\\n if quantity_key not in fh:\\n return default\\n modifier = lambda k, v: None if k == 'description' and v == b'None given' else v.decode()\\n return {k: modifier(k, v) for k, v in fh[quantity_key].attrs.items()}\\n\\n\\n def _get_quantity_info_dict(self, quantity, default=None):\\n q_mod = self.get_quantity_modifier(quantity)\\n if callable(q_mod) or (isinstance(q_mod, (tuple, list)) and len(q_mod) > 1 and callable(q_mod[0])):\\n warnings.warn('This value is composed of a function on native quantities. So we have no idea what the units are')\\n return default\\n return self._get_native_quantity_info_dict(q_mod or quantity, default=default)\\n\"\n]"},"apis":{"kind":"list like","value":[["numpy.sqrt","numpy.arange","numpy.cos","numpy.rad2deg","numpy.sin","numpy.copy","numpy.log10","numpy.random.RandomState","numpy.where"]],"string":"[\n [\n \"numpy.sqrt\",\n \"numpy.arange\",\n \"numpy.cos\",\n \"numpy.rad2deg\",\n \"numpy.sin\",\n \"numpy.copy\",\n \"numpy.log10\",\n \"numpy.random.RandomState\",\n \"numpy.where\"\n ]\n]"},"possible_versions":{"kind":"list like","value":[{"matplotlib":[],"numpy":[],"pandas":[],"scipy":[],"tensorflow":[]}],"string":"[\n {\n \"matplotlib\": [],\n \"numpy\": [],\n \"pandas\": [],\n \"scipy\": [],\n \"tensorflow\": []\n }\n]"}}},{"rowIdx":72521,"cells":{"repo_name":{"kind":"string","value":"pantheon5100/simsimpp"},"hexsha":{"kind":"list like","value":["147d5cdaa986d1da1608efb6cf663826bfd57053"],"string":"[\n \"147d5cdaa986d1da1608efb6cf663826bfd57053\"\n]"},"file_path":{"kind":"list like","value":["solo/methods/new_predictor.py"],"string":"[\n \"solo/methods/new_predictor.py\"\n]"},"code":{"kind":"list like","value":["import argparse\nfrom typing import Any, Dict, List, Sequence\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom solo.losses.simsiam import simsiam_loss_func\nfrom solo.methods.base import BaseModel\nfrom solo.losses.vicreg import covariance_loss\n\n\ndef value_constrain(x, type=None):\n if type == \"sigmoid\":\n return 2*torch.sigmoid(x)-1\n elif type == \"tanh\":\n return torch.tanh(0.5*x)\n else:\n return x\n\n\nclass BiasLayer(nn.Module):\n def __init__(self, output_dim, bias=False, weight_matrix=False, constrain_type=\"none\", bias_first=False):\n super(BiasLayer, self).__init__()\n self.constrain_type = constrain_type\n self.bias_first = bias_first\n\n self.weight_matrix = weight_matrix\n if weight_matrix:\n self.w = nn.Linear(output_dim, output_dim, bias=False)\n\n self.bias = bias\n if bias:\n self.bias_vector = nn.Parameter(torch.zeros(1, output_dim))\n\n def _base_forward(self, x):\n if self.bias_first:\n self.bias_vector.data = value_constrain(self.bias_vector.data, type=self.constrain_type).detach()\n x = x + self.bias_vector\n\n self.w.weight.data = value_constrain(self.w.weight.data, type=self.constrain_type).detach()\n x = self.w(x)\n else:\n self.w.weight.data = value_constrain(self.w.weight.data, type=self.constrain_type).detach()\n x = self.w(x)\n\n self.bias_vector.data = value_constrain(self.bias_vector.data, type=self.constrain_type).detach()\n x = x + self.bias_vector\n return x\n\n def forward(self,x):\n \n x = F.normalize(x, dim=-1)\n\n if self.bias and self.weight_matrix:\n x = self._base_forward(x)\n return x\n\n if self.bias:\n self.bias_vector.data = value_constrain(self.bias_vector.data, type=self.constrain_type).detach()\n x = x + self.bias_vector\n\n if self.weight_matrix:\n self.w.weight.data = value_constrain(self.w.weight.data, type=self.constrain_type).detach()\n x = self.w(x)\n\n return x\n\nclass NewPredictor(BaseModel):\n def __init__(\n self,\n output_dim: int,\n proj_hidden_dim: int,\n pred_hidden_dim: int,\n BL:bool,\n bias:bool,\n weight_matrix:bool,\n constrain:str,\n bias_first:bool,\n **kwargs,\n ):\n \"\"\"Implements SimSiam (https://arxiv.org/abs/2011.10566).\n\n Args:\n output_dim (int): number of dimensions of projected features.\n proj_hidden_dim (int): number of neurons of the hidden layers of the projector.\n pred_hidden_dim (int): number of neurons of the hidden layers of the predictor.\n \"\"\"\n\n super().__init__(**kwargs)\n\n # projector\n self.projector = nn.Sequential(\n nn.Linear(self.features_dim, proj_hidden_dim, bias=False),\n nn.BatchNorm1d(proj_hidden_dim),\n nn.ReLU(),\n nn.Linear(proj_hidden_dim, proj_hidden_dim, bias=False),\n nn.BatchNorm1d(proj_hidden_dim),\n nn.ReLU(),\n nn.Linear(proj_hidden_dim, output_dim),\n # nn.BatchNorm1d(output_dim, affine=False),\n )\n # self.projector[6].bias.requires_grad = False # hack: not use bias as it is followed by BN\n\n\n # predictor\n if not BL:\n assert bias and weight_matrix\n self.predictor = nn.Sequential(\n nn.Linear(output_dim, pred_hidden_dim, bias=False),\n nn.BatchNorm1d(pred_hidden_dim),\n nn.ReLU(),\n nn.Linear(pred_hidden_dim, output_dim),\n )\n elif BL:\n self.predictor = nn.Sequential(\n BiasLayer(output_dim,bias=bias, weight_matrix=weight_matrix, constrain_type=constrain, bias_first=bias_first)\n )\n \n self.register_buffer(\"previouscentering\", torch.randn(1, output_dim))\n self.register_buffer(\"onestepbeforecentering\", torch.randn(1, output_dim))\n\n\n @staticmethod\n def add_model_specific_args(parent_parser: argparse.ArgumentParser) -> argparse.ArgumentParser:\n parent_parser = super(NewPredictor, NewPredictor).add_model_specific_args(parent_parser)\n parser = parent_parser.add_argument_group(\"newpredictor\")\n\n # projector\n parser.add_argument(\"--output_dim\", type=int, default=128)\n parser.add_argument(\"--proj_hidden_dim\", type=int, default=2048)\n\n # predictor\n parser.add_argument(\"--BL\", action=\"store_true\")\n parser.add_argument(\"--bias\", action=\"store_true\")\n parser.add_argument(\"--bias_first\", action=\"store_true\")\n parser.add_argument(\"--weight_matrix\", action=\"store_true\")\n\n SUPPORTED_VALUE_CONSTRAIN = [\"none\", \"sigmoid\", \"tanh\"]\n parser.add_argument(\"--constrain\", choices=SUPPORTED_VALUE_CONSTRAIN, type=str)\n\n\n parser.add_argument(\"--pred_hidden_dim\", type=int, default=512)\n\n return parent_parser\n\n @property\n def learnable_params(self) -> List[dict]:\n \"\"\"Adds projector and predictor parameters to the parent's learnable parameters.\n\n Returns:\n List[dict]: list of learnable parameters.\n \"\"\"\n\n extra_learnable_params: List[dict] = [\n {\"params\": self.projector.parameters()},\n {\"params\": self.predictor.parameters(), \"static_lr\": True},\n ]\n return super().learnable_params + extra_learnable_params\n\n def forward(self, X: torch.Tensor, *args, **kwargs) -> Dict[str, Any]:\n \"\"\"Performs the forward pass of the encoder, the projector and the predictor.\n\n Args:\n X (torch.Tensor): a batch of images in the tensor format.\n\n Returns:\n Dict[str, Any]:\n a dict containing the outputs of the parent\n and the projected and predicted features.\n \"\"\"\n\n out = super().forward(X, *args, **kwargs)\n z = self.projector(out[\"feats\"])\n p = self.predictor(z)\n return {**out, \"z\": z, \"p\": p}\n\n def training_step(self, batch: Sequence[Any], batch_idx: int) -> torch.Tensor:\n \"\"\"Training step for SimSiam reusing BaseModel training step.\n\n Args:\n batch (Sequence[Any]): a batch of data in the format of [img_indexes, [X], Y], where\n [X] is a list of size self.num_crops containing batches of images\n batch_idx (int): index of the batch\n\n Returns:\n torch.Tensor: total loss composed of SimSiam loss and classification loss\n \"\"\"\n\n out = super().training_step(batch, batch_idx)\n class_loss = out[\"loss\"]\n feats1, feats2 = out[\"feats\"]\n\n z1 = self.projector(feats1)\n z2 = self.projector(feats2)\n\n p1 = self.predictor(z1)\n p2 = self.predictor(z2)\n\n # ------- contrastive loss -------\n neg_cos_sim = simsiam_loss_func(p1, z2) / 2 + simsiam_loss_func(p2, z1) / 2\n\n # calculate std of features\n z1_std = F.normalize(z1, dim=-1).std(dim=0).mean()\n z2_std = F.normalize(z2, dim=-1).std(dim=0).mean()\n z_std = (z1_std + z2_std) / 2\n\n with torch.no_grad():\n z1_norm = F.normalize(z1, dim=-1)\n z2_norm = F.normalize(z2, dim=-1)\n # normalize the vector to make it comparable\n\n centervector = ((z1_norm + z2_norm)/2).mean(dim=0)\n residualvector = z2_norm - centervector\n # import pdb; pdb.set_trace()\n\n ZvsC = F.cosine_similarity(z2_norm, centervector.expand(z2_norm.size(0), 2048), dim=-1).mean()\n ZvsR = F.cosine_similarity(z2_norm, residualvector, dim=-1).mean()\n CvsR = F.cosine_similarity(centervector.expand(z2_norm.size(0), 2048), residualvector, dim=-1).mean()\n\n\n ratio_RvsW = (torch.linalg.norm(residualvector, dim=1, ord=2) / torch.linalg.norm(z2_norm, dim=1, ord=2)).mean()\n ratio_CvsW = (torch.linalg.norm(centervector.expand(z2_norm.size(0), 2048), dim=1, ord=2) / torch.linalg.norm(z2_norm, dim=1, ord=2)).mean()\n\n CS1vsCc = F.cosine_similarity(self.onestepbeforecentering, centervector.reshape(1, -1))\n CS1minusCcvsCc = F.cosine_similarity(centervector.reshape(1, -1)-self.onestepbeforecentering , centervector.reshape(1, -1))\n CS1minusCcvsCS1 = F.cosine_similarity(centervector.reshape(1, -1)-self.onestepbeforecentering , self.onestepbeforecentering)\n\n self.onestepbeforecentering = centervector.reshape(1, -1)\n\n new_metric_log={\"ZvsC_norm\":ZvsC,\n \"ZvsR_norm\":ZvsR,\n \"ratio_RvsW_norm\":ratio_RvsW,\n \"ZvsR_norm\":ZvsR,\n \"ratio_CvsW_norm\":ratio_CvsW,\n \"CvsR_norm\":CvsR,\n \"CS1vsCc\":CS1vsCc,\n \"CS1minusCcvsCc\":CS1minusCcvsCc,\n \"CS1minusCcvsCS1\":CS1minusCcvsCS1,\n }\n\n if self.trainer.global_step % 100 == 0:\n\n CpvsCc = F.cosine_similarity(self.previouscentering, centervector.reshape(1, -1))\n\n self.previouscentering = centervector.reshape(1, -1).clone()\n\n new_metric_log.update({\"CpvsCc_norm\": CpvsCc})\n\n # calculate std of features\n z1_std = F.normalize(z1, dim=-1).std(dim=0).mean()\n z2_std = F.normalize(z2, dim=-1).std(dim=0).mean()\n z_std = (z1_std + z2_std) / 2\n\n with torch.no_grad():\n cov_loss = covariance_loss(z1_norm, z2_norm)\n mean_z = (z1_norm.abs().mean(dim=1) + z2_norm.abs().mean(dim=1)).mean()/2\n\n metrics = {\n \"neg_cos_sim\": neg_cos_sim,\n \"train_z_std\": z_std,\n \"cov_loss\": cov_loss,\n \"mean_z\": mean_z,\n }\n\n metrics.update(new_metric_log)\n\n self.log_dict(metrics, on_epoch=True, sync_dist=True)\n\n return neg_cos_sim + class_loss\n"],"string":"[\n \"import argparse\\nfrom typing import Any, Dict, List, Sequence\\n\\nimport torch\\nimport torch.nn as nn\\nimport torch.nn.functional as F\\nfrom solo.losses.simsiam import simsiam_loss_func\\nfrom solo.methods.base import BaseModel\\nfrom solo.losses.vicreg import covariance_loss\\n\\n\\ndef value_constrain(x, type=None):\\n if type == \\\"sigmoid\\\":\\n return 2*torch.sigmoid(x)-1\\n elif type == \\\"tanh\\\":\\n return torch.tanh(0.5*x)\\n else:\\n return x\\n\\n\\nclass BiasLayer(nn.Module):\\n def __init__(self, output_dim, bias=False, weight_matrix=False, constrain_type=\\\"none\\\", bias_first=False):\\n super(BiasLayer, self).__init__()\\n self.constrain_type = constrain_type\\n self.bias_first = bias_first\\n\\n self.weight_matrix = weight_matrix\\n if weight_matrix:\\n self.w = nn.Linear(output_dim, output_dim, bias=False)\\n\\n self.bias = bias\\n if bias:\\n self.bias_vector = nn.Parameter(torch.zeros(1, output_dim))\\n\\n def _base_forward(self, x):\\n if self.bias_first:\\n self.bias_vector.data = value_constrain(self.bias_vector.data, type=self.constrain_type).detach()\\n x = x + self.bias_vector\\n\\n self.w.weight.data = value_constrain(self.w.weight.data, type=self.constrain_type).detach()\\n x = self.w(x)\\n else:\\n self.w.weight.data = value_constrain(self.w.weight.data, type=self.constrain_type).detach()\\n x = self.w(x)\\n\\n self.bias_vector.data = value_constrain(self.bias_vector.data, type=self.constrain_type).detach()\\n x = x + self.bias_vector\\n return x\\n\\n def forward(self,x):\\n \\n x = F.normalize(x, dim=-1)\\n\\n if self.bias and self.weight_matrix:\\n x = self._base_forward(x)\\n return x\\n\\n if self.bias:\\n self.bias_vector.data = value_constrain(self.bias_vector.data, type=self.constrain_type).detach()\\n x = x + self.bias_vector\\n\\n if self.weight_matrix:\\n self.w.weight.data = value_constrain(self.w.weight.data, type=self.constrain_type).detach()\\n x = self.w(x)\\n\\n return x\\n\\nclass NewPredictor(BaseModel):\\n def __init__(\\n self,\\n output_dim: int,\\n proj_hidden_dim: int,\\n pred_hidden_dim: int,\\n BL:bool,\\n bias:bool,\\n weight_matrix:bool,\\n constrain:str,\\n bias_first:bool,\\n **kwargs,\\n ):\\n \\\"\\\"\\\"Implements SimSiam (https://arxiv.org/abs/2011.10566).\\n\\n Args:\\n output_dim (int): number of dimensions of projected features.\\n proj_hidden_dim (int): number of neurons of the hidden layers of the projector.\\n pred_hidden_dim (int): number of neurons of the hidden layers of the predictor.\\n \\\"\\\"\\\"\\n\\n super().__init__(**kwargs)\\n\\n # projector\\n self.projector = nn.Sequential(\\n nn.Linear(self.features_dim, proj_hidden_dim, bias=False),\\n nn.BatchNorm1d(proj_hidden_dim),\\n nn.ReLU(),\\n nn.Linear(proj_hidden_dim, proj_hidden_dim, bias=False),\\n nn.BatchNorm1d(proj_hidden_dim),\\n nn.ReLU(),\\n nn.Linear(proj_hidden_dim, output_dim),\\n # nn.BatchNorm1d(output_dim, affine=False),\\n )\\n # self.projector[6].bias.requires_grad = False # hack: not use bias as it is followed by BN\\n\\n\\n # predictor\\n if not BL:\\n assert bias and weight_matrix\\n self.predictor = nn.Sequential(\\n nn.Linear(output_dim, pred_hidden_dim, bias=False),\\n nn.BatchNorm1d(pred_hidden_dim),\\n nn.ReLU(),\\n nn.Linear(pred_hidden_dim, output_dim),\\n )\\n elif BL:\\n self.predictor = nn.Sequential(\\n BiasLayer(output_dim,bias=bias, weight_matrix=weight_matrix, constrain_type=constrain, bias_first=bias_first)\\n )\\n \\n self.register_buffer(\\\"previouscentering\\\", torch.randn(1, output_dim))\\n self.register_buffer(\\\"onestepbeforecentering\\\", torch.randn(1, output_dim))\\n\\n\\n @staticmethod\\n def add_model_specific_args(parent_parser: argparse.ArgumentParser) -> argparse.ArgumentParser:\\n parent_parser = super(NewPredictor, NewPredictor).add_model_specific_args(parent_parser)\\n parser = parent_parser.add_argument_group(\\\"newpredictor\\\")\\n\\n # projector\\n parser.add_argument(\\\"--output_dim\\\", type=int, default=128)\\n parser.add_argument(\\\"--proj_hidden_dim\\\", type=int, default=2048)\\n\\n # predictor\\n parser.add_argument(\\\"--BL\\\", action=\\\"store_true\\\")\\n parser.add_argument(\\\"--bias\\\", action=\\\"store_true\\\")\\n parser.add_argument(\\\"--bias_first\\\", action=\\\"store_true\\\")\\n parser.add_argument(\\\"--weight_matrix\\\", action=\\\"store_true\\\")\\n\\n SUPPORTED_VALUE_CONSTRAIN = [\\\"none\\\", \\\"sigmoid\\\", \\\"tanh\\\"]\\n parser.add_argument(\\\"--constrain\\\", choices=SUPPORTED_VALUE_CONSTRAIN, type=str)\\n\\n\\n parser.add_argument(\\\"--pred_hidden_dim\\\", type=int, default=512)\\n\\n return parent_parser\\n\\n @property\\n def learnable_params(self) -> List[dict]:\\n \\\"\\\"\\\"Adds projector and predictor parameters to the parent's learnable parameters.\\n\\n Returns:\\n List[dict]: list of learnable parameters.\\n \\\"\\\"\\\"\\n\\n extra_learnable_params: List[dict] = [\\n {\\\"params\\\": self.projector.parameters()},\\n {\\\"params\\\": self.predictor.parameters(), \\\"static_lr\\\": True},\\n ]\\n return super().learnable_params + extra_learnable_params\\n\\n def forward(self, X: torch.Tensor, *args, **kwargs) -> Dict[str, Any]:\\n \\\"\\\"\\\"Performs the forward pass of the encoder, the projector and the predictor.\\n\\n Args:\\n X (torch.Tensor): a batch of images in the tensor format.\\n\\n Returns:\\n Dict[str, Any]:\\n a dict containing the outputs of the parent\\n and the projected and predicted features.\\n \\\"\\\"\\\"\\n\\n out = super().forward(X, *args, **kwargs)\\n z = self.projector(out[\\\"feats\\\"])\\n p = self.predictor(z)\\n return {**out, \\\"z\\\": z, \\\"p\\\": p}\\n\\n def training_step(self, batch: Sequence[Any], batch_idx: int) -> torch.Tensor:\\n \\\"\\\"\\\"Training step for SimSiam reusing BaseModel training step.\\n\\n Args:\\n batch (Sequence[Any]): a batch of data in the format of [img_indexes, [X], Y], where\\n [X] is a list of size self.num_crops containing batches of images\\n batch_idx (int): index of the batch\\n\\n Returns:\\n torch.Tensor: total loss composed of SimSiam loss and classification loss\\n \\\"\\\"\\\"\\n\\n out = super().training_step(batch, batch_idx)\\n class_loss = out[\\\"loss\\\"]\\n feats1, feats2 = out[\\\"feats\\\"]\\n\\n z1 = self.projector(feats1)\\n z2 = self.projector(feats2)\\n\\n p1 = self.predictor(z1)\\n p2 = self.predictor(z2)\\n\\n # ------- contrastive loss -------\\n neg_cos_sim = simsiam_loss_func(p1, z2) / 2 + simsiam_loss_func(p2, z1) / 2\\n\\n # calculate std of features\\n z1_std = F.normalize(z1, dim=-1).std(dim=0).mean()\\n z2_std = F.normalize(z2, dim=-1).std(dim=0).mean()\\n z_std = (z1_std + z2_std) / 2\\n\\n with torch.no_grad():\\n z1_norm = F.normalize(z1, dim=-1)\\n z2_norm = F.normalize(z2, dim=-1)\\n # normalize the vector to make it comparable\\n\\n centervector = ((z1_norm + z2_norm)/2).mean(dim=0)\\n residualvector = z2_norm - centervector\\n # import pdb; pdb.set_trace()\\n\\n ZvsC = F.cosine_similarity(z2_norm, centervector.expand(z2_norm.size(0), 2048), dim=-1).mean()\\n ZvsR = F.cosine_similarity(z2_norm, residualvector, dim=-1).mean()\\n CvsR = F.cosine_similarity(centervector.expand(z2_norm.size(0), 2048), residualvector, dim=-1).mean()\\n\\n\\n ratio_RvsW = (torch.linalg.norm(residualvector, dim=1, ord=2) / torch.linalg.norm(z2_norm, dim=1, ord=2)).mean()\\n ratio_CvsW = (torch.linalg.norm(centervector.expand(z2_norm.size(0), 2048), dim=1, ord=2) / torch.linalg.norm(z2_norm, dim=1, ord=2)).mean()\\n\\n CS1vsCc = F.cosine_similarity(self.onestepbeforecentering, centervector.reshape(1, -1))\\n CS1minusCcvsCc = F.cosine_similarity(centervector.reshape(1, -1)-self.onestepbeforecentering , centervector.reshape(1, -1))\\n CS1minusCcvsCS1 = F.cosine_similarity(centervector.reshape(1, -1)-self.onestepbeforecentering , self.onestepbeforecentering)\\n\\n self.onestepbeforecentering = centervector.reshape(1, -1)\\n\\n new_metric_log={\\\"ZvsC_norm\\\":ZvsC,\\n \\\"ZvsR_norm\\\":ZvsR,\\n \\\"ratio_RvsW_norm\\\":ratio_RvsW,\\n \\\"ZvsR_norm\\\":ZvsR,\\n \\\"ratio_CvsW_norm\\\":ratio_CvsW,\\n \\\"CvsR_norm\\\":CvsR,\\n \\\"CS1vsCc\\\":CS1vsCc,\\n \\\"CS1minusCcvsCc\\\":CS1minusCcvsCc,\\n \\\"CS1minusCcvsCS1\\\":CS1minusCcvsCS1,\\n }\\n\\n if self.trainer.global_step % 100 == 0:\\n\\n CpvsCc = F.cosine_similarity(self.previouscentering, centervector.reshape(1, -1))\\n\\n self.previouscentering = centervector.reshape(1, -1).clone()\\n\\n new_metric_log.update({\\\"CpvsCc_norm\\\": CpvsCc})\\n\\n # calculate std of features\\n z1_std = F.normalize(z1, dim=-1).std(dim=0).mean()\\n z2_std = F.normalize(z2, dim=-1).std(dim=0).mean()\\n z_std = (z1_std + z2_std) / 2\\n\\n with torch.no_grad():\\n cov_loss = covariance_loss(z1_norm, z2_norm)\\n mean_z = (z1_norm.abs().mean(dim=1) + z2_norm.abs().mean(dim=1)).mean()/2\\n\\n metrics = {\\n \\\"neg_cos_sim\\\": neg_cos_sim,\\n \\\"train_z_std\\\": z_std,\\n \\\"cov_loss\\\": cov_loss,\\n \\\"mean_z\\\": mean_z,\\n }\\n\\n metrics.update(new_metric_log)\\n\\n self.log_dict(metrics, on_epoch=True, sync_dist=True)\\n\\n return neg_cos_sim + class_loss\\n\"\n]"},"apis":{"kind":"list like","value":[["torch.nn.functional.normalize","torch.nn.BatchNorm1d","torch.sigmoid","torch.zeros","torch.randn","torch.linalg.norm","torch.tanh","torch.nn.Linear","torch.no_grad","torch.nn.functional.cosine_similarity","torch.nn.ReLU"]],"string":"[\n [\n \"torch.nn.functional.normalize\",\n \"torch.nn.BatchNorm1d\",\n \"torch.sigmoid\",\n \"torch.zeros\",\n \"torch.randn\",\n \"torch.linalg.norm\",\n \"torch.tanh\",\n \"torch.nn.Linear\",\n \"torch.no_grad\",\n \"torch.nn.functional.cosine_similarity\",\n \"torch.nn.ReLU\"\n ]\n]"},"possible_versions":{"kind":"list like","value":[{"matplotlib":[],"numpy":[],"pandas":[],"scipy":[],"tensorflow":[]}],"string":"[\n {\n \"matplotlib\": [],\n \"numpy\": [],\n \"pandas\": [],\n \"scipy\": [],\n \"tensorflow\": []\n }\n]"}}},{"rowIdx":72522,"cells":{"repo_name":{"kind":"string","value":"jbreitbart/detectron2"},"hexsha":{"kind":"list like","value":["53dfc401103993a64f6714b7bfc36bcebe36e55c"],"string":"[\n \"53dfc401103993a64f6714b7bfc36bcebe36e55c\"\n]"},"file_path":{"kind":"list like","value":["projects/DensePose/densepose/evaluator.py"],"string":"[\n \"projects/DensePose/densepose/evaluator.py\"\n]"},"code":{"kind":"list like","value":["# -*- coding: utf-8 -*-\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\nimport contextlib\nimport copy\nimport io\nimport itertools\nimport logging\nimport numpy as np\nimport os\nfrom collections import OrderedDict\nimport pycocotools.mask as mask_utils\nimport torch\nfrom fvcore.common.file_io import PathManager\nfrom pycocotools.coco import COCO\n\nfrom detectron2.data import MetadataCatalog\nfrom detectron2.evaluation import DatasetEvaluator\nfrom detectron2.structures import BoxMode\nfrom detectron2.utils.comm import all_gather, is_main_process, synchronize\nfrom detectron2.utils.logger import create_small_table\n\nfrom .converters import ToChartResultConverter, ToMaskConverter\nfrom .densepose_coco_evaluation import DensePoseCocoEval, DensePoseEvalMode\nfrom .structures import compress_quantized_densepose_chart_result, quantize_densepose_chart_result\n\n\nclass DensePoseCOCOEvaluator(DatasetEvaluator):\n def __init__(self, dataset_name, distributed, output_dir=None):\n self._distributed = distributed\n self._output_dir = output_dir\n\n self._cpu_device = torch.device(\"cpu\")\n self._logger = logging.getLogger(__name__)\n\n self._metadata = MetadataCatalog.get(dataset_name)\n self._min_threshold = 0.5\n json_file = PathManager.get_local_path(self._metadata.json_file)\n with contextlib.redirect_stdout(io.StringIO()):\n self._coco_api = COCO(json_file)\n\n def reset(self):\n self._predictions = []\n\n def process(self, inputs, outputs):\n \"\"\"\n Args:\n inputs: the inputs to a COCO model (e.g., GeneralizedRCNN).\n It is a list of dict. Each dict corresponds to an image and\n contains keys like \"height\", \"width\", \"file_name\", \"image_id\".\n outputs: the outputs of a COCO model. It is a list of dicts with key\n \"instances\" that contains :class:`Instances`.\n The :class:`Instances` object needs to have `densepose` field.\n \"\"\"\n for input, output in zip(inputs, outputs):\n instances = output[\"instances\"].to(self._cpu_device)\n if not instances.has(\"pred_densepose\"):\n continue\n json_results = prediction_to_json(instances, input[\"image_id\"])\n self._predictions.extend(json_results)\n\n def evaluate(self, imgIds=None):\n if self._distributed:\n synchronize()\n predictions = all_gather(self._predictions)\n predictions = list(itertools.chain(*predictions))\n if not is_main_process():\n return\n else:\n predictions = self._predictions\n\n return copy.deepcopy(self._eval_predictions(predictions, imgIds))\n\n def _eval_predictions(self, predictions, imgIds=None):\n \"\"\"\n Evaluate predictions on densepose.\n Return results with the metrics of the tasks.\n \"\"\"\n self._logger.info(\"Preparing results for COCO format ...\")\n\n if self._output_dir:\n PathManager.mkdirs(self._output_dir)\n file_path = os.path.join(self._output_dir, \"coco_densepose_predictions.pth\")\n with PathManager.open(file_path, \"wb\") as f:\n torch.save(predictions, f)\n\n self._logger.info(\"Evaluating predictions ...\")\n res = OrderedDict()\n results_gps, results_gpsm, results_segm = _evaluate_predictions_on_coco(\n self._coco_api, predictions, min_threshold=self._min_threshold, imgIds=imgIds\n )\n res[\"densepose_gps\"] = results_gps\n res[\"densepose_gpsm\"] = results_gpsm\n res[\"densepose_segm\"] = results_segm\n return res\n\n\ndef prediction_to_json(instances, img_id):\n \"\"\"\n Args:\n instances (Instances): the output of the model\n img_id (str): the image id in COCO\n\n Returns:\n list[dict]: the results in densepose evaluation format\n \"\"\"\n scores = instances.scores.tolist()\n segmentations = ToMaskConverter.convert(\n instances.pred_densepose, instances.pred_boxes, instances.image_size\n )\n raw_boxes_xywh = BoxMode.convert(\n instances.pred_boxes.tensor.clone(), BoxMode.XYXY_ABS, BoxMode.XYWH_ABS\n )\n\n results = []\n for k in range(len(instances)):\n densepose_results_quantized_compressed = compress_quantized_densepose_chart_result(\n quantize_densepose_chart_result(\n ToChartResultConverter.convert(instances.pred_densepose[k], instances.pred_boxes[k])\n )\n )\n segmentation = segmentations.tensor[k]\n segmentation_encoded = mask_utils.encode(\n np.require(segmentation.numpy(), dtype=np.uint8, requirements=[\"F\"])\n )\n segmentation_encoded[\"counts\"] = segmentation_encoded[\"counts\"].decode(\"utf-8\")\n result = {\n \"image_id\": img_id,\n \"category_id\": 1, # densepose only has one class\n \"bbox\": raw_boxes_xywh[k].tolist(),\n \"score\": scores[k],\n \"densepose\": densepose_results_quantized_compressed,\n \"segmentation\": segmentation_encoded,\n }\n results.append(result)\n return results\n\n\ndef _evaluate_predictions_on_coco(coco_gt, coco_results, min_threshold=0.5, imgIds=None):\n logger = logging.getLogger(__name__)\n\n segm_metrics = _get_segmentation_metrics()\n densepose_metrics = _get_densepose_metrics(min_threshold)\n if len(coco_results) == 0: # cocoapi does not handle empty results very well\n logger.warn(\"No predictions from the model! Set scores to -1\")\n results_gps = {metric: -1 for metric in densepose_metrics}\n results_gpsm = {metric: -1 for metric in densepose_metrics}\n results_segm = {metric: -1 for metric in segm_metrics}\n return results_gps, results_gpsm, results_segm\n\n coco_dt = coco_gt.loadRes(coco_results)\n results_segm = _evaluate_predictions_on_coco_segm(\n coco_gt, coco_dt, segm_metrics, min_threshold, imgIds\n )\n logger.info(\"Evaluation results for densepose segm: \\n\" + create_small_table(results_segm))\n results_gps = _evaluate_predictions_on_coco_gps(\n coco_gt, coco_dt, densepose_metrics, min_threshold, imgIds\n )\n logger.info(\n \"Evaluation results for densepose, GPS metric: \\n\" + create_small_table(results_gps)\n )\n results_gpsm = _evaluate_predictions_on_coco_gpsm(\n coco_gt, coco_dt, densepose_metrics, min_threshold, imgIds\n )\n logger.info(\n \"Evaluation results for densepose, GPSm metric: \\n\" + create_small_table(results_gpsm)\n )\n return results_gps, results_gpsm, results_segm\n\n\ndef _get_densepose_metrics(min_threshold=0.5):\n metrics = [\"AP\"]\n if min_threshold <= 0.201:\n metrics += [\"AP20\"]\n if min_threshold <= 0.301:\n metrics += [\"AP30\"]\n if min_threshold <= 0.401:\n metrics += [\"AP40\"]\n metrics.extend([\"AP50\", \"AP75\", \"APm\", \"APl\", \"AR\", \"AR50\", \"AR75\", \"ARm\", \"ARl\"])\n return metrics\n\n\ndef _get_segmentation_metrics():\n return [\n \"AP\",\n \"AP50\",\n \"AP75\",\n \"APs\",\n \"APm\",\n \"APl\",\n \"AR@1\",\n \"AR@10\",\n \"AR@100\",\n \"ARs\",\n \"ARm\",\n \"ARl\",\n ]\n\n\ndef _evaluate_predictions_on_coco_gps(coco_gt, coco_dt, metrics, min_threshold=0.5, imgIds=None):\n coco_eval = DensePoseCocoEval(coco_gt, coco_dt, \"densepose\", dpEvalMode=DensePoseEvalMode.GPS)\n if imgIds is not None:\n coco_eval.params.imgIds = imgIds\n coco_eval.params.iouThrs = np.linspace(\n min_threshold, 0.95, int(np.round((0.95 - min_threshold) / 0.05)) + 1, endpoint=True\n )\n coco_eval.evaluate()\n coco_eval.accumulate()\n coco_eval.summarize()\n results = {metric: float(coco_eval.stats[idx] * 100) for idx, metric in enumerate(metrics)}\n return results\n\n\ndef _evaluate_predictions_on_coco_gpsm(coco_gt, coco_dt, metrics, min_threshold=0.5, imgIds=None):\n coco_eval = DensePoseCocoEval(coco_gt, coco_dt, \"densepose\", dpEvalMode=DensePoseEvalMode.GPSM)\n if imgIds is not None:\n coco_eval.params.imgIds = imgIds\n coco_eval.params.iouThrs = np.linspace(\n min_threshold, 0.95, int(np.round((0.95 - min_threshold) / 0.05)) + 1, endpoint=True\n )\n coco_eval.evaluate()\n coco_eval.accumulate()\n coco_eval.summarize()\n results = {metric: float(coco_eval.stats[idx] * 100) for idx, metric in enumerate(metrics)}\n return results\n\n\ndef _evaluate_predictions_on_coco_segm(coco_gt, coco_dt, metrics, min_threshold=0.5, imgIds=None):\n coco_eval = DensePoseCocoEval(coco_gt, coco_dt, \"segm\")\n if imgIds is not None:\n coco_eval.params.imgIds = imgIds\n coco_eval.params.iouThrs = np.linspace(\n min_threshold, 0.95, int(np.round((0.95 - min_threshold) / 0.05)) + 1, endpoint=True\n )\n coco_eval.evaluate()\n coco_eval.accumulate()\n coco_eval.summarize()\n results = {metric: float(coco_eval.stats[idx] * 100) for idx, metric in enumerate(metrics)}\n return results\n"],"string":"[\n \"# -*- coding: utf-8 -*-\\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\\n\\nimport contextlib\\nimport copy\\nimport io\\nimport itertools\\nimport logging\\nimport numpy as np\\nimport os\\nfrom collections import OrderedDict\\nimport pycocotools.mask as mask_utils\\nimport torch\\nfrom fvcore.common.file_io import PathManager\\nfrom pycocotools.coco import COCO\\n\\nfrom detectron2.data import MetadataCatalog\\nfrom detectron2.evaluation import DatasetEvaluator\\nfrom detectron2.structures import BoxMode\\nfrom detectron2.utils.comm import all_gather, is_main_process, synchronize\\nfrom detectron2.utils.logger import create_small_table\\n\\nfrom .converters import ToChartResultConverter, ToMaskConverter\\nfrom .densepose_coco_evaluation import DensePoseCocoEval, DensePoseEvalMode\\nfrom .structures import compress_quantized_densepose_chart_result, quantize_densepose_chart_result\\n\\n\\nclass DensePoseCOCOEvaluator(DatasetEvaluator):\\n def __init__(self, dataset_name, distributed, output_dir=None):\\n self._distributed = distributed\\n self._output_dir = output_dir\\n\\n self._cpu_device = torch.device(\\\"cpu\\\")\\n self._logger = logging.getLogger(__name__)\\n\\n self._metadata = MetadataCatalog.get(dataset_name)\\n self._min_threshold = 0.5\\n json_file = PathManager.get_local_path(self._metadata.json_file)\\n with contextlib.redirect_stdout(io.StringIO()):\\n self._coco_api = COCO(json_file)\\n\\n def reset(self):\\n self._predictions = []\\n\\n def process(self, inputs, outputs):\\n \\\"\\\"\\\"\\n Args:\\n inputs: the inputs to a COCO model (e.g., GeneralizedRCNN).\\n It is a list of dict. Each dict corresponds to an image and\\n contains keys like \\\"height\\\", \\\"width\\\", \\\"file_name\\\", \\\"image_id\\\".\\n outputs: the outputs of a COCO model. It is a list of dicts with key\\n \\\"instances\\\" that contains :class:`Instances`.\\n The :class:`Instances` object needs to have `densepose` field.\\n \\\"\\\"\\\"\\n for input, output in zip(inputs, outputs):\\n instances = output[\\\"instances\\\"].to(self._cpu_device)\\n if not instances.has(\\\"pred_densepose\\\"):\\n continue\\n json_results = prediction_to_json(instances, input[\\\"image_id\\\"])\\n self._predictions.extend(json_results)\\n\\n def evaluate(self, imgIds=None):\\n if self._distributed:\\n synchronize()\\n predictions = all_gather(self._predictions)\\n predictions = list(itertools.chain(*predictions))\\n if not is_main_process():\\n return\\n else:\\n predictions = self._predictions\\n\\n return copy.deepcopy(self._eval_predictions(predictions, imgIds))\\n\\n def _eval_predictions(self, predictions, imgIds=None):\\n \\\"\\\"\\\"\\n Evaluate predictions on densepose.\\n Return results with the metrics of the tasks.\\n \\\"\\\"\\\"\\n self._logger.info(\\\"Preparing results for COCO format ...\\\")\\n\\n if self._output_dir:\\n PathManager.mkdirs(self._output_dir)\\n file_path = os.path.join(self._output_dir, \\\"coco_densepose_predictions.pth\\\")\\n with PathManager.open(file_path, \\\"wb\\\") as f:\\n torch.save(predictions, f)\\n\\n self._logger.info(\\\"Evaluating predictions ...\\\")\\n res = OrderedDict()\\n results_gps, results_gpsm, results_segm = _evaluate_predictions_on_coco(\\n self._coco_api, predictions, min_threshold=self._min_threshold, imgIds=imgIds\\n )\\n res[\\\"densepose_gps\\\"] = results_gps\\n res[\\\"densepose_gpsm\\\"] = results_gpsm\\n res[\\\"densepose_segm\\\"] = results_segm\\n return res\\n\\n\\ndef prediction_to_json(instances, img_id):\\n \\\"\\\"\\\"\\n Args:\\n instances (Instances): the output of the model\\n img_id (str): the image id in COCO\\n\\n Returns:\\n list[dict]: the results in densepose evaluation format\\n \\\"\\\"\\\"\\n scores = instances.scores.tolist()\\n segmentations = ToMaskConverter.convert(\\n instances.pred_densepose, instances.pred_boxes, instances.image_size\\n )\\n raw_boxes_xywh = BoxMode.convert(\\n instances.pred_boxes.tensor.clone(), BoxMode.XYXY_ABS, BoxMode.XYWH_ABS\\n )\\n\\n results = []\\n for k in range(len(instances)):\\n densepose_results_quantized_compressed = compress_quantized_densepose_chart_result(\\n quantize_densepose_chart_result(\\n ToChartResultConverter.convert(instances.pred_densepose[k], instances.pred_boxes[k])\\n )\\n )\\n segmentation = segmentations.tensor[k]\\n segmentation_encoded = mask_utils.encode(\\n np.require(segmentation.numpy(), dtype=np.uint8, requirements=[\\\"F\\\"])\\n )\\n segmentation_encoded[\\\"counts\\\"] = segmentation_encoded[\\\"counts\\\"].decode(\\\"utf-8\\\")\\n result = {\\n \\\"image_id\\\": img_id,\\n \\\"category_id\\\": 1, # densepose only has one class\\n \\\"bbox\\\": raw_boxes_xywh[k].tolist(),\\n \\\"score\\\": scores[k],\\n \\\"densepose\\\": densepose_results_quantized_compressed,\\n \\\"segmentation\\\": segmentation_encoded,\\n }\\n results.append(result)\\n return results\\n\\n\\ndef _evaluate_predictions_on_coco(coco_gt, coco_results, min_threshold=0.5, imgIds=None):\\n logger = logging.getLogger(__name__)\\n\\n segm_metrics = _get_segmentation_metrics()\\n densepose_metrics = _get_densepose_metrics(min_threshold)\\n if len(coco_results) == 0: # cocoapi does not handle empty results very well\\n logger.warn(\\\"No predictions from the model! Set scores to -1\\\")\\n results_gps = {metric: -1 for metric in densepose_metrics}\\n results_gpsm = {metric: -1 for metric in densepose_metrics}\\n results_segm = {metric: -1 for metric in segm_metrics}\\n return results_gps, results_gpsm, results_segm\\n\\n coco_dt = coco_gt.loadRes(coco_results)\\n results_segm = _evaluate_predictions_on_coco_segm(\\n coco_gt, coco_dt, segm_metrics, min_threshold, imgIds\\n )\\n logger.info(\\\"Evaluation results for densepose segm: \\\\n\\\" + create_small_table(results_segm))\\n results_gps = _evaluate_predictions_on_coco_gps(\\n coco_gt, coco_dt, densepose_metrics, min_threshold, imgIds\\n )\\n logger.info(\\n \\\"Evaluation results for densepose, GPS metric: \\\\n\\\" + create_small_table(results_gps)\\n )\\n results_gpsm = _evaluate_predictions_on_coco_gpsm(\\n coco_gt, coco_dt, densepose_metrics, min_threshold, imgIds\\n )\\n logger.info(\\n \\\"Evaluation results for densepose, GPSm metric: \\\\n\\\" + create_small_table(results_gpsm)\\n )\\n return results_gps, results_gpsm, results_segm\\n\\n\\ndef _get_densepose_metrics(min_threshold=0.5):\\n metrics = [\\\"AP\\\"]\\n if min_threshold <= 0.201:\\n metrics += [\\\"AP20\\\"]\\n if min_threshold <= 0.301:\\n metrics += [\\\"AP30\\\"]\\n if min_threshold <= 0.401:\\n metrics += [\\\"AP40\\\"]\\n metrics.extend([\\\"AP50\\\", \\\"AP75\\\", \\\"APm\\\", \\\"APl\\\", \\\"AR\\\", \\\"AR50\\\", \\\"AR75\\\", \\\"ARm\\\", \\\"ARl\\\"])\\n return metrics\\n\\n\\ndef _get_segmentation_metrics():\\n return [\\n \\\"AP\\\",\\n \\\"AP50\\\",\\n \\\"AP75\\\",\\n \\\"APs\\\",\\n \\\"APm\\\",\\n \\\"APl\\\",\\n \\\"AR@1\\\",\\n \\\"AR@10\\\",\\n \\\"AR@100\\\",\\n \\\"ARs\\\",\\n \\\"ARm\\\",\\n \\\"ARl\\\",\\n ]\\n\\n\\ndef _evaluate_predictions_on_coco_gps(coco_gt, coco_dt, metrics, min_threshold=0.5, imgIds=None):\\n coco_eval = DensePoseCocoEval(coco_gt, coco_dt, \\\"densepose\\\", dpEvalMode=DensePoseEvalMode.GPS)\\n if imgIds is not None:\\n coco_eval.params.imgIds = imgIds\\n coco_eval.params.iouThrs = np.linspace(\\n min_threshold, 0.95, int(np.round((0.95 - min_threshold) / 0.05)) + 1, endpoint=True\\n )\\n coco_eval.evaluate()\\n coco_eval.accumulate()\\n coco_eval.summarize()\\n results = {metric: float(coco_eval.stats[idx] * 100) for idx, metric in enumerate(metrics)}\\n return results\\n\\n\\ndef _evaluate_predictions_on_coco_gpsm(coco_gt, coco_dt, metrics, min_threshold=0.5, imgIds=None):\\n coco_eval = DensePoseCocoEval(coco_gt, coco_dt, \\\"densepose\\\", dpEvalMode=DensePoseEvalMode.GPSM)\\n if imgIds is not None:\\n coco_eval.params.imgIds = imgIds\\n coco_eval.params.iouThrs = np.linspace(\\n min_threshold, 0.95, int(np.round((0.95 - min_threshold) / 0.05)) + 1, endpoint=True\\n )\\n coco_eval.evaluate()\\n coco_eval.accumulate()\\n coco_eval.summarize()\\n results = {metric: float(coco_eval.stats[idx] * 100) for idx, metric in enumerate(metrics)}\\n return results\\n\\n\\ndef _evaluate_predictions_on_coco_segm(coco_gt, coco_dt, metrics, min_threshold=0.5, imgIds=None):\\n coco_eval = DensePoseCocoEval(coco_gt, coco_dt, \\\"segm\\\")\\n if imgIds is not None:\\n coco_eval.params.imgIds = imgIds\\n coco_eval.params.iouThrs = np.linspace(\\n min_threshold, 0.95, int(np.round((0.95 - min_threshold) / 0.05)) + 1, endpoint=True\\n )\\n coco_eval.evaluate()\\n coco_eval.accumulate()\\n coco_eval.summarize()\\n results = {metric: float(coco_eval.stats[idx] * 100) for idx, metric in enumerate(metrics)}\\n return results\\n\"\n]"},"apis":{"kind":"list like","value":[["torch.device","numpy.round","torch.save"]],"string":"[\n [\n \"torch.device\",\n \"numpy.round\",\n \"torch.save\"\n ]\n]"},"possible_versions":{"kind":"list like","value":[{"matplotlib":[],"numpy":[],"pandas":[],"scipy":[],"tensorflow":[]}],"string":"[\n {\n \"matplotlib\": [],\n \"numpy\": [],\n \"pandas\": [],\n \"scipy\": [],\n \"tensorflow\": []\n }\n]"}}},{"rowIdx":72523,"cells":{"repo_name":{"kind":"string","value":"ioir123ju/mmskeleton"},"hexsha":{"kind":"list like","value":["bab5f973f00d68c5e166e450dd2ed95169a6549a"],"string":"[\n \"bab5f973f00d68c5e166e450dd2ed95169a6549a\"\n]"},"file_path":{"kind":"list like","value":["mmskeleton/processor/recognition_granary.py"],"string":"[\n \"mmskeleton/processor/recognition_granary.py\"\n]"},"code":{"kind":"list like","value":["#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\n@File : recognition_granary.py.py \n@Contact : JZ\n@License : (C)Copyright 2018-2019, Liugroup-NLPR-CASIA\n\n@Modify Time @Author @Version @Desciption\n------------ ------- -------- -----------\n2019/10/23 15:07 juzheng 1.0 None\n\"\"\"\n\nimport os\nimport cv2\nimport torch\nimport logging\nimport json\nimport numpy as np\nfrom mmskeleton.utils import call_obj, import_obj, load_checkpoint, cache_checkpoint\nfrom mmcv.runner import Runner\nfrom mmcv import Config, ProgressBar\nfrom mmcv.parallel import MMDataParallel\nimport mmcv\nfrom mmskeleton.apis.estimation import init_pose_estimator, inference_pose_estimator\nfrom multiprocessing import current_process, Process, Manager\n\n\n# process a batch of data\ndef batch_processor(model, datas, train_mode, loss):\n\n data, label = datas\n data = data.cuda()\n label = label.cuda()\n\n # forward\n output = model(data)\n losses = loss(output, label)\n\n # output\n log_vars = dict(loss=losses.item())\n if not train_mode:\n log_vars['top1'] = topk_accuracy(output, label)\n log_vars['top5'] = topk_accuracy(output, label, 5)\n\n outputs = dict(loss=losses, log_vars=log_vars, num_samples=len(data.data))\n return outputs\n\n\ndef topk_accuracy(score, label, k=1):\n rank = score.argsort()\n hit_top_k = [l in rank[i, -k:] for i, l in enumerate(label)]\n accuracy = sum(hit_top_k) * 1.0 / len(hit_top_k)\n return accuracy\n\n\ndef weights_init(model):\n classname = model.__class__.__name__\n if classname.find('Conv1d') != -1:\n model.weight.data.normal_(0.0, 0.02)\n if model.bias is not None:\n model.bias.data.fill_(0)\n elif classname.find('Conv2d') != -1:\n model.weight.data.normal_(0.0, 0.02)\n if model.bias is not None:\n model.bias.data.fill_(0)\n elif classname.find('BatchNorm') != -1:\n model.weight.data.normal_(1.0, 0.02)\n model.bias.data.fill_(0)\n\n\ndef render(image, pred, label, person_bbox, bbox_thre=0):\n if pred is None:\n return image\n\n mmcv.imshow_det_bboxes(image,\n person_bbox,\n np.zeros(len(person_bbox)).astype(int),\n class_names=['person'],\n score_thr=bbox_thre,\n show=False,\n wait_time=0)\n\n for person_pred in pred:\n for i, joint_pred in enumerate(person_pred):\n cv2.circle(image, (int(joint_pred[0]), int(joint_pred[1])), 2,\n [255, 0, 0], 2)\n cv2.putText(image, '{}'.format(i), (int(joint_pred[0]), int(joint_pred[1])),\n cv2.FONT_HERSHEY_COMPLEX, 0.5, [255, 255, 255])\n\n cv2.putText(image, '{}'.format(label), (int(person_pred[0][0]), int(person_pred[0][1] - 20)),\n cv2.FONT_HERSHEY_COMPLEX, 0.5, [255, 255, 255])\n image = draw_body_pose(image, person_pred)\n return np.uint8(image)\n\n\n# draw the body keypoint and lims\ndef draw_body_pose(image, person_pred):\n line_seq = [[0, 2], [2, 4], [0, 1], [1, 3], [0, 6], [6, 8], [8, 10], [0, 5],\n [5, 7], [7, 9], [0, 12], [12, 14], [14, 16], [0, 11], [11, 13], [13, 15]]\n\n colors = [[255, 0, 0], [255, 85, 0], [255, 170, 0], [255, 255, 0], [170, 255, 0], [85, 255, 0], [0, 255, 0],\n [0, 255, 85], [0, 255, 170], [0, 255, 255], [0, 170, 255], [0, 85, 255], [0, 0, 255], [85, 0, 255],\n [170, 0, 255], [255, 0, 255], [255, 0, 170], [255, 0, 85]]\n for i, line in enumerate(line_seq):\n first_index, second_index = line\n first_point = person_pred[first_index]\n second_point = person_pred[second_index]\n cv2.line(image, (int(first_point[0]), int(first_point[1])), (int(second_point[0]), int(second_point[1])),\n colors[i], 2)\n return image\n\n\ndef get_all_file(dir_path, file_list):\n for file in os.listdir(dir_path):\n # print(file)\n filepath = os.path.join(dir_path, file)\n # print(filepath)\n if os.path.isdir(filepath):\n get_all_file(filepath, file_list)\n else:\n file_list.append(filepath)\n return file_list\n\n\ndef build(inputs,\n detection_cfg,\n estimation_cfg,\n tracker_cfg,\n video_dir,\n gpus=1,\n video_max_length=10000,\n category_annotation=None):\n print('data build start')\n cache_checkpoint(detection_cfg.checkpoint_file)\n cache_checkpoint(estimation_cfg.checkpoint_file)\n\n if category_annotation is None:\n video_categories = dict()\n else:\n with open(category_annotation) as f:\n video_categories = json.load(f)['annotations']\n\n if tracker_cfg is not None:\n raise NotImplementedError\n\n pose_estimators = init_pose_estimator(\n detection_cfg, estimation_cfg, device=0)\n\n video_file_list = []\n get_all_file(video_dir, video_file_list)\n\n prog_bar = ProgressBar(len(video_file_list))\n for video_path in video_file_list:\n video_file = os.path.basename(video_path)\n reader = mmcv.VideoReader(video_path)\n video_frames = reader[:video_max_length]\n\n annotations = []\n num_keypoints = -1\n for i, image in enumerate(video_frames):\n res = inference_pose_estimator(pose_estimators, image)\n res['frame_index'] = i\n if not res['has_return']:\n continue\n num_person = len(res['joint_preds'])\n assert len(res['person_bbox']) == num_person\n\n for j in range(num_person):\n keypoints = [[p[0], p[1], round(s[0], 2)] for p, s in zip(\n res['joint_preds'][j].round().astype(int).tolist(), res[\n 'joint_scores'][j].tolist())]\n num_keypoints = len(keypoints)\n person_info = dict(\n person_bbox=res['person_bbox'][j].round().astype(int).tolist(),\n frame_index=res['frame_index'],\n id=j,\n person_id=None,\n keypoints=keypoints)\n annotations.append(person_info)\n annotations = sorted(annotations, key=lambda x: x['frame_index'])\n category_id = video_categories[video_file][\n 'category_id'] if video_file in video_categories else -1\n info = dict(\n video_name=video_file,\n resolution=reader.resolution,\n num_frame=len(video_frames),\n num_keypoints=num_keypoints,\n keypoint_channels=['x', 'y', 'score'],\n version='1.0')\n video_info = dict(\n info=info, category_id=category_id, annotations=annotations)\n inputs.put(video_info)\n prog_bar.update()\n\n\ndef data_parse(data, pipeline, num_track=1):\n info = data['info']\n annotations = data['annotations']\n num_frame = info['num_frame']\n num_keypoints = info['num_keypoints']\n channel = info['keypoint_channels']\n num_channel = len(channel)\n\n # get data\n data['data'] = np.zeros(\n (num_channel, num_keypoints, num_frame, num_track),\n dtype=np.float32)\n\n for a in annotations:\n person_id = a['id'] if a['person_id'] is None else a['person_id']\n frame_index = a['frame_index']\n if person_id < num_track and frame_index < num_frame:\n data['data'][:, :, frame_index, person_id] = np.array(\n a['keypoints']).transpose()\n # 数据预处理\n for stage_args in pipeline:\n data = call_obj(data=data, **stage_args)\n return data\n\n\ndef detect(inputs, results, model_cfg, dataset_cfg, checkpoint, video_dir,\n batch_size=64, gpus=1, workers=4):\n print('detect start')\n # put model on gpus\n if isinstance(model_cfg, list):\n model = [call_obj(**c) for c in model_cfg]\n model = torch.nn.Sequential(*model)\n else:\n model = call_obj(**model_cfg)\n load_checkpoint(model, checkpoint, map_location='cpu')\n model = MMDataParallel(model, device_ids=range(gpus)).cuda()\n model.eval()\n\n results = []\n labels = []\n video_file_list = os.listdir(video_dir)\n prog_bar = ProgressBar(len(video_file_list))\n for video_file in video_file_list:\n data = inputs.get()\n data_loader = data_parse(data, dataset_cfg.pipeline, dataset_cfg.data_source.num_track)\n data, label = data_loader\n with torch.no_grad():\n data = torch.from_numpy(data)\n # 增加一维,表示batch_size\n data = data.unsqueeze(0)\n data = data.float().to(\"cuda:0\").detach()\n output = model(data).data.cpu().numpy()\n results.append(output)\n labels.append(torch.tensor([label]))\n for i in range(len(data)):\n prog_bar.update()\n print('--------', results, labels, '--------------')\n results = np.concatenate(results)\n labels = np.concatenate(labels)\n\n print('Top 1: {:.2f}%'.format(100 * topk_accuracy(results, labels, 1)))\n print('Top 5: {:.2f}%'.format(100 * topk_accuracy(results, labels, 5)))\n\n\ndef realtime_detect(detection_cfg, estimation_cfg, model_cfg, dataset_cfg, tracker_cfg, video_dir,\n category_annotation, checkpoint, batch_size=64, gpus=1, workers=4):\n \"\"\"\n 初始化\n \"\"\"\n # 初始化模型\n pose_estimators = init_pose_estimator(\n detection_cfg, estimation_cfg, device=0)\n if isinstance(model_cfg, list):\n model = [call_obj(**c) for c in model_cfg]\n model = torch.nn.Sequential(*model)\n else:\n model = call_obj(**model_cfg)\n load_checkpoint(model, checkpoint, map_location='cpu')\n model = MMDataParallel(model, device_ids=range(gpus)).cuda()\n model.eval()\n\n # 获取图像\n video_file = 'train/clean/clean10.avi'\n reader = mmcv.VideoReader(os.path.join(video_dir, video_file))\n video_frames = reader[:10000]\n\n if category_annotation is None:\n video_categories = dict()\n else:\n with open(category_annotation) as f:\n json_file = json.load(f)\n video_categories = json_file['annotations']\n action_class = json_file['categories']\n annotations = []\n num_keypoints = -1\n for i, image in enumerate(video_frames):\n res = inference_pose_estimator(pose_estimators, image)\n res['frame_index'] = i\n if not res['has_return']:\n continue\n num_person = len(res['joint_preds'])\n assert len(res['person_bbox']) == num_person\n\n for j in range(num_person):\n keypoints = [[p[0], p[1], round(s[0], 2)] for p, s in zip(\n res['joint_preds'][j].round().astype(int).tolist(), res[\n 'joint_scores'][j].tolist())]\n num_keypoints = len(keypoints)\n person_info = dict(\n person_bbox=res['person_bbox'][j].round().astype(int).tolist(),\n frame_index=res['frame_index'],\n id=j,\n person_id=None,\n keypoints=keypoints)\n annotations.append(person_info)\n category_id = video_categories[video_file][\n 'category_id'] if video_file in video_categories else -1\n info = dict(\n video_name=video_file,\n resolution=reader.resolution,\n num_frame=len(video_frames),\n num_keypoints=num_keypoints,\n keypoint_channels=['x', 'y', 'score'],\n version='1.0')\n video_info = dict(info=info, category_id=category_id, annotations=annotations)\n\n data_loader = data_parse(video_info, dataset_cfg.pipeline, dataset_cfg.data_source.num_track)\n data, label = data_loader\n with torch.no_grad():\n data = torch.from_numpy(data)\n # 增加一维,表示batch_size\n data = data.unsqueeze(0)\n data = data.float().to(\"cuda:0\").detach()\n output = model(data).data.cpu().numpy()\n top1 = output.argmax()\n if output[:, top1] > 3:\n label = action_class[top1]\n else:\n label = 'unknow'\n print(\"reslt:\", output)\n\n res['render_image'] = render(image, res['joint_preds'],\n label,\n res['person_bbox'],\n detection_cfg.bbox_thre)\n cv2.imshow('image', image)\n cv2.waitKey(10)\n\n\ndef recognition(detection_cfg, estimation_cfg, model_cfg, dataset_cfg, tracker_cfg, video_dir,\n category_annotation, checkpoint, batch_size=64, gpus=1, workers=4):\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n inputs = Manager().Queue(10000)\n results = Manager().Queue(10000)\n procs = []\n p1 = Process(\n target=build,\n args=(inputs, detection_cfg, estimation_cfg, tracker_cfg, video_dir,\n gpus, 10000, category_annotation))\n p1.start()\n procs.append(p1)\n p2 = Process(\n target=detect,\n args=(inputs, results, model_cfg, dataset_cfg, checkpoint, video_dir,\n batch_size, gpus, workers))\n p2.start()\n procs.append(p2)\n for p in procs:\n p.join()\n\n"],"string":"[\n \"#!/usr/bin/env python\\n# -*- encoding: utf-8 -*-\\n\\\"\\\"\\\"\\n@File : recognition_granary.py.py \\n@Contact : JZ\\n@License : (C)Copyright 2018-2019, Liugroup-NLPR-CASIA\\n\\n@Modify Time @Author @Version @Desciption\\n------------ ------- -------- -----------\\n2019/10/23 15:07 juzheng 1.0 None\\n\\\"\\\"\\\"\\n\\nimport os\\nimport cv2\\nimport torch\\nimport logging\\nimport json\\nimport numpy as np\\nfrom mmskeleton.utils import call_obj, import_obj, load_checkpoint, cache_checkpoint\\nfrom mmcv.runner import Runner\\nfrom mmcv import Config, ProgressBar\\nfrom mmcv.parallel import MMDataParallel\\nimport mmcv\\nfrom mmskeleton.apis.estimation import init_pose_estimator, inference_pose_estimator\\nfrom multiprocessing import current_process, Process, Manager\\n\\n\\n# process a batch of data\\ndef batch_processor(model, datas, train_mode, loss):\\n\\n data, label = datas\\n data = data.cuda()\\n label = label.cuda()\\n\\n # forward\\n output = model(data)\\n losses = loss(output, label)\\n\\n # output\\n log_vars = dict(loss=losses.item())\\n if not train_mode:\\n log_vars['top1'] = topk_accuracy(output, label)\\n log_vars['top5'] = topk_accuracy(output, label, 5)\\n\\n outputs = dict(loss=losses, log_vars=log_vars, num_samples=len(data.data))\\n return outputs\\n\\n\\ndef topk_accuracy(score, label, k=1):\\n rank = score.argsort()\\n hit_top_k = [l in rank[i, -k:] for i, l in enumerate(label)]\\n accuracy = sum(hit_top_k) * 1.0 / len(hit_top_k)\\n return accuracy\\n\\n\\ndef weights_init(model):\\n classname = model.__class__.__name__\\n if classname.find('Conv1d') != -1:\\n model.weight.data.normal_(0.0, 0.02)\\n if model.bias is not None:\\n model.bias.data.fill_(0)\\n elif classname.find('Conv2d') != -1:\\n model.weight.data.normal_(0.0, 0.02)\\n if model.bias is not None:\\n model.bias.data.fill_(0)\\n elif classname.find('BatchNorm') != -1:\\n model.weight.data.normal_(1.0, 0.02)\\n model.bias.data.fill_(0)\\n\\n\\ndef render(image, pred, label, person_bbox, bbox_thre=0):\\n if pred is None:\\n return image\\n\\n mmcv.imshow_det_bboxes(image,\\n person_bbox,\\n np.zeros(len(person_bbox)).astype(int),\\n class_names=['person'],\\n score_thr=bbox_thre,\\n show=False,\\n wait_time=0)\\n\\n for person_pred in pred:\\n for i, joint_pred in enumerate(person_pred):\\n cv2.circle(image, (int(joint_pred[0]), int(joint_pred[1])), 2,\\n [255, 0, 0], 2)\\n cv2.putText(image, '{}'.format(i), (int(joint_pred[0]), int(joint_pred[1])),\\n cv2.FONT_HERSHEY_COMPLEX, 0.5, [255, 255, 255])\\n\\n cv2.putText(image, '{}'.format(label), (int(person_pred[0][0]), int(person_pred[0][1] - 20)),\\n cv2.FONT_HERSHEY_COMPLEX, 0.5, [255, 255, 255])\\n image = draw_body_pose(image, person_pred)\\n return np.uint8(image)\\n\\n\\n# draw the body keypoint and lims\\ndef draw_body_pose(image, person_pred):\\n line_seq = [[0, 2], [2, 4], [0, 1], [1, 3], [0, 6], [6, 8], [8, 10], [0, 5],\\n [5, 7], [7, 9], [0, 12], [12, 14], [14, 16], [0, 11], [11, 13], [13, 15]]\\n\\n colors = [[255, 0, 0], [255, 85, 0], [255, 170, 0], [255, 255, 0], [170, 255, 0], [85, 255, 0], [0, 255, 0],\\n [0, 255, 85], [0, 255, 170], [0, 255, 255], [0, 170, 255], [0, 85, 255], [0, 0, 255], [85, 0, 255],\\n [170, 0, 255], [255, 0, 255], [255, 0, 170], [255, 0, 85]]\\n for i, line in enumerate(line_seq):\\n first_index, second_index = line\\n first_point = person_pred[first_index]\\n second_point = person_pred[second_index]\\n cv2.line(image, (int(first_point[0]), int(first_point[1])), (int(second_point[0]), int(second_point[1])),\\n colors[i], 2)\\n return image\\n\\n\\ndef get_all_file(dir_path, file_list):\\n for file in os.listdir(dir_path):\\n # print(file)\\n filepath = os.path.join(dir_path, file)\\n # print(filepath)\\n if os.path.isdir(filepath):\\n get_all_file(filepath, file_list)\\n else:\\n file_list.append(filepath)\\n return file_list\\n\\n\\ndef build(inputs,\\n detection_cfg,\\n estimation_cfg,\\n tracker_cfg,\\n video_dir,\\n gpus=1,\\n video_max_length=10000,\\n category_annotation=None):\\n print('data build start')\\n cache_checkpoint(detection_cfg.checkpoint_file)\\n cache_checkpoint(estimation_cfg.checkpoint_file)\\n\\n if category_annotation is None:\\n video_categories = dict()\\n else:\\n with open(category_annotation) as f:\\n video_categories = json.load(f)['annotations']\\n\\n if tracker_cfg is not None:\\n raise NotImplementedError\\n\\n pose_estimators = init_pose_estimator(\\n detection_cfg, estimation_cfg, device=0)\\n\\n video_file_list = []\\n get_all_file(video_dir, video_file_list)\\n\\n prog_bar = ProgressBar(len(video_file_list))\\n for video_path in video_file_list:\\n video_file = os.path.basename(video_path)\\n reader = mmcv.VideoReader(video_path)\\n video_frames = reader[:video_max_length]\\n\\n annotations = []\\n num_keypoints = -1\\n for i, image in enumerate(video_frames):\\n res = inference_pose_estimator(pose_estimators, image)\\n res['frame_index'] = i\\n if not res['has_return']:\\n continue\\n num_person = len(res['joint_preds'])\\n assert len(res['person_bbox']) == num_person\\n\\n for j in range(num_person):\\n keypoints = [[p[0], p[1], round(s[0], 2)] for p, s in zip(\\n res['joint_preds'][j].round().astype(int).tolist(), res[\\n 'joint_scores'][j].tolist())]\\n num_keypoints = len(keypoints)\\n person_info = dict(\\n person_bbox=res['person_bbox'][j].round().astype(int).tolist(),\\n frame_index=res['frame_index'],\\n id=j,\\n person_id=None,\\n keypoints=keypoints)\\n annotations.append(person_info)\\n annotations = sorted(annotations, key=lambda x: x['frame_index'])\\n category_id = video_categories[video_file][\\n 'category_id'] if video_file in video_categories else -1\\n info = dict(\\n video_name=video_file,\\n resolution=reader.resolution,\\n num_frame=len(video_frames),\\n num_keypoints=num_keypoints,\\n keypoint_channels=['x', 'y', 'score'],\\n version='1.0')\\n video_info = dict(\\n info=info, category_id=category_id, annotations=annotations)\\n inputs.put(video_info)\\n prog_bar.update()\\n\\n\\ndef data_parse(data, pipeline, num_track=1):\\n info = data['info']\\n annotations = data['annotations']\\n num_frame = info['num_frame']\\n num_keypoints = info['num_keypoints']\\n channel = info['keypoint_channels']\\n num_channel = len(channel)\\n\\n # get data\\n data['data'] = np.zeros(\\n (num_channel, num_keypoints, num_frame, num_track),\\n dtype=np.float32)\\n\\n for a in annotations:\\n person_id = a['id'] if a['person_id'] is None else a['person_id']\\n frame_index = a['frame_index']\\n if person_id < num_track and frame_index < num_frame:\\n data['data'][:, :, frame_index, person_id] = np.array(\\n a['keypoints']).transpose()\\n # 数据预处理\\n for stage_args in pipeline:\\n data = call_obj(data=data, **stage_args)\\n return data\\n\\n\\ndef detect(inputs, results, model_cfg, dataset_cfg, checkpoint, video_dir,\\n batch_size=64, gpus=1, workers=4):\\n print('detect start')\\n # put model on gpus\\n if isinstance(model_cfg, list):\\n model = [call_obj(**c) for c in model_cfg]\\n model = torch.nn.Sequential(*model)\\n else:\\n model = call_obj(**model_cfg)\\n load_checkpoint(model, checkpoint, map_location='cpu')\\n model = MMDataParallel(model, device_ids=range(gpus)).cuda()\\n model.eval()\\n\\n results = []\\n labels = []\\n video_file_list = os.listdir(video_dir)\\n prog_bar = ProgressBar(len(video_file_list))\\n for video_file in video_file_list:\\n data = inputs.get()\\n data_loader = data_parse(data, dataset_cfg.pipeline, dataset_cfg.data_source.num_track)\\n data, label = data_loader\\n with torch.no_grad():\\n data = torch.from_numpy(data)\\n # 增加一维,表示batch_size\\n data = data.unsqueeze(0)\\n data = data.float().to(\\\"cuda:0\\\").detach()\\n output = model(data).data.cpu().numpy()\\n results.append(output)\\n labels.append(torch.tensor([label]))\\n for i in range(len(data)):\\n prog_bar.update()\\n print('--------', results, labels, '--------------')\\n results = np.concatenate(results)\\n labels = np.concatenate(labels)\\n\\n print('Top 1: {:.2f}%'.format(100 * topk_accuracy(results, labels, 1)))\\n print('Top 5: {:.2f}%'.format(100 * topk_accuracy(results, labels, 5)))\\n\\n\\ndef realtime_detect(detection_cfg, estimation_cfg, model_cfg, dataset_cfg, tracker_cfg, video_dir,\\n category_annotation, checkpoint, batch_size=64, gpus=1, workers=4):\\n \\\"\\\"\\\"\\n 初始化\\n \\\"\\\"\\\"\\n # 初始化模型\\n pose_estimators = init_pose_estimator(\\n detection_cfg, estimation_cfg, device=0)\\n if isinstance(model_cfg, list):\\n model = [call_obj(**c) for c in model_cfg]\\n model = torch.nn.Sequential(*model)\\n else:\\n model = call_obj(**model_cfg)\\n load_checkpoint(model, checkpoint, map_location='cpu')\\n model = MMDataParallel(model, device_ids=range(gpus)).cuda()\\n model.eval()\\n\\n # 获取图像\\n video_file = 'train/clean/clean10.avi'\\n reader = mmcv.VideoReader(os.path.join(video_dir, video_file))\\n video_frames = reader[:10000]\\n\\n if category_annotation is None:\\n video_categories = dict()\\n else:\\n with open(category_annotation) as f:\\n json_file = json.load(f)\\n video_categories = json_file['annotations']\\n action_class = json_file['categories']\\n annotations = []\\n num_keypoints = -1\\n for i, image in enumerate(video_frames):\\n res = inference_pose_estimator(pose_estimators, image)\\n res['frame_index'] = i\\n if not res['has_return']:\\n continue\\n num_person = len(res['joint_preds'])\\n assert len(res['person_bbox']) == num_person\\n\\n for j in range(num_person):\\n keypoints = [[p[0], p[1], round(s[0], 2)] for p, s in zip(\\n res['joint_preds'][j].round().astype(int).tolist(), res[\\n 'joint_scores'][j].tolist())]\\n num_keypoints = len(keypoints)\\n person_info = dict(\\n person_bbox=res['person_bbox'][j].round().astype(int).tolist(),\\n frame_index=res['frame_index'],\\n id=j,\\n person_id=None,\\n keypoints=keypoints)\\n annotations.append(person_info)\\n category_id = video_categories[video_file][\\n 'category_id'] if video_file in video_categories else -1\\n info = dict(\\n video_name=video_file,\\n resolution=reader.resolution,\\n num_frame=len(video_frames),\\n num_keypoints=num_keypoints,\\n keypoint_channels=['x', 'y', 'score'],\\n version='1.0')\\n video_info = dict(info=info, category_id=category_id, annotations=annotations)\\n\\n data_loader = data_parse(video_info, dataset_cfg.pipeline, dataset_cfg.data_source.num_track)\\n data, label = data_loader\\n with torch.no_grad():\\n data = torch.from_numpy(data)\\n # 增加一维,表示batch_size\\n data = data.unsqueeze(0)\\n data = data.float().to(\\\"cuda:0\\\").detach()\\n output = model(data).data.cpu().numpy()\\n top1 = output.argmax()\\n if output[:, top1] > 3:\\n label = action_class[top1]\\n else:\\n label = 'unknow'\\n print(\\\"reslt:\\\", output)\\n\\n res['render_image'] = render(image, res['joint_preds'],\\n label,\\n res['person_bbox'],\\n detection_cfg.bbox_thre)\\n cv2.imshow('image', image)\\n cv2.waitKey(10)\\n\\n\\ndef recognition(detection_cfg, estimation_cfg, model_cfg, dataset_cfg, tracker_cfg, video_dir,\\n category_annotation, checkpoint, batch_size=64, gpus=1, workers=4):\\n os.environ[\\\"CUDA_VISIBLE_DEVICES\\\"] = \\\"0\\\"\\n inputs = Manager().Queue(10000)\\n results = Manager().Queue(10000)\\n procs = []\\n p1 = Process(\\n target=build,\\n args=(inputs, detection_cfg, estimation_cfg, tracker_cfg, video_dir,\\n gpus, 10000, category_annotation))\\n p1.start()\\n procs.append(p1)\\n p2 = Process(\\n target=detect,\\n args=(inputs, results, model_cfg, dataset_cfg, checkpoint, video_dir,\\n batch_size, gpus, workers))\\n p2.start()\\n procs.append(p2)\\n for p in procs:\\n p.join()\\n\\n\"\n]"},"apis":{"kind":"list like","value":[["torch.nn.Sequential","numpy.uint8","torch.from_numpy","torch.tensor","numpy.concatenate","torch.no_grad","numpy.array","numpy.zeros"]],"string":"[\n [\n \"torch.nn.Sequential\",\n \"numpy.uint8\",\n \"torch.from_numpy\",\n \"torch.tensor\",\n \"numpy.concatenate\",\n \"torch.no_grad\",\n \"numpy.array\",\n \"numpy.zeros\"\n ]\n]"},"possible_versions":{"kind":"list like","value":[{"matplotlib":[],"numpy":[],"pandas":[],"scipy":[],"tensorflow":[]}],"string":"[\n {\n \"matplotlib\": [],\n \"numpy\": [],\n \"pandas\": [],\n \"scipy\": [],\n \"tensorflow\": []\n }\n]"}}},{"rowIdx":72524,"cells":{"repo_name":{"kind":"string","value":"juliadeneva/NICERsoft"},"hexsha":{"kind":"list like","value":["13681678ec57a81605601714896876cb870475ff"],"string":"[\n \"13681678ec57a81605601714896876cb870475ff\"\n]"},"file_path":{"kind":"list like","value":["scripts/photon_toa.py"],"string":"[\n \"scripts/photon_toa.py\"\n]"},"code":{"kind":"list like","value":["#!/usr/bin/env python\n# Program: photon_toa.py\n# Authors: Paul S. Ray \n# Matthew Kerr \n# Julia Deneva \n# Description:\n# Reads a FITS file of photon event times (from NICER or another X-ray mission)\n# and generates TOAs from the unbined times using a pulsar timing model\n# and an analytic template. The TOAs can be output them in Tempo2 format.\nfrom __future__ import division, print_function\n\n# from future import standard_library\n# standard_library.install_aliases()\nfrom builtins import str\nfrom builtins import zip\nfrom builtins import range\nimport os, sys\nimport argparse\nimport numpy as np\nfrom astropy import log\nimport astropy.units as u\nimport astropy.io.fits as pyfits\nimport pint.residuals\nfrom pint.event_toas import load_NICER_TOAs\nfrom pint.event_toas import load_RXTE_TOAs\nfrom pint.event_toas import load_NuSTAR_TOAs\nfrom pint.event_toas import load_XMM_TOAs\nfrom pint.plot_utils import phaseogram_binned\nfrom pint.observatory.satellite_obs import get_satellite_observatory\nimport pint.toa, pint.models\nfrom pint.eventstats import hmw, hm, h2sig\nfrom astropy.time import Time, TimeDelta\nfrom pint.templates.lctemplate import LCTemplate, prim_io\nfrom pint.templates import lcfitters\nfrom copy import deepcopy\nimport pickle\nimport io\nfrom collections import deque\nimport astropy.constants as const\nfrom pint.observatory import get_observatory\nfrom pint.observatory.special_locations import T2SpacecraftObs\n\nlog.setLevel(\"INFO\")\n\n\ndef local_load_NICER_TOAs(eventname):\n \"\"\" Local override to add MET field to each TOA object.\"\"\"\n # TODO -- add this to PINT method ?\n tl = load_NICER_TOAs(eventname)\n f = pyfits.open(eventname)\n mets = f[\"events\"].data.field(\"time\")\n f.close()\n for t, met in zip(tl, mets):\n t.met = met\n # The returned tl has topocentric TT MJD photon times; TIMESYS=TT, TIMEREF=LOCAL in the .evt file\n return tl\n\n\ndef estimate_toa(mjds, phases, ph_times, topo, obs, modelin):\n \"\"\" Return a pint TOA object for the provided times and phases.\n\n Longer description here.\n\n Parameters\n ----------\n mjds : array of floats\n The MJD times of each photon. These are for sorting the TOAs into\n groups and making plots, not for precision work! The timescale\n may be different for different datasets (see pint.toa.get_mjds)\n phases : array\n Array of model-computed phase values for each photon. Should be floats\n between 0.0 and 1.0\n ph_times : array of astropy.Time objects\n Array of photon times, as recorded at Observatory obs\n If obs==\"Barycenter\" then these should be BAT times in the TDB timescale\n with the Roemer delays removed (the usual sense of \"barycentered\" times)\n topo : bool\n If True, then TOA will be computed for the arrival time at the Spacecraft\n and the TOA line will have the spacecraft ECI position included.\n If False, then the TOA will be a Barycentric Arrival Time (BAT)\n obs : pint.observatory.Observatory\n The observatory corresponding to the photon event times.\n This is NOT necessarily the observatory for the output TOAs,\n which can be the Barycenter.\n\"\"\"\n\n # Given some subset of the event times, phases, and weights, compute\n # the TOA based on a reference event near the middle of the span.\n # Build the TOA as a PINT TOA() object\n lcf = lcfitters.LCFitter(deepcopy(template), phases)\n # fitbg does not work! Disabling.\n # if args.fitbg:\n # for i in xrange(2):\n # lcf.fit_position(unbinned=False)\n # lcf.fit_background(unbinned=False)\n dphi, dphierr = lcf.fit_position(unbinned=args.unbinned, track=args.track)\n log.info(\"Measured phase shift dphi={0}, dphierr={1}\".format(dphi, dphierr))\n\n # find time of event closest to center of observation and turn it into a TOA\n argmid = np.searchsorted(mjds, 0.5 * (mjds.min() + mjds.max()))\n tmid = ph_times[argmid]\n # So, tmid should be a time at the observatory if topo, otherwise\n # it should be a BAT (in TDB timescale with delays applied)\n # Here, convert tmid if not topo and data not barycentered\n\n if topo:\n tplus = tmid + TimeDelta(1 * u.s, scale=tmid.scale)\n toamid = pint.toa.TOA(tmid, obs=obs.name)\n toaplus = pint.toa.TOA(tplus, obs=obs.name)\n else:\n # If input data were not barycentered but we want barycentric TOAs\n # then make TMID into a BAT\n if tmid.scale not in (\"tdb\", \"tcb\"):\n log.debug(\n \"Making TOA, tmid {}, tmid.scale {}, obs {}\".format(\n tmid, tmid.scale, obs.name\n )\n )\n toas = pint.toa.get_TOAs_list(\n [pint.toa.TOA(tmid, obs=obs.name)],\n include_gps=args.use_gps,\n include_bipm=args.use_bipm,\n ephem=args.ephem,\n planets=planets,\n )\n tmid = Time(modelin.get_barycentric_toas(toas), format=\"mjd\", scale=\"tdb\")[\n 0\n ]\n log.debug(\"New tmid {}, tmid.scale {}\".format(tmid, tmid.scale))\n\n tplus = tmid + TimeDelta(1 * u.s, scale=tmid.scale)\n toamid = pint.toa.TOA(tmid, obs=\"Barycenter\")\n toaplus = pint.toa.TOA(tplus, obs=\"Barycenter\")\n\n toas = pint.toa.get_TOAs_list(\n [toamid, toaplus],\n include_gps=args.use_gps,\n include_bipm=args.use_bipm,\n ephem=args.ephem,\n planets=planets,\n )\n\n phsi, phsf = modelin.phase(toas, abs_phase=True)\n if topo:\n sc = \"tt\"\n else:\n sc = \"tdb\"\n # Compute frequency = d(phase)/dt\n f = (phsi[1] - phsi[0]) + (phsf[1] - phsf[0])\n f._unit = u.Hz\n\n # First delta is to get time of phase 0.0 of initial model\n # Second term corrects for the measured phase offset to align with template\n tfinal = (\n tmid + TimeDelta(-phsf[0].value / f, scale=sc) + TimeDelta(dphi / f, scale=sc)\n )\n\n # Use PINT's TOA writer to save the TOA\n nsrc = lcf.template.norm() * len(lcf.phases)\n nbkg = (1 - lcf.template.norm()) * len(lcf.phases)\n\n if args.topo: # tfinal is a topocentric TT MJD\n telposvel = obs.posvel_gcrs(tfinal)\n x = telposvel.pos[0].to(u.km)\n y = telposvel.pos[1].to(u.km)\n z = telposvel.pos[2].to(u.km)\n vx = telposvel.vel[0].to(u.km / u.s)\n vy = telposvel.vel[1].to(u.km / u.s)\n vz = telposvel.vel[2].to(u.km / u.s)\n\n toafinal = pint.toa.TOA(\n tfinal.utc,\n obs=\"spacecraft\",\n nsrc=\"%.2f\" % nsrc,\n nbkg=\"%.2f\" % nbkg,\n exposure=\"%.2f\" % exposure,\n dphi=\"%.5f\" % dphi,\n mjdTT=\"%.8f\" % tfinal.tt.mjd,\n telx=\"%.8f\" % x.value,\n tely=\"%.8f\" % y.value,\n telz=\"%.8f\" % z.value,\n vx=\"%.8f\" % vx.value,\n vy=\"%.8f\" % vy.value,\n vz=\"%.8f\" % vz.value,\n )\n\n else:\n # Make a TOA for the Barycenter, which is the default obs\n toafinal = pint.toa.TOA(\n tfinal,\n obs=\"Barycenter\",\n nsrc=\"%.2f\" % nsrc,\n nbkg=\"%.2f\" % nbkg,\n exposure=\"%.2f\" % exposure,\n dphi=\"%.5f\" % dphi,\n )\n toasfinal = pint.toa.get_TOAs_list(\n [toafinal],\n include_gps=args.use_gps,\n include_bipm=args.use_bipm,\n ephem=args.ephem,\n planets=planets,\n )\n log.debug(\n \"Modelin final phase {}\".format(modelin.phase(toasfinal, abs_phase=True))\n )\n log.info(\n \"Src rate = {0} c/s, Bkg rate = {1} c/s\".format(\n nsrc / exposure, nbkg / exposure\n )\n )\n return toafinal, dphierr / f.value * 1.0e6\n\n\ndesc = \"\"\"Generate TOAs from photon event data.\"\"\"\n\nparser = argparse.ArgumentParser(description=desc)\nparser.add_argument(\"eventname\", help=\"FITS file to read events from\")\nparser.add_argument(\"templatename\", help=\"Name of file to read template from\")\nparser.add_argument(\"parname\", help=\"Timing model file name\")\nparser.add_argument(\"--orbfile\", help=\"Name of orbit file\", default=None)\nparser.add_argument(\n \"--ephem\", help=\"Planetary ephemeris to use (default=DE421)\", default=\"DE421\"\n)\nparser.add_argument(\n \"--plot\", help=\"Show phaseogram plot.\", action=\"store_true\", default=False\n)\nparser.add_argument(\n \"--plotfile\", help=\"Output figure file name (default=None)\", default=None\n)\n# parser.add_argument(\"--fitbg\",help=\"Fit an overall background level (e.g. for changing particle background level (default=False).\",action='store_true',default=False)\nparser.add_argument(\n \"--unbinned\",\n help=\"Fit position with unbinned likelihood. Don't use for large data sets. (default=False)\",\n action=\"store_true\",\n default=False,\n)\n# parser.add_argument(\"--fix\",help=\"Adjust times to fix 1.0 second offset in NICER data (default=False)\", action='store_true',default=False)\nparser.add_argument(\n \"--tint\",\n help=\"Integrate for tint seconds for each TOA, or until the total integration exceeds maxint. The algorithm is based on GTI, so the integration will slightly exceed tint (default None; see maxint.)\",\n default=None,\n)\nparser.add_argument(\n \"--maxint\",\n help=\"Maximum time interval to accumulate exposure for a single TOA (default=2*86400s)\",\n type=float,\n default=2 * 86400.0,\n)\nparser.add_argument(\n \"--minexp\",\n help=\"Minimum exposure (s) for which to include a TOA (default=0.0).\",\n default=0.0,\n type=float,\n)\nparser.add_argument(\n \"--track\",\n help=\"Assume model is close to good and only search near 0 phase (to avoid getting TOAs off by 0.5 in double peaked pulsars)\",\n action=\"store_true\",\n default=False,\n)\nparser.add_argument(\n \"--dice\",\n help=\"Dice up long GTIs into chunks of length <= tint\",\n action=\"store_true\",\n default=False,\n)\nparser.add_argument(\n \"--use_bipm\", help=\"Use BIPM clock corrections\", action=\"store_true\", default=False\n)\nparser.add_argument(\n \"--use_gps\",\n help=\"Use GPS to UTC clock corrections\",\n action=\"store_true\",\n default=False,\n)\nparser.add_argument(\n \"--topo\",\n help=\"Make topocentric TOAs; include the spacecraft ECI position on the TOA line\",\n action=\"store_true\",\n default=False,\n)\nparser.add_argument(\n \"--outfile\", help=\"Name of file to save TOAs to (default is STDOUT)\", default=None\n)\nparser.add_argument(\"--append\", help=\"Append TOAs to output file instead of overwriting\", default=False, action=\"store_true\")\n\n## Parse arguments\nargs = parser.parse_args()\n\n# Load PINT model objects\nmodelin = pint.models.get_model(args.parname)\nlog.info(str(modelin))\n\n# check for consistency between ephemeris and options\nif modelin.PLANET_SHAPIRO.quantity:\n planets = True\nelse:\n planets = False\n\n# Load Template objects\ntry:\n template = pickle.load(file(args.templatename))\nexcept:\n primitives, norms = prim_io(args.templatename)\n template = LCTemplate(primitives, norms)\n# print(template)\n\n# Load photons as PINT toas, and weights, if specified\n# Here I might loop over the files specified\n# Read event file header to figure out what instrument is is from\nhdr = pyfits.getheader(args.eventname, ext=1)\nlog.info(\n \"Event file TELESCOPE = {0}, INSTRUMENT = {1}\".format(\n hdr[\"TELESCOP\"], hdr[\"INSTRUME\"]\n )\n)\n\n# If the FITS events are barycentered then these keywords should be set\n# TIMESYS = 'TDB ' / All times in this file are TDB\n# TIMEREF = 'SOLARSYSTEM' / Times are pathlength-corrected to barycenter\nif hdr[\"TIMESYS\"].startswith(\"TDB\"):\n barydata = True\nelse:\n barydata = False\nlog.info(\n \"Event time system = {0}, reference = {1}\".format(hdr[\"TIMESYS\"], hdr[\"TIMEREF\"])\n)\n\nif args.topo and barydata:\n log.error(\"Can't compute topocentric TOAs from barycentered events!\")\n sys.exit(1)\n\nif (args.orbfile is not None) and barydata:\n log.warning(\"Data are barycentered, so ignoring orbfile!\")\n\nif hdr[\"TELESCOP\"] == \"NICER\":\n # Instantiate NICERObs once so it gets added to the observatory registry\n # Bug! It should not do this if the events have already been barycentered!\n if barydata:\n obs = \"Barycenter\"\n else:\n if args.orbfile is not None:\n log.info(\"Setting up NICER observatory\")\n obs = get_satellite_observatory(\"NICER\", args.orbfile)\n else:\n log.error(\n \"NICER .orb file required for non-barycentered events!\\n\"\n \"Please specify with --orbfile\"\n )\n sys.exit(2)\n\n # Read event file and return list of TOA objects\n try:\n tl = local_load_NICER_TOAs(args.eventname)\n except KeyError:\n log.error(\n \"Failed to load NICER TOAs. Make sure orbit file is specified on command line!\"\n )\n raise\nelif hdr[\"TELESCOP\"] == \"XTE\":\n if barydata:\n obs = \"Barycenter\"\n else:\n # Instantiate RXTEObs once so it gets added to the observatory registry\n if args.orbfile is not None:\n # Determine what observatory type is.\n log.info(\"Setting up RXTE observatory\")\n obs = get_satellite_observatory(\"RXTE\", args.orbfile)\n else:\n log.error(\n \"RXTE FPorbit file required for non-barycentered events!\\n\"\n \"Please specify with --orbfile\"\n )\n sys.exit(2)\n # Read event file and return list of TOA objects\n tl = load_RXTE_TOAs(args.eventname)\nelif hdr[\"TELESCOP\"].startswith(\"XMM\"):\n # Not loading orbit file here, since that is not yet supported.\n if barydata:\n obs = \"Barycenter\"\n else:\n log.error(\"Non-barycentered XMM data not yet supported\")\n sys.exit(3)\n tl = load_XMM_TOAs(args.eventname)\nelif hdr[\"TELESCOP\"].startswith(\"NuSTAR\"):\n # Not loading orbit file here, since that is not yet supported.\n if barydata:\n obs = \"Barycenter\"\n else:\n log.error(\"Non-barycentered NuSTAR data not yet supported\")\n sys.exit(3)\n tl = load_NuSTAR_TOAs(args.eventname)\n f = pyfits.open(args.eventname)\n mets = f[\"events\"].data.field(\"time\")\n f.close()\n for t, met in zip(tl, mets):\n t.met = met\nelse:\n log.error(\n \"FITS file not recognized, TELESCOPE = {0}, INSTRUMENT = {1}\".format(\n hdr[\"TELESCOP\"], hdr[\"INSTRUME\"]\n )\n )\n sys.exit(1)\n\nif args.topo: # for writing UTC topo toas\n T2SpacecraftObs(name=\"spacecraft\")\n\nif len(tl) <= 0:\n log.error(\"No TOAs found. Aborting.\")\n sys.exit(1)\n\n# Now convert to TOAs object and compute TDBs and (SSB) posvels\nts = pint.toa.get_TOAs_list(\n tl, ephem=args.ephem, planets=planets, include_bipm=False, include_gps=False\n)\nts.filename = args.eventname\nlog.info(ts.print_summary())\n# print(ts.get_summary())\nmjds = (\n ts.get_mjds()\n) # TT topocentric MJDs as floats; only used to find the index of the photon time closest to the middle of the MJD range\n\n# Compute model phase for each TOA;\nphss = modelin.phase(ts, abs_phase=True)[1].value # discard units\n\n# Note that you can compute barycentric TOAs from topocentric data, so\n# just because topo is False does NOT mean that data are barycentered!\nif barydata:\n ph_times = ts.table[\"tdb\"]\nelse:\n ph_times = ts.table[\"mjd\"]\n\n# ensure all positive\nphases = np.where(phss < 0.0, phss + 1.0, phss)\n\nh = float(hm(phases))\nprint(\"Htest : {0:.2f} ({1:.2f} sigma)\".format(h, h2sig(h)))\nif args.plot:\n phaseogram_binned(mjds, phases, bins=100, plotfile=args.plotfile)\n\n# get exposure information\ntry:\n f = pyfits.open(args.eventname)\n exposure = f[1].header[\"exposure\"]\n f.close()\nexcept:\n exposure = 0\n\n\nif args.tint is None:\n\n # do a single TOA for table\n toafinal, toafinal_err = estimate_toa(\n mjds, phases, ph_times, args.topo, obs, modelin\n )\n if \"OBS_ID\" in hdr:\n # Add ObsID to the TOA flags\n toafinal.flags[\"obsid\"] = hdr[\"OBS_ID\"]\n toafinal.flags[\"htest\"] = \"{0:.2f}\".format(hm(phases))\n toafinal = [toafinal]\n toafinal_err = [toafinal_err]\nelse:\n # Load in GTIs\n f = pyfits.open(args.eventname)\n # Warning:: This is ignoring TIMEZERO!!!!\n gti_t0 = f[\"gti\"].data.field(\"start\")\n gti_t1 = f[\"gti\"].data.field(\"stop\")\n gti_dt = gti_t1 - gti_t0\n mets = np.asarray([t.met for t in tl])\n\n tint = float(args.tint)\n\n if args.dice:\n # Break up larger GTIs into small chunks\n new_t0s = deque()\n new_t1s = deque()\n for t0, t1 in zip(gti_t0, gti_t1):\n dt = t1 - t0\n if dt < tint:\n new_t0s.append(t0)\n new_t1s.append(t1)\n else:\n # break up GTI in such a way to avoid losing time (to tmin) and\n # to avoid having pieces longer than tint\n npiece = int(np.floor(dt / tint)) + 1\n new_edges = np.linspace(t0, t1, npiece + 1)\n for it0, it1 in zip(new_edges[:-1], new_edges[1:]):\n new_t0s.append(it0)\n new_t1s.append(it1)\n gti_t0 = np.asarray(new_t0s)\n gti_t1 = np.asarray(new_t1s)\n gti_dt = gti_t1 - gti_t0\n\n # the algorithm here is simple -- go through the GTI and add them up\n # until either the good time exceeds tint, or until the total time\n # interval exceeds maxint\n i0 = 0\n current = 0.0\n toas = deque()\n maxint = float(args.maxint)\n for i in range(len(gti_t0)):\n current += gti_dt[i]\n # print('iteration=%d, current=%f'%(i,current))\n if (\n (current >= tint)\n or ((gti_t1[i] - gti_t0[i0]) > maxint)\n or (i == len(gti_t0) - 1)\n ):\n # make a TOA\n ph0, ph1 = np.searchsorted(mets, [gti_t0[i0], gti_t1[i]])\n m, p, t = mjds[ph0:ph1], phases[ph0:ph1], ph_times[ph0:ph1]\n # print('Generating TOA ph0={0}, ph1={1}, len(m)={2}, i0={3}, i={4}'.format(ph0,ph1,len(m),i0,i))\n # print('m[0]={0}, m[1]={1}'.format(m[0],m[-1]))\n if len(m) > 0:\n toas.append(estimate_toa(m, p, t, args.topo, obs, modelin))\n toas[-1][0].flags[\"htest\"] = \"{0:.2f}\".format(hm(p))\n # fix exposure\n toas[-1][0].flags[\"exposure\"] = current\n current = 0.0\n i0 = i + 1\n toafinal, toafinal_err = list(zip(*toas))\n\nif args.minexp > 0.0:\n x = [\n (t, e)\n for t, e in zip(toafinal, toafinal_err)\n if float(t.flags[\"exposure\"]) > args.minexp\n ]\n if len(x) > 0:\n toafinal, toafinal_err = list(zip(*x))\n else:\n print(\"No TOAs passed exposure cut!\")\n sys.exit(0)\n\nfor t in toafinal:\n t.flags[\"-t\"] = hdr[\"TELESCOP\"]\ntoas = pint.toa.TOAs(toalist=toafinal)\ntoas.table[\"error\"][:] = np.asarray(toafinal_err)\nsio = io.StringIO()\ntoas.write_TOA_file(sio, name=\"photon_toa\", format=\"tempo2\")\noutput = sio.getvalue()\n\nif args.topo:\n output = output.replace(\"spacecraft\", \"STL_GEO\")\nelse:\n output = output.replace(\"bat\", \"@\")\n\nif args.append:\n output = output.replace(\"FORMAT 1\",\"C \")\n # Try to remove blank lines\n output = output.replace(\"\\n\\n\",\"\\n\")\n\nif args.outfile is not None:\n print(output, file=open(args.outfile, \"a\" if args.append else \"w\"))\nelse:\n print(output)\n"],"string":"[\n \"#!/usr/bin/env python\\n# Program: photon_toa.py\\n# Authors: Paul S. Ray \\n# Matthew Kerr \\n# Julia Deneva \\n# Description:\\n# Reads a FITS file of photon event times (from NICER or another X-ray mission)\\n# and generates TOAs from the unbined times using a pulsar timing model\\n# and an analytic template. The TOAs can be output them in Tempo2 format.\\nfrom __future__ import division, print_function\\n\\n# from future import standard_library\\n# standard_library.install_aliases()\\nfrom builtins import str\\nfrom builtins import zip\\nfrom builtins import range\\nimport os, sys\\nimport argparse\\nimport numpy as np\\nfrom astropy import log\\nimport astropy.units as u\\nimport astropy.io.fits as pyfits\\nimport pint.residuals\\nfrom pint.event_toas import load_NICER_TOAs\\nfrom pint.event_toas import load_RXTE_TOAs\\nfrom pint.event_toas import load_NuSTAR_TOAs\\nfrom pint.event_toas import load_XMM_TOAs\\nfrom pint.plot_utils import phaseogram_binned\\nfrom pint.observatory.satellite_obs import get_satellite_observatory\\nimport pint.toa, pint.models\\nfrom pint.eventstats import hmw, hm, h2sig\\nfrom astropy.time import Time, TimeDelta\\nfrom pint.templates.lctemplate import LCTemplate, prim_io\\nfrom pint.templates import lcfitters\\nfrom copy import deepcopy\\nimport pickle\\nimport io\\nfrom collections import deque\\nimport astropy.constants as const\\nfrom pint.observatory import get_observatory\\nfrom pint.observatory.special_locations import T2SpacecraftObs\\n\\nlog.setLevel(\\\"INFO\\\")\\n\\n\\ndef local_load_NICER_TOAs(eventname):\\n \\\"\\\"\\\" Local override to add MET field to each TOA object.\\\"\\\"\\\"\\n # TODO -- add this to PINT method ?\\n tl = load_NICER_TOAs(eventname)\\n f = pyfits.open(eventname)\\n mets = f[\\\"events\\\"].data.field(\\\"time\\\")\\n f.close()\\n for t, met in zip(tl, mets):\\n t.met = met\\n # The returned tl has topocentric TT MJD photon times; TIMESYS=TT, TIMEREF=LOCAL in the .evt file\\n return tl\\n\\n\\ndef estimate_toa(mjds, phases, ph_times, topo, obs, modelin):\\n \\\"\\\"\\\" Return a pint TOA object for the provided times and phases.\\n\\n Longer description here.\\n\\n Parameters\\n ----------\\n mjds : array of floats\\n The MJD times of each photon. These are for sorting the TOAs into\\n groups and making plots, not for precision work! The timescale\\n may be different for different datasets (see pint.toa.get_mjds)\\n phases : array\\n Array of model-computed phase values for each photon. Should be floats\\n between 0.0 and 1.0\\n ph_times : array of astropy.Time objects\\n Array of photon times, as recorded at Observatory obs\\n If obs==\\\"Barycenter\\\" then these should be BAT times in the TDB timescale\\n with the Roemer delays removed (the usual sense of \\\"barycentered\\\" times)\\n topo : bool\\n If True, then TOA will be computed for the arrival time at the Spacecraft\\n and the TOA line will have the spacecraft ECI position included.\\n If False, then the TOA will be a Barycentric Arrival Time (BAT)\\n obs : pint.observatory.Observatory\\n The observatory corresponding to the photon event times.\\n This is NOT necessarily the observatory for the output TOAs,\\n which can be the Barycenter.\\n\\\"\\\"\\\"\\n\\n # Given some subset of the event times, phases, and weights, compute\\n # the TOA based on a reference event near the middle of the span.\\n # Build the TOA as a PINT TOA() object\\n lcf = lcfitters.LCFitter(deepcopy(template), phases)\\n # fitbg does not work! Disabling.\\n # if args.fitbg:\\n # for i in xrange(2):\\n # lcf.fit_position(unbinned=False)\\n # lcf.fit_background(unbinned=False)\\n dphi, dphierr = lcf.fit_position(unbinned=args.unbinned, track=args.track)\\n log.info(\\\"Measured phase shift dphi={0}, dphierr={1}\\\".format(dphi, dphierr))\\n\\n # find time of event closest to center of observation and turn it into a TOA\\n argmid = np.searchsorted(mjds, 0.5 * (mjds.min() + mjds.max()))\\n tmid = ph_times[argmid]\\n # So, tmid should be a time at the observatory if topo, otherwise\\n # it should be a BAT (in TDB timescale with delays applied)\\n # Here, convert tmid if not topo and data not barycentered\\n\\n if topo:\\n tplus = tmid + TimeDelta(1 * u.s, scale=tmid.scale)\\n toamid = pint.toa.TOA(tmid, obs=obs.name)\\n toaplus = pint.toa.TOA(tplus, obs=obs.name)\\n else:\\n # If input data were not barycentered but we want barycentric TOAs\\n # then make TMID into a BAT\\n if tmid.scale not in (\\\"tdb\\\", \\\"tcb\\\"):\\n log.debug(\\n \\\"Making TOA, tmid {}, tmid.scale {}, obs {}\\\".format(\\n tmid, tmid.scale, obs.name\\n )\\n )\\n toas = pint.toa.get_TOAs_list(\\n [pint.toa.TOA(tmid, obs=obs.name)],\\n include_gps=args.use_gps,\\n include_bipm=args.use_bipm,\\n ephem=args.ephem,\\n planets=planets,\\n )\\n tmid = Time(modelin.get_barycentric_toas(toas), format=\\\"mjd\\\", scale=\\\"tdb\\\")[\\n 0\\n ]\\n log.debug(\\\"New tmid {}, tmid.scale {}\\\".format(tmid, tmid.scale))\\n\\n tplus = tmid + TimeDelta(1 * u.s, scale=tmid.scale)\\n toamid = pint.toa.TOA(tmid, obs=\\\"Barycenter\\\")\\n toaplus = pint.toa.TOA(tplus, obs=\\\"Barycenter\\\")\\n\\n toas = pint.toa.get_TOAs_list(\\n [toamid, toaplus],\\n include_gps=args.use_gps,\\n include_bipm=args.use_bipm,\\n ephem=args.ephem,\\n planets=planets,\\n )\\n\\n phsi, phsf = modelin.phase(toas, abs_phase=True)\\n if topo:\\n sc = \\\"tt\\\"\\n else:\\n sc = \\\"tdb\\\"\\n # Compute frequency = d(phase)/dt\\n f = (phsi[1] - phsi[0]) + (phsf[1] - phsf[0])\\n f._unit = u.Hz\\n\\n # First delta is to get time of phase 0.0 of initial model\\n # Second term corrects for the measured phase offset to align with template\\n tfinal = (\\n tmid + TimeDelta(-phsf[0].value / f, scale=sc) + TimeDelta(dphi / f, scale=sc)\\n )\\n\\n # Use PINT's TOA writer to save the TOA\\n nsrc = lcf.template.norm() * len(lcf.phases)\\n nbkg = (1 - lcf.template.norm()) * len(lcf.phases)\\n\\n if args.topo: # tfinal is a topocentric TT MJD\\n telposvel = obs.posvel_gcrs(tfinal)\\n x = telposvel.pos[0].to(u.km)\\n y = telposvel.pos[1].to(u.km)\\n z = telposvel.pos[2].to(u.km)\\n vx = telposvel.vel[0].to(u.km / u.s)\\n vy = telposvel.vel[1].to(u.km / u.s)\\n vz = telposvel.vel[2].to(u.km / u.s)\\n\\n toafinal = pint.toa.TOA(\\n tfinal.utc,\\n obs=\\\"spacecraft\\\",\\n nsrc=\\\"%.2f\\\" % nsrc,\\n nbkg=\\\"%.2f\\\" % nbkg,\\n exposure=\\\"%.2f\\\" % exposure,\\n dphi=\\\"%.5f\\\" % dphi,\\n mjdTT=\\\"%.8f\\\" % tfinal.tt.mjd,\\n telx=\\\"%.8f\\\" % x.value,\\n tely=\\\"%.8f\\\" % y.value,\\n telz=\\\"%.8f\\\" % z.value,\\n vx=\\\"%.8f\\\" % vx.value,\\n vy=\\\"%.8f\\\" % vy.value,\\n vz=\\\"%.8f\\\" % vz.value,\\n )\\n\\n else:\\n # Make a TOA for the Barycenter, which is the default obs\\n toafinal = pint.toa.TOA(\\n tfinal,\\n obs=\\\"Barycenter\\\",\\n nsrc=\\\"%.2f\\\" % nsrc,\\n nbkg=\\\"%.2f\\\" % nbkg,\\n exposure=\\\"%.2f\\\" % exposure,\\n dphi=\\\"%.5f\\\" % dphi,\\n )\\n toasfinal = pint.toa.get_TOAs_list(\\n [toafinal],\\n include_gps=args.use_gps,\\n include_bipm=args.use_bipm,\\n ephem=args.ephem,\\n planets=planets,\\n )\\n log.debug(\\n \\\"Modelin final phase {}\\\".format(modelin.phase(toasfinal, abs_phase=True))\\n )\\n log.info(\\n \\\"Src rate = {0} c/s, Bkg rate = {1} c/s\\\".format(\\n nsrc / exposure, nbkg / exposure\\n )\\n )\\n return toafinal, dphierr / f.value * 1.0e6\\n\\n\\ndesc = \\\"\\\"\\\"Generate TOAs from photon event data.\\\"\\\"\\\"\\n\\nparser = argparse.ArgumentParser(description=desc)\\nparser.add_argument(\\\"eventname\\\", help=\\\"FITS file to read events from\\\")\\nparser.add_argument(\\\"templatename\\\", help=\\\"Name of file to read template from\\\")\\nparser.add_argument(\\\"parname\\\", help=\\\"Timing model file name\\\")\\nparser.add_argument(\\\"--orbfile\\\", help=\\\"Name of orbit file\\\", default=None)\\nparser.add_argument(\\n \\\"--ephem\\\", help=\\\"Planetary ephemeris to use (default=DE421)\\\", default=\\\"DE421\\\"\\n)\\nparser.add_argument(\\n \\\"--plot\\\", help=\\\"Show phaseogram plot.\\\", action=\\\"store_true\\\", default=False\\n)\\nparser.add_argument(\\n \\\"--plotfile\\\", help=\\\"Output figure file name (default=None)\\\", default=None\\n)\\n# parser.add_argument(\\\"--fitbg\\\",help=\\\"Fit an overall background level (e.g. for changing particle background level (default=False).\\\",action='store_true',default=False)\\nparser.add_argument(\\n \\\"--unbinned\\\",\\n help=\\\"Fit position with unbinned likelihood. Don't use for large data sets. (default=False)\\\",\\n action=\\\"store_true\\\",\\n default=False,\\n)\\n# parser.add_argument(\\\"--fix\\\",help=\\\"Adjust times to fix 1.0 second offset in NICER data (default=False)\\\", action='store_true',default=False)\\nparser.add_argument(\\n \\\"--tint\\\",\\n help=\\\"Integrate for tint seconds for each TOA, or until the total integration exceeds maxint. The algorithm is based on GTI, so the integration will slightly exceed tint (default None; see maxint.)\\\",\\n default=None,\\n)\\nparser.add_argument(\\n \\\"--maxint\\\",\\n help=\\\"Maximum time interval to accumulate exposure for a single TOA (default=2*86400s)\\\",\\n type=float,\\n default=2 * 86400.0,\\n)\\nparser.add_argument(\\n \\\"--minexp\\\",\\n help=\\\"Minimum exposure (s) for which to include a TOA (default=0.0).\\\",\\n default=0.0,\\n type=float,\\n)\\nparser.add_argument(\\n \\\"--track\\\",\\n help=\\\"Assume model is close to good and only search near 0 phase (to avoid getting TOAs off by 0.5 in double peaked pulsars)\\\",\\n action=\\\"store_true\\\",\\n default=False,\\n)\\nparser.add_argument(\\n \\\"--dice\\\",\\n help=\\\"Dice up long GTIs into chunks of length <= tint\\\",\\n action=\\\"store_true\\\",\\n default=False,\\n)\\nparser.add_argument(\\n \\\"--use_bipm\\\", help=\\\"Use BIPM clock corrections\\\", action=\\\"store_true\\\", default=False\\n)\\nparser.add_argument(\\n \\\"--use_gps\\\",\\n help=\\\"Use GPS to UTC clock corrections\\\",\\n action=\\\"store_true\\\",\\n default=False,\\n)\\nparser.add_argument(\\n \\\"--topo\\\",\\n help=\\\"Make topocentric TOAs; include the spacecraft ECI position on the TOA line\\\",\\n action=\\\"store_true\\\",\\n default=False,\\n)\\nparser.add_argument(\\n \\\"--outfile\\\", help=\\\"Name of file to save TOAs to (default is STDOUT)\\\", default=None\\n)\\nparser.add_argument(\\\"--append\\\", help=\\\"Append TOAs to output file instead of overwriting\\\", default=False, action=\\\"store_true\\\")\\n\\n## Parse arguments\\nargs = parser.parse_args()\\n\\n# Load PINT model objects\\nmodelin = pint.models.get_model(args.parname)\\nlog.info(str(modelin))\\n\\n# check for consistency between ephemeris and options\\nif modelin.PLANET_SHAPIRO.quantity:\\n planets = True\\nelse:\\n planets = False\\n\\n# Load Template objects\\ntry:\\n template = pickle.load(file(args.templatename))\\nexcept:\\n primitives, norms = prim_io(args.templatename)\\n template = LCTemplate(primitives, norms)\\n# print(template)\\n\\n# Load photons as PINT toas, and weights, if specified\\n# Here I might loop over the files specified\\n# Read event file header to figure out what instrument is is from\\nhdr = pyfits.getheader(args.eventname, ext=1)\\nlog.info(\\n \\\"Event file TELESCOPE = {0}, INSTRUMENT = {1}\\\".format(\\n hdr[\\\"TELESCOP\\\"], hdr[\\\"INSTRUME\\\"]\\n )\\n)\\n\\n# If the FITS events are barycentered then these keywords should be set\\n# TIMESYS = 'TDB ' / All times in this file are TDB\\n# TIMEREF = 'SOLARSYSTEM' / Times are pathlength-corrected to barycenter\\nif hdr[\\\"TIMESYS\\\"].startswith(\\\"TDB\\\"):\\n barydata = True\\nelse:\\n barydata = False\\nlog.info(\\n \\\"Event time system = {0}, reference = {1}\\\".format(hdr[\\\"TIMESYS\\\"], hdr[\\\"TIMEREF\\\"])\\n)\\n\\nif args.topo and barydata:\\n log.error(\\\"Can't compute topocentric TOAs from barycentered events!\\\")\\n sys.exit(1)\\n\\nif (args.orbfile is not None) and barydata:\\n log.warning(\\\"Data are barycentered, so ignoring orbfile!\\\")\\n\\nif hdr[\\\"TELESCOP\\\"] == \\\"NICER\\\":\\n # Instantiate NICERObs once so it gets added to the observatory registry\\n # Bug! It should not do this if the events have already been barycentered!\\n if barydata:\\n obs = \\\"Barycenter\\\"\\n else:\\n if args.orbfile is not None:\\n log.info(\\\"Setting up NICER observatory\\\")\\n obs = get_satellite_observatory(\\\"NICER\\\", args.orbfile)\\n else:\\n log.error(\\n \\\"NICER .orb file required for non-barycentered events!\\\\n\\\"\\n \\\"Please specify with --orbfile\\\"\\n )\\n sys.exit(2)\\n\\n # Read event file and return list of TOA objects\\n try:\\n tl = local_load_NICER_TOAs(args.eventname)\\n except KeyError:\\n log.error(\\n \\\"Failed to load NICER TOAs. Make sure orbit file is specified on command line!\\\"\\n )\\n raise\\nelif hdr[\\\"TELESCOP\\\"] == \\\"XTE\\\":\\n if barydata:\\n obs = \\\"Barycenter\\\"\\n else:\\n # Instantiate RXTEObs once so it gets added to the observatory registry\\n if args.orbfile is not None:\\n # Determine what observatory type is.\\n log.info(\\\"Setting up RXTE observatory\\\")\\n obs = get_satellite_observatory(\\\"RXTE\\\", args.orbfile)\\n else:\\n log.error(\\n \\\"RXTE FPorbit file required for non-barycentered events!\\\\n\\\"\\n \\\"Please specify with --orbfile\\\"\\n )\\n sys.exit(2)\\n # Read event file and return list of TOA objects\\n tl = load_RXTE_TOAs(args.eventname)\\nelif hdr[\\\"TELESCOP\\\"].startswith(\\\"XMM\\\"):\\n # Not loading orbit file here, since that is not yet supported.\\n if barydata:\\n obs = \\\"Barycenter\\\"\\n else:\\n log.error(\\\"Non-barycentered XMM data not yet supported\\\")\\n sys.exit(3)\\n tl = load_XMM_TOAs(args.eventname)\\nelif hdr[\\\"TELESCOP\\\"].startswith(\\\"NuSTAR\\\"):\\n # Not loading orbit file here, since that is not yet supported.\\n if barydata:\\n obs = \\\"Barycenter\\\"\\n else:\\n log.error(\\\"Non-barycentered NuSTAR data not yet supported\\\")\\n sys.exit(3)\\n tl = load_NuSTAR_TOAs(args.eventname)\\n f = pyfits.open(args.eventname)\\n mets = f[\\\"events\\\"].data.field(\\\"time\\\")\\n f.close()\\n for t, met in zip(tl, mets):\\n t.met = met\\nelse:\\n log.error(\\n \\\"FITS file not recognized, TELESCOPE = {0}, INSTRUMENT = {1}\\\".format(\\n hdr[\\\"TELESCOP\\\"], hdr[\\\"INSTRUME\\\"]\\n )\\n )\\n sys.exit(1)\\n\\nif args.topo: # for writing UTC topo toas\\n T2SpacecraftObs(name=\\\"spacecraft\\\")\\n\\nif len(tl) <= 0:\\n log.error(\\\"No TOAs found. Aborting.\\\")\\n sys.exit(1)\\n\\n# Now convert to TOAs object and compute TDBs and (SSB) posvels\\nts = pint.toa.get_TOAs_list(\\n tl, ephem=args.ephem, planets=planets, include_bipm=False, include_gps=False\\n)\\nts.filename = args.eventname\\nlog.info(ts.print_summary())\\n# print(ts.get_summary())\\nmjds = (\\n ts.get_mjds()\\n) # TT topocentric MJDs as floats; only used to find the index of the photon time closest to the middle of the MJD range\\n\\n# Compute model phase for each TOA;\\nphss = modelin.phase(ts, abs_phase=True)[1].value # discard units\\n\\n# Note that you can compute barycentric TOAs from topocentric data, so\\n# just because topo is False does NOT mean that data are barycentered!\\nif barydata:\\n ph_times = ts.table[\\\"tdb\\\"]\\nelse:\\n ph_times = ts.table[\\\"mjd\\\"]\\n\\n# ensure all positive\\nphases = np.where(phss < 0.0, phss + 1.0, phss)\\n\\nh = float(hm(phases))\\nprint(\\\"Htest : {0:.2f} ({1:.2f} sigma)\\\".format(h, h2sig(h)))\\nif args.plot:\\n phaseogram_binned(mjds, phases, bins=100, plotfile=args.plotfile)\\n\\n# get exposure information\\ntry:\\n f = pyfits.open(args.eventname)\\n exposure = f[1].header[\\\"exposure\\\"]\\n f.close()\\nexcept:\\n exposure = 0\\n\\n\\nif args.tint is None:\\n\\n # do a single TOA for table\\n toafinal, toafinal_err = estimate_toa(\\n mjds, phases, ph_times, args.topo, obs, modelin\\n )\\n if \\\"OBS_ID\\\" in hdr:\\n # Add ObsID to the TOA flags\\n toafinal.flags[\\\"obsid\\\"] = hdr[\\\"OBS_ID\\\"]\\n toafinal.flags[\\\"htest\\\"] = \\\"{0:.2f}\\\".format(hm(phases))\\n toafinal = [toafinal]\\n toafinal_err = [toafinal_err]\\nelse:\\n # Load in GTIs\\n f = pyfits.open(args.eventname)\\n # Warning:: This is ignoring TIMEZERO!!!!\\n gti_t0 = f[\\\"gti\\\"].data.field(\\\"start\\\")\\n gti_t1 = f[\\\"gti\\\"].data.field(\\\"stop\\\")\\n gti_dt = gti_t1 - gti_t0\\n mets = np.asarray([t.met for t in tl])\\n\\n tint = float(args.tint)\\n\\n if args.dice:\\n # Break up larger GTIs into small chunks\\n new_t0s = deque()\\n new_t1s = deque()\\n for t0, t1 in zip(gti_t0, gti_t1):\\n dt = t1 - t0\\n if dt < tint:\\n new_t0s.append(t0)\\n new_t1s.append(t1)\\n else:\\n # break up GTI in such a way to avoid losing time (to tmin) and\\n # to avoid having pieces longer than tint\\n npiece = int(np.floor(dt / tint)) + 1\\n new_edges = np.linspace(t0, t1, npiece + 1)\\n for it0, it1 in zip(new_edges[:-1], new_edges[1:]):\\n new_t0s.append(it0)\\n new_t1s.append(it1)\\n gti_t0 = np.asarray(new_t0s)\\n gti_t1 = np.asarray(new_t1s)\\n gti_dt = gti_t1 - gti_t0\\n\\n # the algorithm here is simple -- go through the GTI and add them up\\n # until either the good time exceeds tint, or until the total time\\n # interval exceeds maxint\\n i0 = 0\\n current = 0.0\\n toas = deque()\\n maxint = float(args.maxint)\\n for i in range(len(gti_t0)):\\n current += gti_dt[i]\\n # print('iteration=%d, current=%f'%(i,current))\\n if (\\n (current >= tint)\\n or ((gti_t1[i] - gti_t0[i0]) > maxint)\\n or (i == len(gti_t0) - 1)\\n ):\\n # make a TOA\\n ph0, ph1 = np.searchsorted(mets, [gti_t0[i0], gti_t1[i]])\\n m, p, t = mjds[ph0:ph1], phases[ph0:ph1], ph_times[ph0:ph1]\\n # print('Generating TOA ph0={0}, ph1={1}, len(m)={2}, i0={3}, i={4}'.format(ph0,ph1,len(m),i0,i))\\n # print('m[0]={0}, m[1]={1}'.format(m[0],m[-1]))\\n if len(m) > 0:\\n toas.append(estimate_toa(m, p, t, args.topo, obs, modelin))\\n toas[-1][0].flags[\\\"htest\\\"] = \\\"{0:.2f}\\\".format(hm(p))\\n # fix exposure\\n toas[-1][0].flags[\\\"exposure\\\"] = current\\n current = 0.0\\n i0 = i + 1\\n toafinal, toafinal_err = list(zip(*toas))\\n\\nif args.minexp > 0.0:\\n x = [\\n (t, e)\\n for t, e in zip(toafinal, toafinal_err)\\n if float(t.flags[\\\"exposure\\\"]) > args.minexp\\n ]\\n if len(x) > 0:\\n toafinal, toafinal_err = list(zip(*x))\\n else:\\n print(\\\"No TOAs passed exposure cut!\\\")\\n sys.exit(0)\\n\\nfor t in toafinal:\\n t.flags[\\\"-t\\\"] = hdr[\\\"TELESCOP\\\"]\\ntoas = pint.toa.TOAs(toalist=toafinal)\\ntoas.table[\\\"error\\\"][:] = np.asarray(toafinal_err)\\nsio = io.StringIO()\\ntoas.write_TOA_file(sio, name=\\\"photon_toa\\\", format=\\\"tempo2\\\")\\noutput = sio.getvalue()\\n\\nif args.topo:\\n output = output.replace(\\\"spacecraft\\\", \\\"STL_GEO\\\")\\nelse:\\n output = output.replace(\\\"bat\\\", \\\"@\\\")\\n\\nif args.append:\\n output = output.replace(\\\"FORMAT 1\\\",\\\"C \\\")\\n # Try to remove blank lines\\n output = output.replace(\\\"\\\\n\\\\n\\\",\\\"\\\\n\\\")\\n\\nif args.outfile is not None:\\n print(output, file=open(args.outfile, \\\"a\\\" if args.append else \\\"w\\\"))\\nelse:\\n print(output)\\n\"\n]"},"apis":{"kind":"list like","value":[["numpy.linspace","numpy.asarray","numpy.floor","numpy.searchsorted","numpy.where"]],"string":"[\n [\n \"numpy.linspace\",\n \"numpy.asarray\",\n \"numpy.floor\",\n \"numpy.searchsorted\",\n \"numpy.where\"\n ]\n]"},"possible_versions":{"kind":"list like","value":[{"matplotlib":[],"numpy":[],"pandas":[],"scipy":[],"tensorflow":[]}],"string":"[\n {\n \"matplotlib\": [],\n \"numpy\": [],\n \"pandas\": [],\n \"scipy\": [],\n \"tensorflow\": []\n }\n]"}}},{"rowIdx":72525,"cells":{"repo_name":{"kind":"string","value":"Migelo/lopa-sorting"},"hexsha":{"kind":"list like","value":["5ed2732262940e0c24caee8ac734c54167932bcd"],"string":"[\n \"5ed2732262940e0c24caee8ac734c54167932bcd\"\n]"},"file_path":{"kind":"list like","value":["bins.py"],"string":"[\n \"bins.py\"\n]"},"code":{"kind":"list like","value":["import numpy as np\nimport argparse\n\nparser = argparse.ArgumentParser(description='Generate bins.')\nparser.add_argument('beginning', help='Beginning of the first bin.', type=str)\nparser.add_argument('end', help='End of the last bin.', type=str)\nparser.add_argument('-interval', help='Size of the bin.', type=int)\nparser.add_argument('-n', help='Number of bins.', type=int)\nparser.add_argument('outputFile', type=str, help='Set the output file.')\nparser.add_argument('-sb', type=bool, default=False, help='Use when \\\n creating sub-bins.')\nargs = parser.parse_args()\n\nargs.beginning = np.float(args.beginning)\nargs.end = np.float(args.end)\n\nif (args.interval is not None) and (args.n is not None):\n parser.error('-n and -interval are mutually exclusive')\n\nbins = []\ni = args.beginning\nif args.interval is not None:\n interval = args.interval\n while i < args.end:\n if i + interval > args.end:\n bins.append([i, args.end])\n else:\n bins.append([i, i + interval])\n i += interval\nelif args.n is not None:\n if args.sb:\n interval = 1.\n else:\n interval = (args.end - args.beginning) / args.n\n for j in range(args.n):\n bins.append([i, i + interval])\n i += interval\n\nnp.savetxt(args.outputFile, bins)\n"],"string":"[\n \"import numpy as np\\nimport argparse\\n\\nparser = argparse.ArgumentParser(description='Generate bins.')\\nparser.add_argument('beginning', help='Beginning of the first bin.', type=str)\\nparser.add_argument('end', help='End of the last bin.', type=str)\\nparser.add_argument('-interval', help='Size of the bin.', type=int)\\nparser.add_argument('-n', help='Number of bins.', type=int)\\nparser.add_argument('outputFile', type=str, help='Set the output file.')\\nparser.add_argument('-sb', type=bool, default=False, help='Use when \\\\\\n creating sub-bins.')\\nargs = parser.parse_args()\\n\\nargs.beginning = np.float(args.beginning)\\nargs.end = np.float(args.end)\\n\\nif (args.interval is not None) and (args.n is not None):\\n parser.error('-n and -interval are mutually exclusive')\\n\\nbins = []\\ni = args.beginning\\nif args.interval is not None:\\n interval = args.interval\\n while i < args.end:\\n if i + interval > args.end:\\n bins.append([i, args.end])\\n else:\\n bins.append([i, i + interval])\\n i += interval\\nelif args.n is not None:\\n if args.sb:\\n interval = 1.\\n else:\\n interval = (args.end - args.beginning) / args.n\\n for j in range(args.n):\\n bins.append([i, i + interval])\\n i += interval\\n\\nnp.savetxt(args.outputFile, bins)\\n\"\n]"},"apis":{"kind":"list like","value":[["numpy.savetxt","numpy.float"]],"string":"[\n [\n \"numpy.savetxt\",\n \"numpy.float\"\n ]\n]"},"possible_versions":{"kind":"list like","value":[{"matplotlib":[],"numpy":[],"pandas":[],"scipy":[],"tensorflow":[]}],"string":"[\n {\n \"matplotlib\": [],\n \"numpy\": [],\n \"pandas\": [],\n \"scipy\": [],\n \"tensorflow\": []\n }\n]"}}},{"rowIdx":72526,"cells":{"repo_name":{"kind":"string","value":"LeOntalEs/transform3d"},"hexsha":{"kind":"list like","value":["f3426c3cce98298c17d3820fa2d8e1bdf92a8571"],"string":"[\n \"f3426c3cce98298c17d3820fa2d8e1bdf92a8571\"\n]"},"file_path":{"kind":"list like","value":["transform3d/transform.py"],"string":"[\n \"transform3d/transform.py\"\n]"},"code":{"kind":"list like","value":["import cv2\nimport numpy as np\n\ndef _get_M(w, h, f, rx=0, ry=0, rz=0, dx=0, dy=0, dz=0, sx=1, sy=1, sz=1):\n A1 = np.matrix([ [1, 0, -w/2],\n [0, 1, -h/2],\n [0, 0, 1],\n [0, 0, 1]])\n S = np.matrix([[sx, 0, 0, 0],\n [0, sy, 0, 0],\n [0, 0, sz, 0],\n [0, 0, 0, 1]])\n RX = np.matrix([ [1, 0, 0, 0],\n [0, np.cos(rx), -np.sin(rx), 0],\n [0, np.sin(rx), np.cos(rx), 0],\n [0, 0, 0, 1]])\n RY = np.matrix([ [np.cos(ry), 0, -np.sin(ry), 0],\n [0, 1, 0, 0],\n [np.sin(ry), 0, np.cos(ry), 0],\n [0, 0, 0, 1]])\n RZ = np.matrix([ [np.cos(rz), -np.sin(rz), 0, 0],\n [np.sin(rz), np.cos(rz), 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1]])\n T = np.matrix([ [1, 0, 0, dx],\n [0, 1, 0, dy],\n [0, 0, 1, dz],\n [0, 0, 0, 1]])\n A2 = np.matrix([ [f, 0, w/2, 0],\n [0, f, h/2, 0],\n [0, 0, 1, 0]])\n R = RX * RY * RZ\n return A2 * T * R * S * A1\n\ndef transform3d(img, rx=0, ry=0, rz=0, dx=0, dy=0, dz=0, sx=1, sy=1, sz=1):\n h, w, c = img.shape\n rx, ry, rz = np.radians([rx, ry, rz])\n d = np.sqrt(h**2 + w**2)\n f = d / (2 * np.sin(rz) if np.sin(rz) != 0 else 1)\n dz = f\n M = _get_M(w, h, f, rx, ry,rz, dx, dy, dz, sx, sy)\n return cv2.warpPerspective(img.copy(), M, (w, h))\n "],"string":"[\n \"import cv2\\nimport numpy as np\\n\\ndef _get_M(w, h, f, rx=0, ry=0, rz=0, dx=0, dy=0, dz=0, sx=1, sy=1, sz=1):\\n A1 = np.matrix([ [1, 0, -w/2],\\n [0, 1, -h/2],\\n [0, 0, 1],\\n [0, 0, 1]])\\n S = np.matrix([[sx, 0, 0, 0],\\n [0, sy, 0, 0],\\n [0, 0, sz, 0],\\n [0, 0, 0, 1]])\\n RX = np.matrix([ [1, 0, 0, 0],\\n [0, np.cos(rx), -np.sin(rx), 0],\\n [0, np.sin(rx), np.cos(rx), 0],\\n [0, 0, 0, 1]])\\n RY = np.matrix([ [np.cos(ry), 0, -np.sin(ry), 0],\\n [0, 1, 0, 0],\\n [np.sin(ry), 0, np.cos(ry), 0],\\n [0, 0, 0, 1]])\\n RZ = np.matrix([ [np.cos(rz), -np.sin(rz), 0, 0],\\n [np.sin(rz), np.cos(rz), 0, 0],\\n [0, 0, 1, 0],\\n [0, 0, 0, 1]])\\n T = np.matrix([ [1, 0, 0, dx],\\n [0, 1, 0, dy],\\n [0, 0, 1, dz],\\n [0, 0, 0, 1]])\\n A2 = np.matrix([ [f, 0, w/2, 0],\\n [0, f, h/2, 0],\\n [0, 0, 1, 0]])\\n R = RX * RY * RZ\\n return A2 * T * R * S * A1\\n\\ndef transform3d(img, rx=0, ry=0, rz=0, dx=0, dy=0, dz=0, sx=1, sy=1, sz=1):\\n h, w, c = img.shape\\n rx, ry, rz = np.radians([rx, ry, rz])\\n d = np.sqrt(h**2 + w**2)\\n f = d / (2 * np.sin(rz) if np.sin(rz) != 0 else 1)\\n dz = f\\n M = _get_M(w, h, f, rx, ry,rz, dx, dy, dz, sx, sy)\\n return cv2.warpPerspective(img.copy(), M, (w, h))\\n \"\n]"},"apis":{"kind":"list like","value":[["numpy.matrix","numpy.radians","numpy.sqrt","numpy.cos","numpy.sin"]],"string":"[\n [\n \"numpy.matrix\",\n \"numpy.radians\",\n \"numpy.sqrt\",\n \"numpy.cos\",\n \"numpy.sin\"\n ]\n]"},"possible_versions":{"kind":"list like","value":[{"matplotlib":[],"numpy":[],"pandas":[],"scipy":[],"tensorflow":[]}],"string":"[\n {\n \"matplotlib\": [],\n \"numpy\": [],\n \"pandas\": [],\n \"scipy\": [],\n \"tensorflow\": []\n }\n]"}}},{"rowIdx":72527,"cells":{"repo_name":{"kind":"string","value":"PM25/Facial_Expression_DL"},"hexsha":{"kind":"list like","value":["9c10886b27ed13a352e8ca355b1b512cf6e92db0"],"string":"[\n \"9c10886b27ed13a352e8ca355b1b512cf6e92db0\"\n]"},"file_path":{"kind":"list like","value":["main.py"],"string":"[\n \"main.py\"\n]"},"code":{"kind":"list like","value":["import torch\nfrom PIL import Image\nimport torch.nn.functional as F\nfrom torchvision import transforms\nfrom argparse import ArgumentParser\nimport matplotlib.pyplot as plt\n\n\n# Arguments\nparser = ArgumentParser(description='Predicting Facial Expression of an Image.')\nparser.add_argument('--model', type=str, default='models/model.pkl', help='Path of Previous Trained Model')\nparser.add_argument('--img', type=str, default='img.jpg', help='Path of Image')\nargs = parser.parse_args()\n\n\n# PyTorch Transform function\ntransform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(mean=(.5, .5, .5), std=(.5, .5, .5))\n ])\n\n# Start frome here!\nif __name__ == '__main__':\n classes = [\"Surprise\", \"Fear\", \"Disgust\", \"Happiness\", \"Sadness\" ,\"Anger\", \"Neutral\"]\n n_classes = len(classes)\n\n # Load Model\n model = torch.load(args.model).eval()\n\n # Load Image & Predict \n with torch.no_grad():\n img = Image.open(args.img).convert('RGB')\n img = transform(img)\n output = model(img.unsqueeze(0))\n output = F.softmax(output, dim=1)\n _, predict = torch.max(output, 1)\n \n plt.barh(range(n_classes), output.squeeze().tolist())\n plt.yticks(range(n_classes), classes)\n plt.title(f'Predict: {classes[predict]}')\n plt.show()"],"string":"[\n \"import torch\\nfrom PIL import Image\\nimport torch.nn.functional as F\\nfrom torchvision import transforms\\nfrom argparse import ArgumentParser\\nimport matplotlib.pyplot as plt\\n\\n\\n# Arguments\\nparser = ArgumentParser(description='Predicting Facial Expression of an Image.')\\nparser.add_argument('--model', type=str, default='models/model.pkl', help='Path of Previous Trained Model')\\nparser.add_argument('--img', type=str, default='img.jpg', help='Path of Image')\\nargs = parser.parse_args()\\n\\n\\n# PyTorch Transform function\\ntransform = transforms.Compose([\\n transforms.ToTensor(),\\n transforms.Normalize(mean=(.5, .5, .5), std=(.5, .5, .5))\\n ])\\n\\n# Start frome here!\\nif __name__ == '__main__':\\n classes = [\\\"Surprise\\\", \\\"Fear\\\", \\\"Disgust\\\", \\\"Happiness\\\", \\\"Sadness\\\" ,\\\"Anger\\\", \\\"Neutral\\\"]\\n n_classes = len(classes)\\n\\n # Load Model\\n model = torch.load(args.model).eval()\\n\\n # Load Image & Predict \\n with torch.no_grad():\\n img = Image.open(args.img).convert('RGB')\\n img = transform(img)\\n output = model(img.unsqueeze(0))\\n output = F.softmax(output, dim=1)\\n _, predict = torch.max(output, 1)\\n \\n plt.barh(range(n_classes), output.squeeze().tolist())\\n plt.yticks(range(n_classes), classes)\\n plt.title(f'Predict: {classes[predict]}')\\n plt.show()\"\n]"},"apis":{"kind":"list like","value":[["torch.nn.functional.softmax","torch.max","matplotlib.pyplot.title","torch.load","torch.no_grad","matplotlib.pyplot.show"]],"string":"[\n [\n \"torch.nn.functional.softmax\",\n \"torch.max\",\n \"matplotlib.pyplot.title\",\n \"torch.load\",\n \"torch.no_grad\",\n \"matplotlib.pyplot.show\"\n ]\n]"},"possible_versions":{"kind":"list like","value":[{"matplotlib":[],"numpy":[],"pandas":[],"scipy":[],"tensorflow":[]}],"string":"[\n {\n \"matplotlib\": [],\n \"numpy\": [],\n \"pandas\": [],\n \"scipy\": [],\n \"tensorflow\": []\n }\n]"}}},{"rowIdx":72528,"cells":{"repo_name":{"kind":"string","value":"ilyakrasnou/DiplomaProject"},"hexsha":{"kind":"list like","value":["a4cfd04fc00780c254e86e47039fecf27c3cbc9b"],"string":"[\n \"a4cfd04fc00780c254e86e47039fecf27c3cbc9b\"\n]"},"file_path":{"kind":"list like","value":["PythonNeuro/weights_viewer.py"],"string":"[\n \"PythonNeuro/weights_viewer.py\"\n]"},"code":{"kind":"list like","value":["import numpy as np\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\n\nmodel = keras.models.load_model(\"mnist_model.h5\")\n\nfor layer in model.layers:\n weights = layer.get_weights()\n print(layer.name)\n print(weights)\n"],"string":"[\n \"import numpy as np\\nfrom tensorflow import keras\\nfrom tensorflow.keras import layers\\n\\nmodel = keras.models.load_model(\\\"mnist_model.h5\\\")\\n\\nfor layer in model.layers:\\n weights = layer.get_weights()\\n print(layer.name)\\n print(weights)\\n\"\n]"},"apis":{"kind":"list like","value":[["tensorflow.keras.models.load_model"]],"string":"[\n [\n \"tensorflow.keras.models.load_model\"\n ]\n]"},"possible_versions":{"kind":"list like","value":[{"matplotlib":[],"numpy":[],"pandas":[],"scipy":[],"tensorflow":["1.10","2.7","2.2","2.3","2.4","2.5","2.6"]}],"string":"[\n {\n \"matplotlib\": [],\n \"numpy\": [],\n \"pandas\": [],\n \"scipy\": [],\n \"tensorflow\": [\n \"1.10\",\n \"2.7\",\n \"2.2\",\n \"2.3\",\n \"2.4\",\n \"2.5\",\n \"2.6\"\n ]\n }\n]"}}},{"rowIdx":72529,"cells":{"repo_name":{"kind":"string","value":"je-c/CryptoClassifier"},"hexsha":{"kind":"list like","value":["abce5e81e9045581df29af2f77f89e851911e0bc"],"string":"[\n \"abce5e81e9045581df29af2f77f89e851911e0bc\"\n]"},"file_path":{"kind":"list like","value":["lib/functionality/processing.py"],"string":"[\n \"lib/functionality/processing.py\"\n]"},"code":{"kind":"list like","value":["import pandas as pd\nimport numpy as np\nimport datetime as dt\nimport time, csv, os, itertools, shutil, json, random\nimport btalib\n\nfrom itertools import compress\nfrom PIL import Image\n\nfrom sklearn.preprocessing import MinMaxScaler\n\ndef bool_convert(s):\n \"\"\"\n Parse string booleans from parameters\n * :param s(str): String to convert\n :return s(bool): Boolean type\n \"\"\"\n try:\n if s == \"True\":\n return True\n elif s == \"False\":\n return False\n else:\n return s\n except TypeError:\n return s\n\ndef int_convert(s):\n \"\"\"\n Parse string int from parameters\n * :param s(str): String to convert\n :return s(int): Int type\n \"\"\"\n try:\n return int(s)\n except ValueError:\n return s\n except TypeError:\n return s\n \ndef load_params(filePath, deploy = False):\n \"\"\"\n Parse parameters json\n * :param filePath(str): Location of parameters file\n * :param deploy(bool): Denotation for whether parameters are being loaded by deployment code\n\n :return params(dict): Python dictionary of parameters with correct dtypes\n \"\"\"\n with open(filePath) as f:\n params = json.load(f)\n if deploy:\n return params\n else: \n for split in ['validDL', 'trainDL']:\n params['loadingParams'][split]['shuffle'] = bool_convert(params['loadingParams'][split]['shuffle'])\n\n for key in params:\n for subkey in params[key]:\n if subkey == 'shuffle':\n params[key][subkey] = bool_convert(params[key][subkey])\n else:\n params[key][subkey] = int_convert(params[key][subkey])\n \n f.close()\n return params\n\ndef unpack_img_dataset(params, directory, file_name):\n \"\"\"\n Unpack an image dataset stored as raw data (csv or otherwise) into .png's. Creates file structure for pytorch loading\n and handles train/test/validation splitting internally\n * :param params(dict): Location of parameters file\n * :param directory(str): Name of directory to check for, or create to store images\n * :param file_name(str): Name of .csv file of featureset for image creation \n\n :return parentPath(str): Path to parent directory of the dataset\n \"\"\"\n _, targetDir, classNames, imSize = [value for key, value in params.items()]\n counter = {}\n labelMap = {}\n filePathMap = {\n 0:{}, \n 1:{}\n }\n classFilePaths = {\n 'train':[], \n 'test':[]\n }\n \n for i, j in zip(range(0,len(classNames)), classNames):\n labelMap[str(i)] = j\n filePathMap[0][str(i)] = ''\n filePathMap[1][str(i)] = ''\n\n #Paths for the directory\n parentPath = os.path.join(targetDir, directory)\n trainPath = os.path.join(parentPath, 'train')\n testPath = os.path.join(parentPath, 'test')\n try:\n os.mkdir(parentPath)\n os.mkdir(trainPath)\n os.mkdir(testPath)\n print(f'Directory \\'{directory}\\' created')\n for elem in classNames:\n fpTrain = os.path.join(trainPath, elem)\n fpTest = os.path.join(testPath, elem)\n classFilePaths['train'].append(fpTrain)\n classFilePaths['test'].append(fpTest)\n os.mkdir(fpTrain)\n os.mkdir(fpTest)\n print(f' {elem} class train/test directories created')\n \n for i, itemTrain, itemTest in zip(range(len(classNames)), classFilePaths['train'], classFilePaths['test']):\n i = str(i)\n filePathMap[0][i] = itemTrain\n filePathMap[1][i] = itemTest\n\n except FileExistsError:\n print(f'{directory} already exists - consider deleting the directory for a clean install!')\n \n numSamples = len(pd.read_csv(file_name))\n test_idx = [random.randint(0, numSamples) for i in range(0, int(numSamples * 0.2))]\n print(f'Unpacking {file_name}...')\n print('Please wait...')\n with open(file_name) as csv_file:\n csv_reader = csv.reader(csv_file)\n\n next(csv_reader)\n fileCount = 0\n for row in csv_reader:\n \n if fileCount % 1000 == 0:\n print(f'Unpacking {fileCount}/{numSamples}...', end = ' ')\n\n pixels = row[:-1] # without label\n pixels = np.array(pixels, dtype='float64')\n pixels = pixels.reshape((imSize, imSize, 3))\n image = Image.fromarray(pixels, 'RGB')\n\n label = row[-1][0]\n\n if label not in counter: counter[label] = 0\n counter[label] += 1\n\n filename = f'{labelMap[label]}{counter[label]}.png'\n\n if fileCount in test_idx:\n filepath = os.path.join(filePathMap[1][label], filename)\n\n else:\n filepath = os.path.join(filePathMap[0][label], filename)\n\n image.save(filepath)\n \n if (fileCount % 999 == 0) and (fileCount != 9): print(f'Completed')\n fileCount += 1\n\n print(f'Unpacking complete. {fileCount} images parsed.')\n \n return parentPath\n\ndef tech_ind_features(data):\n \"\"\"\n Generate technical indicators \n * :param data(pd.DataFrame): Raw data for processing\n \n :return transformed_df(pd.DataFrame): Dataframe of features, sample balanced and normalised\n \"\"\"\n data['smoothed_close'] = data.close.rolling(9).mean().rolling(21).mean().shift(-15)\n data['dx'] = np.diff(data['smoothed_close'], prepend=data['smoothed_close'][0])\n data['dx_signal'] = pd.Series(data['dx']).rolling(9).mean()\n data['ddx'] = np.diff(np.diff(data['smoothed_close']), prepend=data['smoothed_close'][0:2])\n\n data['labels'] = np.zeros(len(data))\n data['labels'].iloc[[(data.ddx < 0.1) & (data.dx <= 0) & (data.dx_signal > 0)]] = 1\n data['labels'].iloc[[(data.ddx > -0.075) & (data.dx >= 0) & (data.dx_signal < 0)]] = 2\n\n #Filter and drop all columns except close price, volume and date (for indexing)\n relevant_cols = list(\n compress(\n data.columns,\n [False if i in [1, 3, 4, 5, 6, len(data.columns)-1] else True for i in range(len(data.columns))]\n )\n )\n\n data = data.drop(columns=relevant_cols).rename(columns={'open_date_time': 'date'})\n data.set_index('date', inplace = True)\n\n #Define relevant periods for lookback/feature engineering\n periods = [\n 9, 14, 21, \n 30, 45, 60,\n 90, 100, 120\n ]\n\n #Construct technical features for image synthesis\n for period in periods:\n data[f'ema_{period}'] = btalib.ema(\n data.close,\n period = period\n ).df['ema']\n data[f'ema_{period}_dx'] = np.append(np.nan, np.diff(btalib.ema(\n data.close,\n period = period\n ).df['ema']))\n data[f'rsi_{period}'] = btalib.rsi(\n data.close,\n period = period\n ).df['rsi']\n data[f'cci_{period}'] = btalib.cci(\n data.high,\n data.low,\n data.close,\n period = period\n ).df['cci']\n data[f'macd_{period}'] = btalib.macd(\n data.close,\n pfast = period,\n pslow = period*2,\n psignal = int(period/3)\n ).df['macd']\n data[f'signal_{period}'] = btalib.macd(\n data.close,\n pfast = period,\n pslow = period*2,\n psignal = int(period/3)\n ).df['signal']\n data[f'hist_{period}'] = btalib.macd(\n data.close,\n pfast = period,\n pslow = period*2,\n psignal = int(period/3)\n ).df['histogram']\n data[f'volume_{period}'] = btalib.sma(\n data.volume,\n period = period\n ).df['sma']\n data[f'change_{period}'] = data.close.pct_change(periods = period)\n\n data = data.drop(data.query('labels == 0').sample(frac=.90).index)\n\n data = data.replace([np.inf, -np.inf], np.nan).dropna()\n\n data_trimmed = data.loc[:, 'ema_9':]\n data_trimmed = pd.concat(\n [data_trimmed, \n data_trimmed.shift(1), \n data_trimmed.shift(2)],\n axis = 1\n )\n\n mm_scaler = MinMaxScaler(feature_range=(0, 1))\n transformed_data = mm_scaler.fit_transform(data_trimmed[24:])\n transformed_data = np.c_[\n transformed_data, \n pd.to_numeric(\n data.labels[24:],\n downcast = 'signed'\n ).to_list()\n ]\n\n return transformed_data"],"string":"[\n \"import pandas as pd\\nimport numpy as np\\nimport datetime as dt\\nimport time, csv, os, itertools, shutil, json, random\\nimport btalib\\n\\nfrom itertools import compress\\nfrom PIL import Image\\n\\nfrom sklearn.preprocessing import MinMaxScaler\\n\\ndef bool_convert(s):\\n \\\"\\\"\\\"\\n Parse string booleans from parameters\\n * :param s(str): String to convert\\n :return s(bool): Boolean type\\n \\\"\\\"\\\"\\n try:\\n if s == \\\"True\\\":\\n return True\\n elif s == \\\"False\\\":\\n return False\\n else:\\n return s\\n except TypeError:\\n return s\\n\\ndef int_convert(s):\\n \\\"\\\"\\\"\\n Parse string int from parameters\\n * :param s(str): String to convert\\n :return s(int): Int type\\n \\\"\\\"\\\"\\n try:\\n return int(s)\\n except ValueError:\\n return s\\n except TypeError:\\n return s\\n \\ndef load_params(filePath, deploy = False):\\n \\\"\\\"\\\"\\n Parse parameters json\\n * :param filePath(str): Location of parameters file\\n * :param deploy(bool): Denotation for whether parameters are being loaded by deployment code\\n\\n :return params(dict): Python dictionary of parameters with correct dtypes\\n \\\"\\\"\\\"\\n with open(filePath) as f:\\n params = json.load(f)\\n if deploy:\\n return params\\n else: \\n for split in ['validDL', 'trainDL']:\\n params['loadingParams'][split]['shuffle'] = bool_convert(params['loadingParams'][split]['shuffle'])\\n\\n for key in params:\\n for subkey in params[key]:\\n if subkey == 'shuffle':\\n params[key][subkey] = bool_convert(params[key][subkey])\\n else:\\n params[key][subkey] = int_convert(params[key][subkey])\\n \\n f.close()\\n return params\\n\\ndef unpack_img_dataset(params, directory, file_name):\\n \\\"\\\"\\\"\\n Unpack an image dataset stored as raw data (csv or otherwise) into .png's. Creates file structure for pytorch loading\\n and handles train/test/validation splitting internally\\n * :param params(dict): Location of parameters file\\n * :param directory(str): Name of directory to check for, or create to store images\\n * :param file_name(str): Name of .csv file of featureset for image creation \\n\\n :return parentPath(str): Path to parent directory of the dataset\\n \\\"\\\"\\\"\\n _, targetDir, classNames, imSize = [value for key, value in params.items()]\\n counter = {}\\n labelMap = {}\\n filePathMap = {\\n 0:{}, \\n 1:{}\\n }\\n classFilePaths = {\\n 'train':[], \\n 'test':[]\\n }\\n \\n for i, j in zip(range(0,len(classNames)), classNames):\\n labelMap[str(i)] = j\\n filePathMap[0][str(i)] = ''\\n filePathMap[1][str(i)] = ''\\n\\n #Paths for the directory\\n parentPath = os.path.join(targetDir, directory)\\n trainPath = os.path.join(parentPath, 'train')\\n testPath = os.path.join(parentPath, 'test')\\n try:\\n os.mkdir(parentPath)\\n os.mkdir(trainPath)\\n os.mkdir(testPath)\\n print(f'Directory \\\\'{directory}\\\\' created')\\n for elem in classNames:\\n fpTrain = os.path.join(trainPath, elem)\\n fpTest = os.path.join(testPath, elem)\\n classFilePaths['train'].append(fpTrain)\\n classFilePaths['test'].append(fpTest)\\n os.mkdir(fpTrain)\\n os.mkdir(fpTest)\\n print(f' {elem} class train/test directories created')\\n \\n for i, itemTrain, itemTest in zip(range(len(classNames)), classFilePaths['train'], classFilePaths['test']):\\n i = str(i)\\n filePathMap[0][i] = itemTrain\\n filePathMap[1][i] = itemTest\\n\\n except FileExistsError:\\n print(f'{directory} already exists - consider deleting the directory for a clean install!')\\n \\n numSamples = len(pd.read_csv(file_name))\\n test_idx = [random.randint(0, numSamples) for i in range(0, int(numSamples * 0.2))]\\n print(f'Unpacking {file_name}...')\\n print('Please wait...')\\n with open(file_name) as csv_file:\\n csv_reader = csv.reader(csv_file)\\n\\n next(csv_reader)\\n fileCount = 0\\n for row in csv_reader:\\n \\n if fileCount % 1000 == 0:\\n print(f'Unpacking {fileCount}/{numSamples}...', end = ' ')\\n\\n pixels = row[:-1] # without label\\n pixels = np.array(pixels, dtype='float64')\\n pixels = pixels.reshape((imSize, imSize, 3))\\n image = Image.fromarray(pixels, 'RGB')\\n\\n label = row[-1][0]\\n\\n if label not in counter: counter[label] = 0\\n counter[label] += 1\\n\\n filename = f'{labelMap[label]}{counter[label]}.png'\\n\\n if fileCount in test_idx:\\n filepath = os.path.join(filePathMap[1][label], filename)\\n\\n else:\\n filepath = os.path.join(filePathMap[0][label], filename)\\n\\n image.save(filepath)\\n \\n if (fileCount % 999 == 0) and (fileCount != 9): print(f'Completed')\\n fileCount += 1\\n\\n print(f'Unpacking complete. {fileCount} images parsed.')\\n \\n return parentPath\\n\\ndef tech_ind_features(data):\\n \\\"\\\"\\\"\\n Generate technical indicators \\n * :param data(pd.DataFrame): Raw data for processing\\n \\n :return transformed_df(pd.DataFrame): Dataframe of features, sample balanced and normalised\\n \\\"\\\"\\\"\\n data['smoothed_close'] = data.close.rolling(9).mean().rolling(21).mean().shift(-15)\\n data['dx'] = np.diff(data['smoothed_close'], prepend=data['smoothed_close'][0])\\n data['dx_signal'] = pd.Series(data['dx']).rolling(9).mean()\\n data['ddx'] = np.diff(np.diff(data['smoothed_close']), prepend=data['smoothed_close'][0:2])\\n\\n data['labels'] = np.zeros(len(data))\\n data['labels'].iloc[[(data.ddx < 0.1) & (data.dx <= 0) & (data.dx_signal > 0)]] = 1\\n data['labels'].iloc[[(data.ddx > -0.075) & (data.dx >= 0) & (data.dx_signal < 0)]] = 2\\n\\n #Filter and drop all columns except close price, volume and date (for indexing)\\n relevant_cols = list(\\n compress(\\n data.columns,\\n [False if i in [1, 3, 4, 5, 6, len(data.columns)-1] else True for i in range(len(data.columns))]\\n )\\n )\\n\\n data = data.drop(columns=relevant_cols).rename(columns={'open_date_time': 'date'})\\n data.set_index('date', inplace = True)\\n\\n #Define relevant periods for lookback/feature engineering\\n periods = [\\n 9, 14, 21, \\n 30, 45, 60,\\n 90, 100, 120\\n ]\\n\\n #Construct technical features for image synthesis\\n for period in periods:\\n data[f'ema_{period}'] = btalib.ema(\\n data.close,\\n period = period\\n ).df['ema']\\n data[f'ema_{period}_dx'] = np.append(np.nan, np.diff(btalib.ema(\\n data.close,\\n period = period\\n ).df['ema']))\\n data[f'rsi_{period}'] = btalib.rsi(\\n data.close,\\n period = period\\n ).df['rsi']\\n data[f'cci_{period}'] = btalib.cci(\\n data.high,\\n data.low,\\n data.close,\\n period = period\\n ).df['cci']\\n data[f'macd_{period}'] = btalib.macd(\\n data.close,\\n pfast = period,\\n pslow = period*2,\\n psignal = int(period/3)\\n ).df['macd']\\n data[f'signal_{period}'] = btalib.macd(\\n data.close,\\n pfast = period,\\n pslow = period*2,\\n psignal = int(period/3)\\n ).df['signal']\\n data[f'hist_{period}'] = btalib.macd(\\n data.close,\\n pfast = period,\\n pslow = period*2,\\n psignal = int(period/3)\\n ).df['histogram']\\n data[f'volume_{period}'] = btalib.sma(\\n data.volume,\\n period = period\\n ).df['sma']\\n data[f'change_{period}'] = data.close.pct_change(periods = period)\\n\\n data = data.drop(data.query('labels == 0').sample(frac=.90).index)\\n\\n data = data.replace([np.inf, -np.inf], np.nan).dropna()\\n\\n data_trimmed = data.loc[:, 'ema_9':]\\n data_trimmed = pd.concat(\\n [data_trimmed, \\n data_trimmed.shift(1), \\n data_trimmed.shift(2)],\\n axis = 1\\n )\\n\\n mm_scaler = MinMaxScaler(feature_range=(0, 1))\\n transformed_data = mm_scaler.fit_transform(data_trimmed[24:])\\n transformed_data = np.c_[\\n transformed_data, \\n pd.to_numeric(\\n data.labels[24:],\\n downcast = 'signed'\\n ).to_list()\\n ]\\n\\n return transformed_data\"\n]"},"apis":{"kind":"list like","value":[["pandas.read_csv","pandas.Series","numpy.diff","numpy.array","pandas.to_numeric","sklearn.preprocessing.MinMaxScaler"]],"string":"[\n [\n \"pandas.read_csv\",\n \"pandas.Series\",\n \"numpy.diff\",\n \"numpy.array\",\n \"pandas.to_numeric\",\n \"sklearn.preprocessing.MinMaxScaler\"\n ]\n]"},"possible_versions":{"kind":"list like","value":[{"matplotlib":[],"numpy":[],"pandas":["2.0","1.4","1.1","1.5","1.2","1.3"],"scipy":[],"tensorflow":[]}],"string":"[\n {\n \"matplotlib\": [],\n \"numpy\": [],\n \"pandas\": [\n \"2.0\",\n \"1.4\",\n \"1.1\",\n \"1.5\",\n \"1.2\",\n \"1.3\"\n ],\n \"scipy\": [],\n \"tensorflow\": []\n }\n]"}}},{"rowIdx":72530,"cells":{"repo_name":{"kind":"string","value":"Mistariano/Deep-Image-Matting"},"hexsha":{"kind":"list like","value":["c7e5516ca4a0729b27410c10ab8a017d92b95bf0"],"string":"[\n \"c7e5516ca4a0729b27410c10ab8a017d92b95bf0\"\n]"},"file_path":{"kind":"list like","value":["demo.py"],"string":"[\n \"demo.py\"\n]"},"code":{"kind":"list like","value":["import math\nimport os\nimport random\n\nimport cv2 as cv\nimport keras.backend as K\nimport numpy as np\n\nfrom data_generator import generate_trimap, random_choice, get_alpha_test\nfrom model import build_encoder_decoder, build_refinement\nfrom utils import compute_mse_loss, compute_sad_loss\nfrom utils import get_final_output, safe_crop, draw_str\n\n\ndef composite4(fg, bg, a, w, h):\n fg = np.array(fg, np.float32)\n bg_h, bg_w = bg.shape[:2]\n x = 0\n if bg_w > w:\n x = np.random.randint(0, bg_w - w)\n y = 0\n if bg_h > h:\n y = np.random.randint(0, bg_h - h)\n bg = np.array(bg[y:y + h, x:x + w], np.float32)\n alpha = np.zeros((h, w, 1), np.float32)\n alpha[:, :, 0] = a / 255.\n im = alpha * fg + (1 - alpha) * bg\n im = im.astype(np.uint8)\n return im, bg\n\n\nif __name__ == '__main__':\n img_rows, img_cols = 320, 320\n channel = 4\n\n pretrained_path = 'models/final.42-0.0398.hdf5'\n encoder_decoder = build_encoder_decoder()\n final = build_refinement(encoder_decoder)\n final.load_weights(pretrained_path)\n print(final.summary())\n\n out_test_path = 'data/merged_test/'\n if not os.path.exists(out_test_path):\n os.makedirs(out_test_path)\n test_images = [f for f in os.listdir(out_test_path) if\n os.path.isfile(os.path.join(out_test_path, f)) and f.endswith('.png')]\n print('test_images:', test_images)\n assert len(test_images) > 0\n samples = random.sample(test_images, min(10, len(test_images)))\n\n bg_test = 'data/bg_test/'\n if not os.path.exists(bg_test):\n os.makedirs(bg_test)\n test_bgs = [f for f in os.listdir(bg_test) if\n os.path.isfile(os.path.join(bg_test, f)) and f.endswith('.png')]\n print('test_bgs:', test_bgs)\n assert len(test_bgs) > 0\n sample_bgs = random.sample(test_bgs, min(10, len(test_bgs)))\n\n total_loss = 0.0\n for i in range(len(samples)):\n filename = samples[i]\n image_name = filename.split('.')[0]\n\n print('\\nStart processing image: {}'.format(filename))\n\n bgr_img = cv.imread(os.path.join(out_test_path, filename))\n bg_h, bg_w = bgr_img.shape[:2]\n print('bg_h, bg_w: ' + str((bg_h, bg_w)))\n\n # a = get_alpha_test(image_name)\n # TODO: fix fucking here\n filename = os.path.join('mask_test', filename)\n filename = os.path.join('data', filename)\n print('mask file name:', filename)\n a = cv.imread(filename, 0)\n\n a_h, a_w = a.shape[:2]\n print('a_h, a_w: ' + str((a_h, a_w)))\n\n alpha = np.zeros((bg_h, bg_w), np.float32)\n alpha[0:a_h, 0:a_w] = a\n trimap = generate_trimap(alpha)\n different_sizes = [(320, 320), (320, 320), (320, 320), (480, 480), (640, 640)]\n crop_size = random.choice(different_sizes)\n x, y = random_choice(trimap, crop_size)\n print('x, y: ' + str((x, y)))\n\n bgr_img = safe_crop(bgr_img, x, y, crop_size)\n alpha = safe_crop(alpha, x, y, crop_size)\n trimap = safe_crop(trimap, x, y, crop_size)\n cv.imwrite('images/{}_image.png'.format(i), np.array(bgr_img).astype(np.uint8))\n cv.imwrite('images/{}_trimap.png'.format(i), np.array(trimap).astype(np.uint8))\n cv.imwrite('images/{}_alpha.png'.format(i), np.array(alpha).astype(np.uint8))\n\n x_test = np.empty((1, img_rows, img_cols, 4), dtype=np.float32)\n x_test[0, :, :, 0:3] = bgr_img / 255.\n x_test[0, :, :, 3] = trimap / 255.\n\n y_true = np.empty((1, img_rows, img_cols, 2), dtype=np.float32)\n y_true[0, :, :, 0] = alpha / 255.\n y_true[0, :, :, 1] = trimap / 255.\n\n y_pred = final.predict(x_test)\n # print('y_pred.shape: ' + str(y_pred.shape))\n\n y_pred = np.reshape(y_pred, (img_rows, img_cols))\n print(y_pred.shape)\n y_pred = y_pred * 255.0\n y_pred = get_final_output(y_pred, trimap)\n y_pred = y_pred.astype(np.uint8)\n\n sad_loss = compute_sad_loss(y_pred, alpha, trimap)\n mse_loss = compute_mse_loss(y_pred, alpha, trimap)\n str_msg = 'sad_loss: %.4f, mse_loss: %.4f, crop_size: %s' % (\n sad_loss, mse_loss, str(crop_size))\n print(str_msg)\n\n out = y_pred.copy()\n draw_str(out, (10, 20), str_msg)\n cv.imwrite('images/{}_out.png'.format(i), out)\n\n sample_bg = sample_bgs[i]\n bg = cv.imread(os.path.join(bg_test, sample_bg))\n bh, bw = bg.shape[:2]\n wratio = img_cols / bw\n hratio = img_rows / bh\n ratio = wratio if wratio > hratio else hratio\n if ratio > 1:\n bg = cv.resize(src=bg, dsize=(math.ceil(bw * ratio), math.ceil(bh * ratio)),\n interpolation=cv.INTER_CUBIC)\n im, bg = composite4(bgr_img, bg, y_pred, img_cols, img_rows)\n cv.imwrite('images/{}_compose.png'.format(i), im)\n cv.imwrite('images/{}_new_bg.png'.format(i), bg)\n\n K.clear_session()\n"],"string":"[\n \"import math\\nimport os\\nimport random\\n\\nimport cv2 as cv\\nimport keras.backend as K\\nimport numpy as np\\n\\nfrom data_generator import generate_trimap, random_choice, get_alpha_test\\nfrom model import build_encoder_decoder, build_refinement\\nfrom utils import compute_mse_loss, compute_sad_loss\\nfrom utils import get_final_output, safe_crop, draw_str\\n\\n\\ndef composite4(fg, bg, a, w, h):\\n fg = np.array(fg, np.float32)\\n bg_h, bg_w = bg.shape[:2]\\n x = 0\\n if bg_w > w:\\n x = np.random.randint(0, bg_w - w)\\n y = 0\\n if bg_h > h:\\n y = np.random.randint(0, bg_h - h)\\n bg = np.array(bg[y:y + h, x:x + w], np.float32)\\n alpha = np.zeros((h, w, 1), np.float32)\\n alpha[:, :, 0] = a / 255.\\n im = alpha * fg + (1 - alpha) * bg\\n im = im.astype(np.uint8)\\n return im, bg\\n\\n\\nif __name__ == '__main__':\\n img_rows, img_cols = 320, 320\\n channel = 4\\n\\n pretrained_path = 'models/final.42-0.0398.hdf5'\\n encoder_decoder = build_encoder_decoder()\\n final = build_refinement(encoder_decoder)\\n final.load_weights(pretrained_path)\\n print(final.summary())\\n\\n out_test_path = 'data/merged_test/'\\n if not os.path.exists(out_test_path):\\n os.makedirs(out_test_path)\\n test_images = [f for f in os.listdir(out_test_path) if\\n os.path.isfile(os.path.join(out_test_path, f)) and f.endswith('.png')]\\n print('test_images:', test_images)\\n assert len(test_images) > 0\\n samples = random.sample(test_images, min(10, len(test_images)))\\n\\n bg_test = 'data/bg_test/'\\n if not os.path.exists(bg_test):\\n os.makedirs(bg_test)\\n test_bgs = [f for f in os.listdir(bg_test) if\\n os.path.isfile(os.path.join(bg_test, f)) and f.endswith('.png')]\\n print('test_bgs:', test_bgs)\\n assert len(test_bgs) > 0\\n sample_bgs = random.sample(test_bgs, min(10, len(test_bgs)))\\n\\n total_loss = 0.0\\n for i in range(len(samples)):\\n filename = samples[i]\\n image_name = filename.split('.')[0]\\n\\n print('\\\\nStart processing image: {}'.format(filename))\\n\\n bgr_img = cv.imread(os.path.join(out_test_path, filename))\\n bg_h, bg_w = bgr_img.shape[:2]\\n print('bg_h, bg_w: ' + str((bg_h, bg_w)))\\n\\n # a = get_alpha_test(image_name)\\n # TODO: fix fucking here\\n filename = os.path.join('mask_test', filename)\\n filename = os.path.join('data', filename)\\n print('mask file name:', filename)\\n a = cv.imread(filename, 0)\\n\\n a_h, a_w = a.shape[:2]\\n print('a_h, a_w: ' + str((a_h, a_w)))\\n\\n alpha = np.zeros((bg_h, bg_w), np.float32)\\n alpha[0:a_h, 0:a_w] = a\\n trimap = generate_trimap(alpha)\\n different_sizes = [(320, 320), (320, 320), (320, 320), (480, 480), (640, 640)]\\n crop_size = random.choice(different_sizes)\\n x, y = random_choice(trimap, crop_size)\\n print('x, y: ' + str((x, y)))\\n\\n bgr_img = safe_crop(bgr_img, x, y, crop_size)\\n alpha = safe_crop(alpha, x, y, crop_size)\\n trimap = safe_crop(trimap, x, y, crop_size)\\n cv.imwrite('images/{}_image.png'.format(i), np.array(bgr_img).astype(np.uint8))\\n cv.imwrite('images/{}_trimap.png'.format(i), np.array(trimap).astype(np.uint8))\\n cv.imwrite('images/{}_alpha.png'.format(i), np.array(alpha).astype(np.uint8))\\n\\n x_test = np.empty((1, img_rows, img_cols, 4), dtype=np.float32)\\n x_test[0, :, :, 0:3] = bgr_img / 255.\\n x_test[0, :, :, 3] = trimap / 255.\\n\\n y_true = np.empty((1, img_rows, img_cols, 2), dtype=np.float32)\\n y_true[0, :, :, 0] = alpha / 255.\\n y_true[0, :, :, 1] = trimap / 255.\\n\\n y_pred = final.predict(x_test)\\n # print('y_pred.shape: ' + str(y_pred.shape))\\n\\n y_pred = np.reshape(y_pred, (img_rows, img_cols))\\n print(y_pred.shape)\\n y_pred = y_pred * 255.0\\n y_pred = get_final_output(y_pred, trimap)\\n y_pred = y_pred.astype(np.uint8)\\n\\n sad_loss = compute_sad_loss(y_pred, alpha, trimap)\\n mse_loss = compute_mse_loss(y_pred, alpha, trimap)\\n str_msg = 'sad_loss: %.4f, mse_loss: %.4f, crop_size: %s' % (\\n sad_loss, mse_loss, str(crop_size))\\n print(str_msg)\\n\\n out = y_pred.copy()\\n draw_str(out, (10, 20), str_msg)\\n cv.imwrite('images/{}_out.png'.format(i), out)\\n\\n sample_bg = sample_bgs[i]\\n bg = cv.imread(os.path.join(bg_test, sample_bg))\\n bh, bw = bg.shape[:2]\\n wratio = img_cols / bw\\n hratio = img_rows / bh\\n ratio = wratio if wratio > hratio else hratio\\n if ratio > 1:\\n bg = cv.resize(src=bg, dsize=(math.ceil(bw * ratio), math.ceil(bh * ratio)),\\n interpolation=cv.INTER_CUBIC)\\n im, bg = composite4(bgr_img, bg, y_pred, img_cols, img_rows)\\n cv.imwrite('images/{}_compose.png'.format(i), im)\\n cv.imwrite('images/{}_new_bg.png'.format(i), bg)\\n\\n K.clear_session()\\n\"\n]"},"apis":{"kind":"list like","value":[["numpy.reshape","numpy.array","numpy.zeros","numpy.empty","numpy.random.randint"]],"string":"[\n [\n \"numpy.reshape\",\n \"numpy.array\",\n \"numpy.zeros\",\n \"numpy.empty\",\n \"numpy.random.randint\"\n ]\n]"},"possible_versions":{"kind":"list like","value":[{"matplotlib":[],"numpy":[],"pandas":[],"scipy":[],"tensorflow":[]}],"string":"[\n {\n \"matplotlib\": [],\n \"numpy\": [],\n \"pandas\": [],\n \"scipy\": [],\n \"tensorflow\": []\n }\n]"}}},{"rowIdx":72531,"cells":{"repo_name":{"kind":"string","value":"georglind/fermihubbard"},"hexsha":{"kind":"list like","value":["d76ad1df6b5ea57abf7b290576bbca4dd5275aeb"],"string":"[\n \"d76ad1df6b5ea57abf7b290576bbca4dd5275aeb\"\n]"},"file_path":{"kind":"list like","value":["example.py"],"string":"[\n \"example.py\"\n]"},"code":{"kind":"list like","value":["from __future__ import division, print_function\nimport numpy as np\nimport lintable as lin\nimport fermihubbard\n\nimport scipy.sparse as sparse\n\n# The model parameters:\n\n# The onsite energies (0)\nH1E = np.zeros((4, 4))\n\n# Hopping on a ring\nH1T = np.zeros((4, 4))\nfor i in xrange(4):\n H1T[i, (i+1) % 4] = -1.\n H1T[(i+1) % 4, i] = -1.\n\n# Only onsite interaction\nH1U = 2*np.eye(4)\n\n# Construc the model\nm = fermihubbard.Model(H1E, H1T, H1U)\n\n# Construct a specific chargestate with eight electrons:\nns4 = m.numbersector(4)\n\n# Consider the sector with net zero spin in the z direction, meaning that\n# 4 electrons = 2 spin-up electrons + 2 spin-down electrons\ns0 = ns4.szsector(0)\n\n# Let us then take a look at the basis. Generate the Lin-table:\nlita = lin.Table(4, 2, 2)\n\n# Print the basis\nprint('Spin-up basis:')\nprint(lita.basisu)\n# Spin-up basis:\n# [[0 0 1 1]\n# [0 1 0 1]\n# [0 1 1 0]\n# [1 0 0 1]\n# [1 0 1 0]\n# [1 1 0 0]]\n\n# Compute the Hamiltonian\n(HTu, HTd, HUd) = s0.hamiltonian\n\n# Print the hopping Hamiltonian for the spin-up electronic systems\nprint('Spin-up hopping:')\nprint(HTu)\n\n# The Total hamiltonian can be generated from these parts.\nNu, Nd = lita.Ns\n\n# The interaction part in sparse format\nHU = sparse.coo_matrix((HUd, (np.arange(Nu*Nd), np.arange(Nu*Nd))), shape=(Nu*Nd, Nu*Nd)).tocsr()\n\n# The kronecker product of the two hopping sectors.\nHT = sparse.kron(np.eye(Nd), HTu, 'dok') + sparse.kron(HTd, np.eye(Nu), 'dok')\n\nprint('The total Hamiltonian:')\nprint(HU + HT)\n"],"string":"[\n \"from __future__ import division, print_function\\nimport numpy as np\\nimport lintable as lin\\nimport fermihubbard\\n\\nimport scipy.sparse as sparse\\n\\n# The model parameters:\\n\\n# The onsite energies (0)\\nH1E = np.zeros((4, 4))\\n\\n# Hopping on a ring\\nH1T = np.zeros((4, 4))\\nfor i in xrange(4):\\n H1T[i, (i+1) % 4] = -1.\\n H1T[(i+1) % 4, i] = -1.\\n\\n# Only onsite interaction\\nH1U = 2*np.eye(4)\\n\\n# Construc the model\\nm = fermihubbard.Model(H1E, H1T, H1U)\\n\\n# Construct a specific chargestate with eight electrons:\\nns4 = m.numbersector(4)\\n\\n# Consider the sector with net zero spin in the z direction, meaning that\\n# 4 electrons = 2 spin-up electrons + 2 spin-down electrons\\ns0 = ns4.szsector(0)\\n\\n# Let us then take a look at the basis. Generate the Lin-table:\\nlita = lin.Table(4, 2, 2)\\n\\n# Print the basis\\nprint('Spin-up basis:')\\nprint(lita.basisu)\\n# Spin-up basis:\\n# [[0 0 1 1]\\n# [0 1 0 1]\\n# [0 1 1 0]\\n# [1 0 0 1]\\n# [1 0 1 0]\\n# [1 1 0 0]]\\n\\n# Compute the Hamiltonian\\n(HTu, HTd, HUd) = s0.hamiltonian\\n\\n# Print the hopping Hamiltonian for the spin-up electronic systems\\nprint('Spin-up hopping:')\\nprint(HTu)\\n\\n# The Total hamiltonian can be generated from these parts.\\nNu, Nd = lita.Ns\\n\\n# The interaction part in sparse format\\nHU = sparse.coo_matrix((HUd, (np.arange(Nu*Nd), np.arange(Nu*Nd))), shape=(Nu*Nd, Nu*Nd)).tocsr()\\n\\n# The kronecker product of the two hopping sectors.\\nHT = sparse.kron(np.eye(Nd), HTu, 'dok') + sparse.kron(HTd, np.eye(Nu), 'dok')\\n\\nprint('The total Hamiltonian:')\\nprint(HU + HT)\\n\"\n]"},"apis":{"kind":"list like","value":[["numpy.arange","numpy.eye","numpy.zeros"]],"string":"[\n [\n \"numpy.arange\",\n \"numpy.eye\",\n \"numpy.zeros\"\n ]\n]"},"possible_versions":{"kind":"list like","value":[{"matplotlib":[],"numpy":[],"pandas":[],"scipy":[],"tensorflow":[]}],"string":"[\n {\n \"matplotlib\": [],\n \"numpy\": [],\n \"pandas\": [],\n \"scipy\": [],\n \"tensorflow\": []\n }\n]"}}},{"rowIdx":72532,"cells":{"repo_name":{"kind":"string","value":"SkyfengBiuBiu/pytorch-detect-to-track_1"},"hexsha":{"kind":"list like","value":["afdfdf505deca4506ebc594ec0c2eb032a2a5569"],"string":"[\n \"afdfdf505deca4506ebc594ec0c2eb032a2a5569\"\n]"},"file_path":{"kind":"list like","value":["lib/model/correlation/build.py"],"string":"[\n \"lib/model/correlation/build.py\"\n]"},"code":{"kind":"list like","value":["import os\nimport torch\nimport torch.utils.ffi\n\nstrBasepath = os.path.split(os.path.abspath(__file__))[0] + '/'\nstrHeaders = []\nstrSources = []\nstrDefines = []\nstrObjects = []\n\nif torch.cuda.is_available() == True:\n strHeaders += ['src/correlation_cuda.h']\n strSources += ['src/correlation_cuda.c']\n strDefines += [('WITH_CUDA', None)]\n strObjects += ['src/correlation_cuda_kernel.o']\n\nffi = torch.utils.ffi.create_extension(\n name='_ext.correlation',\n headers=strHeaders,\n sources=strSources,\n verbose=False,\n with_cuda=any(strDefine[0] == 'WITH_CUDA' for strDefine in strDefines),\n package=False,\n relative_to=strBasepath,\n include_dirs=[os.path.expandvars('$CUDA_HOME') + '/include'],\n define_macros=strDefines,\n extra_objects=[os.path.join(strBasepath, strObject) for strObject in strObjects]\n)\n\nif __name__ == '__main__':\n ffi.build()"],"string":"[\n \"import os\\nimport torch\\nimport torch.utils.ffi\\n\\nstrBasepath = os.path.split(os.path.abspath(__file__))[0] + '/'\\nstrHeaders = []\\nstrSources = []\\nstrDefines = []\\nstrObjects = []\\n\\nif torch.cuda.is_available() == True:\\n strHeaders += ['src/correlation_cuda.h']\\n strSources += ['src/correlation_cuda.c']\\n strDefines += [('WITH_CUDA', None)]\\n strObjects += ['src/correlation_cuda_kernel.o']\\n\\nffi = torch.utils.ffi.create_extension(\\n name='_ext.correlation',\\n headers=strHeaders,\\n sources=strSources,\\n verbose=False,\\n with_cuda=any(strDefine[0] == 'WITH_CUDA' for strDefine in strDefines),\\n package=False,\\n relative_to=strBasepath,\\n include_dirs=[os.path.expandvars('$CUDA_HOME') + '/include'],\\n define_macros=strDefines,\\n extra_objects=[os.path.join(strBasepath, strObject) for strObject in strObjects]\\n)\\n\\nif __name__ == '__main__':\\n ffi.build()\"\n]"},"apis":{"kind":"list like","value":[["torch.cuda.is_available"]],"string":"[\n [\n \"torch.cuda.is_available\"\n ]\n]"},"possible_versions":{"kind":"list like","value":[{"matplotlib":[],"numpy":[],"pandas":[],"scipy":[],"tensorflow":[]}],"string":"[\n {\n \"matplotlib\": [],\n \"numpy\": [],\n \"pandas\": [],\n \"scipy\": [],\n \"tensorflow\": []\n }\n]"}}},{"rowIdx":72533,"cells":{"repo_name":{"kind":"string","value":"MolecularAI/pysmilesutils"},"hexsha":{"kind":"list like","value":["9fadf5c34fb21d50cf79e56a3ed1033e4d5015e5"],"string":"[\n \"9fadf5c34fb21d50cf79e56a3ed1033e4d5015e5\"\n]"},"file_path":{"kind":"list like","value":["examples/examples_data.py"],"string":"[\n \"examples/examples_data.py\"\n]"},"code":{"kind":"list like","value":["\n# %%\n# %load_ext autoreload\n# %autoreload 2\n\nimport torch\nimport h5py\nimport time\n\nfrom torch.utils.data import Dataset, TensorDataset, DataLoader\nfrom pysmilesutils.datautils import BlockDataLoader, BucketBatchSampler, MultiDataset\n\nfrom tqdm.notebook import tqdm\n\n\n# %% [markdown]\n# # `BlockDataLoader`\n\n# %% [markdown]\n# Det `BlockDataLoader` is used to split the data loading into two parts: first loading blocks, and then drawing batches from thse blocks. This can be usefull when datasets are very large and don't fit into memory.\n#\n# As an example lets look at data in the form of a single `torch.Tensor`. We use `BlockDataLoader` to load this in blocks of size `10`, from which we draw batches of size `5`.\n\n# %%\nclass TestDataset(Dataset):\n data = torch.arange(20)\n \n def __getitem__(self, idx):\n return self.data[idx]\n \n def __len__(self):\n return len(self.data)\n\n\ndataset = TestDataset()\n \ndataloader = BlockDataLoader(dataset, batch_size=5, block_size=10)\n\nfor batch in dataloader:\n print(batch)\n\n\n# %% [markdown]\n# Note that all elements in a batch come from the same block, i.e., the numbers 0 through 9 are not mixed with the numbers 10 through 19.\n#\n# This is of course just a small example, and does not illstrate the real benefit of the `BlockDataLoader`. Lets instead look at an example with a larger dataset, stored on disk.\n\n# %%\nclass HDFDataset(Dataset):\n \"\"\"Small `Dataset` for loading HDF data.\"\"\"\n def __init__(self, path):\n self.path = path\n \n def __len__(self):\n with h5py.File(self.path, \"r\") as f:\n num = len(f.get(\"tensor_data\"))\n return num\n \n def __getitem__(self, idx):\n with h5py.File(self.path, \"r\") as f:\n data = f.get(\"tensor_data\")[idx]\n return data\n \n\nhdf_dataset = HDFDataset(\"data/data.hdf5\")\n\n# %% [markdown]\n# Here we have created a dataset that loads tensor data stored in a HDF5 file. The file, `\"data.hdf5\"`, contains 1 million integer, 0 through 999999. Lets compare data loading using a block loader, and a torch dataloader. Below we load the entire dataset to memory for comparison.\n\n# %%\nwith h5py.File(\"data/data.hdf5\", \"r\") as f:\n # Loaded data with `h5py` is numpy arrays, we convert to torch tensors\n data_h5py = torch.tensor(f.get(\"tensor_data\")[:])\n \ndata_h5py[:15]\n\n# %% [markdown]\n# Below we calculate the time it takes to load and shuffle the dataset using the `BlockDataLoader`. We also make sure that data is shuffled, and that all data is loaded. Note that we load data in blocksof 50000 samples. This means that we only shuffle batches within blocks of this size.\n\n# %%\nblock_dataloader = BlockDataLoader(dataset=hdf_dataset, block_size=50000, batch_size=500)\n\ndata = []\n\nfor batch in tqdm(block_dataloader):\n data.extend(batch.tolist())\n\n# Loaded data that has been shuffled\nprint(torch.equal(data_h5py, torch.tensor(data)))\n# Loaded data that has been sorted\nprint(torch.equal(data_h5py, torch.tensor(sorted(data))))\n\n# %%\ndataloader = DataLoader(dataset=hdf_dataset, batch_size=500)\n\nt = time.time()\n\nfor batch in tqdm(dataloader):\n pass\n\n# %% [markdown]\n# The time to load all batches using the `DataLoader` is significantly longer.\n\n# %% [markdown]\n# The `BlockDataLoader` receives several arguments which can alter its behaviour.\n\n# %%\ndataloader = BlockDataLoader(\n dataset=dataset,\n block_size=13,\n batch_size=4,\n drop_last_block=False,\n drop_last_batch=True,\n shuffle=False,\n)\n\nfor batch in dataloader:\n print(batch)\n\n# %% [markdown]\n# Depending on how data is stored the default functions in `BlockDataLoader` might not be able to properly retrieve slices. In this case the user needs to specify the `_accessitem` and `_accesslen`.\n\n# %% [markdown]\n# # `BucketBatchSampler`\n\n# %% [markdown]\n# The `BucketBatchSampler` can be used to bucket items in the training set. This could, for example, be to make sure samples of similar length are passed to the model.\n\n# %%\n# random data of differentlenths\ndata = [\n torch.arange(torch.randint(1, 5, size=(1,)).item())\n for _ in range(20)\n]\n\n\nclass WrapperDataset(Dataset):\n def __init__(self, data):\n self.data = data\n \n def __getitem__(self, idx):\n return self.data[idx]\n \n def __len__(self):\n return len(self.data)\n \n\ndef collate(data):\n return data\n\n\ndataset = WrapperDataset(data)\n\n_, sorted_indices = torch.sort(torch.tensor([len(d) for d in data]))\nbucket_sampler = BucketBatchSampler(\n data,\n batch_size=3,\n num_buckets=3,\n indices=sorted_indices,\n drop_last=True,\n)\n\ndataloader = DataLoader(\n dataset,\n batch_sampler=bucket_sampler,\n collate_fn=lambda x: x, # needed to not put batches into tensors\n)\n\nfor batch in dataloader:\n print(batch)\n\n# %% [markdown]\n# Note that in each batch the tensors are of similar length\n\n# %% [markdown]\n# # `MultiDataset`\n\n# %% [markdown]\n# The `MultiDataset` can be used to iterate through different datasets each epoch. This can be usefull when a lot of data is present. As a dummy example let us look at a set of torch tensors.\n\n# %%\n# each list in the element represents one dataset\ndata_list = [\n torch.arange(start=(5 * idx), end=(5 * (idx + 1)))\n for idx in range(4)\n]\n\ndataset = MultiDataset(data_list, repeats=False, shuffle=False)\n\nfor _ in range(dataset.num_steps):\n print(dataset[:])\n dataset.step()\n\n# %% [markdown]\n# Here we used the `step` function to iterate through the different datasets. We could also use the multi dataset as an iterator\n\n# %%\nfor _ in dataset:\n print(dataset[:])\n\n# %% [markdown]\n# We can also repeat data, to allow for an arbitrary number of epochs.\n\n# %%\ndataset = MultiDataset(data_list, repeats=True, shuffle=False)\n\nnum_epochs = 10\n\nfor _ in range(num_epochs):\n print(dataset[:])\n dataset.step()\n\n# %% [markdown]\n# We can also shuffle the dataset order, with our without repeats.\n\n# %%\ndataset = MultiDataset(data_list, repeats=False, shuffle=True)\n\nfor _ in dataset:\n print(dataset[:])\n\n# %%\ndataset = MultiDataset(data_list, repeats=True, shuffle=True)\n \nfor _ in range(num_epochs):\n print(dataset[:])\n dataset.step()\n\n# %%\n\n# %%\n"],"string":"[\n \"\\n# %%\\n# %load_ext autoreload\\n# %autoreload 2\\n\\nimport torch\\nimport h5py\\nimport time\\n\\nfrom torch.utils.data import Dataset, TensorDataset, DataLoader\\nfrom pysmilesutils.datautils import BlockDataLoader, BucketBatchSampler, MultiDataset\\n\\nfrom tqdm.notebook import tqdm\\n\\n\\n# %% [markdown]\\n# # `BlockDataLoader`\\n\\n# %% [markdown]\\n# Det `BlockDataLoader` is used to split the data loading into two parts: first loading blocks, and then drawing batches from thse blocks. This can be usefull when datasets are very large and don't fit into memory.\\n#\\n# As an example lets look at data in the form of a single `torch.Tensor`. We use `BlockDataLoader` to load this in blocks of size `10`, from which we draw batches of size `5`.\\n\\n# %%\\nclass TestDataset(Dataset):\\n data = torch.arange(20)\\n \\n def __getitem__(self, idx):\\n return self.data[idx]\\n \\n def __len__(self):\\n return len(self.data)\\n\\n\\ndataset = TestDataset()\\n \\ndataloader = BlockDataLoader(dataset, batch_size=5, block_size=10)\\n\\nfor batch in dataloader:\\n print(batch)\\n\\n\\n# %% [markdown]\\n# Note that all elements in a batch come from the same block, i.e., the numbers 0 through 9 are not mixed with the numbers 10 through 19.\\n#\\n# This is of course just a small example, and does not illstrate the real benefit of the `BlockDataLoader`. Lets instead look at an example with a larger dataset, stored on disk.\\n\\n# %%\\nclass HDFDataset(Dataset):\\n \\\"\\\"\\\"Small `Dataset` for loading HDF data.\\\"\\\"\\\"\\n def __init__(self, path):\\n self.path = path\\n \\n def __len__(self):\\n with h5py.File(self.path, \\\"r\\\") as f:\\n num = len(f.get(\\\"tensor_data\\\"))\\n return num\\n \\n def __getitem__(self, idx):\\n with h5py.File(self.path, \\\"r\\\") as f:\\n data = f.get(\\\"tensor_data\\\")[idx]\\n return data\\n \\n\\nhdf_dataset = HDFDataset(\\\"data/data.hdf5\\\")\\n\\n# %% [markdown]\\n# Here we have created a dataset that loads tensor data stored in a HDF5 file. The file, `\\\"data.hdf5\\\"`, contains 1 million integer, 0 through 999999. Lets compare data loading using a block loader, and a torch dataloader. Below we load the entire dataset to memory for comparison.\\n\\n# %%\\nwith h5py.File(\\\"data/data.hdf5\\\", \\\"r\\\") as f:\\n # Loaded data with `h5py` is numpy arrays, we convert to torch tensors\\n data_h5py = torch.tensor(f.get(\\\"tensor_data\\\")[:])\\n \\ndata_h5py[:15]\\n\\n# %% [markdown]\\n# Below we calculate the time it takes to load and shuffle the dataset using the `BlockDataLoader`. We also make sure that data is shuffled, and that all data is loaded. Note that we load data in blocksof 50000 samples. This means that we only shuffle batches within blocks of this size.\\n\\n# %%\\nblock_dataloader = BlockDataLoader(dataset=hdf_dataset, block_size=50000, batch_size=500)\\n\\ndata = []\\n\\nfor batch in tqdm(block_dataloader):\\n data.extend(batch.tolist())\\n\\n# Loaded data that has been shuffled\\nprint(torch.equal(data_h5py, torch.tensor(data)))\\n# Loaded data that has been sorted\\nprint(torch.equal(data_h5py, torch.tensor(sorted(data))))\\n\\n# %%\\ndataloader = DataLoader(dataset=hdf_dataset, batch_size=500)\\n\\nt = time.time()\\n\\nfor batch in tqdm(dataloader):\\n pass\\n\\n# %% [markdown]\\n# The time to load all batches using the `DataLoader` is significantly longer.\\n\\n# %% [markdown]\\n# The `BlockDataLoader` receives several arguments which can alter its behaviour.\\n\\n# %%\\ndataloader = BlockDataLoader(\\n dataset=dataset,\\n block_size=13,\\n batch_size=4,\\n drop_last_block=False,\\n drop_last_batch=True,\\n shuffle=False,\\n)\\n\\nfor batch in dataloader:\\n print(batch)\\n\\n# %% [markdown]\\n# Depending on how data is stored the default functions in `BlockDataLoader` might not be able to properly retrieve slices. In this case the user needs to specify the `_accessitem` and `_accesslen`.\\n\\n# %% [markdown]\\n# # `BucketBatchSampler`\\n\\n# %% [markdown]\\n# The `BucketBatchSampler` can be used to bucket items in the training set. This could, for example, be to make sure samples of similar length are passed to the model.\\n\\n# %%\\n# random data of differentlenths\\ndata = [\\n torch.arange(torch.randint(1, 5, size=(1,)).item())\\n for _ in range(20)\\n]\\n\\n\\nclass WrapperDataset(Dataset):\\n def __init__(self, data):\\n self.data = data\\n \\n def __getitem__(self, idx):\\n return self.data[idx]\\n \\n def __len__(self):\\n return len(self.data)\\n \\n\\ndef collate(data):\\n return data\\n\\n\\ndataset = WrapperDataset(data)\\n\\n_, sorted_indices = torch.sort(torch.tensor([len(d) for d in data]))\\nbucket_sampler = BucketBatchSampler(\\n data,\\n batch_size=3,\\n num_buckets=3,\\n indices=sorted_indices,\\n drop_last=True,\\n)\\n\\ndataloader = DataLoader(\\n dataset,\\n batch_sampler=bucket_sampler,\\n collate_fn=lambda x: x, # needed to not put batches into tensors\\n)\\n\\nfor batch in dataloader:\\n print(batch)\\n\\n# %% [markdown]\\n# Note that in each batch the tensors are of similar length\\n\\n# %% [markdown]\\n# # `MultiDataset`\\n\\n# %% [markdown]\\n# The `MultiDataset` can be used to iterate through different datasets each epoch. This can be usefull when a lot of data is present. As a dummy example let us look at a set of torch tensors.\\n\\n# %%\\n# each list in the element represents one dataset\\ndata_list = [\\n torch.arange(start=(5 * idx), end=(5 * (idx + 1)))\\n for idx in range(4)\\n]\\n\\ndataset = MultiDataset(data_list, repeats=False, shuffle=False)\\n\\nfor _ in range(dataset.num_steps):\\n print(dataset[:])\\n dataset.step()\\n\\n# %% [markdown]\\n# Here we used the `step` function to iterate through the different datasets. We could also use the multi dataset as an iterator\\n\\n# %%\\nfor _ in dataset:\\n print(dataset[:])\\n\\n# %% [markdown]\\n# We can also repeat data, to allow for an arbitrary number of epochs.\\n\\n# %%\\ndataset = MultiDataset(data_list, repeats=True, shuffle=False)\\n\\nnum_epochs = 10\\n\\nfor _ in range(num_epochs):\\n print(dataset[:])\\n dataset.step()\\n\\n# %% [markdown]\\n# We can also shuffle the dataset order, with our without repeats.\\n\\n# %%\\ndataset = MultiDataset(data_list, repeats=False, shuffle=True)\\n\\nfor _ in dataset:\\n print(dataset[:])\\n\\n# %%\\ndataset = MultiDataset(data_list, repeats=True, shuffle=True)\\n \\nfor _ in range(num_epochs):\\n print(dataset[:])\\n dataset.step()\\n\\n# %%\\n\\n# %%\\n\"\n]"},"apis":{"kind":"list like","value":[["torch.tensor","torch.utils.data.DataLoader","torch.randint","torch.arange"]],"string":"[\n [\n \"torch.tensor\",\n \"torch.utils.data.DataLoader\",\n \"torch.randint\",\n \"torch.arange\"\n ]\n]"},"possible_versions":{"kind":"list like","value":[{"matplotlib":[],"numpy":[],"pandas":[],"scipy":[],"tensorflow":[]}],"string":"[\n {\n \"matplotlib\": [],\n \"numpy\": [],\n \"pandas\": [],\n \"scipy\": [],\n \"tensorflow\": []\n }\n]"}}},{"rowIdx":72534,"cells":{"repo_name":{"kind":"string","value":"boschresearch/blackboxopt"},"hexsha":{"kind":"list like","value":["85abea86f01a4a9d50f05d15e7d850e3288baafd"],"string":"[\n \"85abea86f01a4a9d50f05d15e7d850e3288baafd\"\n]"},"file_path":{"kind":"list like","value":["blackboxopt/optimizers/staged/iteration.py"],"string":"[\n \"blackboxopt/optimizers/staged/iteration.py\"\n]"},"code":{"kind":"list like","value":["# Copyright (c) 2020 - for information on the respective copyright owner\n# see the NOTICE file and/or the repository https://github.com/boschresearch/blackboxopt\n#\n# SPDX-License-Identifier: Apache-2.0\n\nimport copy\nimport logging\nfrom dataclasses import dataclass\nfrom typing import Callable, Dict, List, Optional, Tuple\nfrom uuid import UUID, uuid4\n\nimport numpy as np\n\nfrom blackboxopt import Evaluation, EvaluationSpecification, Objective\nfrom blackboxopt.optimizers.staged.configuration_sampler import (\n StagedIterationConfigurationSampler,\n)\n\n\n@dataclass\nclass Datum:\n \"\"\"Small container for bookkeeping only.\"\"\"\n\n config_key: Tuple[int, int, int]\n status: str\n loss: float = float(\"NaN\")\n\n\nclass StagedIteration:\n def __init__(\n self,\n iteration: int,\n num_configs: List[int],\n fidelities: List[float],\n config_sampler: StagedIterationConfigurationSampler,\n config_promotion_function: Callable,\n objective: Objective,\n logger: logging.Logger = None,\n ):\n \"\"\"Base class for iterations that compare configurations at different\n fidelities and race them as in SuccessiveHalving or Hyperband.\n\n Args:\n iteration: Index of this iteration.\n num_configs: Number of configurations in each stage.\n fidelities: The fidelity for each stage. Must have the same length as\n `num_configs'.\n config_sampler: Configuration Sampler object that suggests a new\n configuration for evaluation given a fidelity.\n config_promotion_function: Function that decides which configurations are\n promoted. Check\n `blackboxopt.optimizers.utils.staged_iteration.greedy_promotion` for\n the signature.\n objective: The objective of the optimization.\n logger: A standard logger to which some debug output might be written.\n \"\"\"\n assert len(fidelities) == len(\n num_configs\n ), \"Please specify the number of configuration and the fidelities.\"\n self.logger = logging.getLogger(\"blackboxopt\") if logger is None else logger\n self.iteration = iteration\n self.fidelities = fidelities\n self.num_configs = num_configs\n self.config_sampler = config_sampler\n self.config_promotion_function = config_promotion_function\n self.objective = objective\n self.current_stage = 0\n self.evaluation_data: List[List[Datum]] = [[]]\n self.eval_specs: Dict[Tuple[int, int, int], EvaluationSpecification] = {}\n self.pending_evaluations: Dict[UUID, int] = {}\n self.finished = False\n\n def generate_evaluation_specification(self) -> Optional[EvaluationSpecification]:\n \"\"\"Pick the next evaluation specification with a budget i.e. fidelity to run.\n\n Returns:\n [description]\n \"\"\"\n if self.finished:\n return None\n\n # try to find a queued entry first\n for i, d in enumerate(self.evaluation_data[self.current_stage]):\n if d.status == \"QUEUED\":\n es = copy.deepcopy(self.eval_specs[d.config_key])\n es.settings[\"fidelity\"] = self.fidelities[self.current_stage]\n d.status = \"RUNNING\"\n self.pending_evaluations[es.optimizer_info[\"id\"]] = i\n return es\n\n # sample a new configuration if there are empty slots to be filled\n if (\n len(self.evaluation_data[self.current_stage])\n < self.num_configs[self.current_stage]\n ):\n conf_key = (\n self.iteration,\n self.current_stage,\n len(self.evaluation_data[self.current_stage]),\n )\n conf, opt_info = self.config_sampler.sample_configuration()\n opt_info.update({\"configuration_key\": conf_key, \"id\": str(uuid4())})\n self.eval_specs[conf_key] = EvaluationSpecification(\n configuration=conf, settings={}, optimizer_info=opt_info\n )\n self.evaluation_data[self.current_stage].append(Datum(conf_key, \"QUEUED\"))\n # To understand recursion, you first must understand recursion :)\n return self.generate_evaluation_specification()\n\n # at this point there are pending evaluations and this iteration has to wait\n return None\n\n def digest_evaluation(\n self, evaluation_specificiation_id: UUID, evaluation: Evaluation\n ):\n \"\"\"Registers the result of an evaluation.\n\n Args:\n id: [description]\n evaluation: [description]\n \"\"\"\n self.config_sampler.digest_evaluation(evaluation)\n i = self.pending_evaluations.pop(evaluation_specificiation_id)\n d = self.evaluation_data[self.current_stage][i]\n d.status = \"FINISHED\" if not evaluation.all_objectives_none else \"CRASHED\"\n objective_value = evaluation.objectives[self.objective.name]\n if objective_value is not None:\n d.loss = (\n -objective_value\n if self.objective.greater_is_better\n else objective_value\n )\n\n # quick check if all configurations have finished yet\n if len(self.evaluation_data[self.current_stage]) == self.num_configs[\n self.current_stage\n ] and all(\n [\n e.status in [\"FINISHED\", \"CRASHED\"]\n for e in self.evaluation_data[self.current_stage]\n ]\n ):\n self._progress_to_next_stage()\n\n def _progress_to_next_stage(self):\n \"\"\"Implements logic to promote configurations to the next stage.\"\"\"\n # filter out crashed configurations\n data = [\n d for d in self.evaluation_data[self.current_stage] if np.isfinite(d.loss)\n ]\n self.current_stage += 1\n if self.current_stage == len(self.num_configs):\n self.finished = True\n return\n\n config_keys = self.config_promotion_function(\n data, self.num_configs[self.current_stage]\n )\n self.logger.debug(\n \"Iteration %i: Advancing configurations %s to stage %i.\",\n self.iteration,\n str(config_keys),\n self.current_stage,\n )\n self.evaluation_data.append(\n [Datum(config_key, \"QUEUED\") for config_key in config_keys]\n )\n"],"string":"[\n \"# Copyright (c) 2020 - for information on the respective copyright owner\\n# see the NOTICE file and/or the repository https://github.com/boschresearch/blackboxopt\\n#\\n# SPDX-License-Identifier: Apache-2.0\\n\\nimport copy\\nimport logging\\nfrom dataclasses import dataclass\\nfrom typing import Callable, Dict, List, Optional, Tuple\\nfrom uuid import UUID, uuid4\\n\\nimport numpy as np\\n\\nfrom blackboxopt import Evaluation, EvaluationSpecification, Objective\\nfrom blackboxopt.optimizers.staged.configuration_sampler import (\\n StagedIterationConfigurationSampler,\\n)\\n\\n\\n@dataclass\\nclass Datum:\\n \\\"\\\"\\\"Small container for bookkeeping only.\\\"\\\"\\\"\\n\\n config_key: Tuple[int, int, int]\\n status: str\\n loss: float = float(\\\"NaN\\\")\\n\\n\\nclass StagedIteration:\\n def __init__(\\n self,\\n iteration: int,\\n num_configs: List[int],\\n fidelities: List[float],\\n config_sampler: StagedIterationConfigurationSampler,\\n config_promotion_function: Callable,\\n objective: Objective,\\n logger: logging.Logger = None,\\n ):\\n \\\"\\\"\\\"Base class for iterations that compare configurations at different\\n fidelities and race them as in SuccessiveHalving or Hyperband.\\n\\n Args:\\n iteration: Index of this iteration.\\n num_configs: Number of configurations in each stage.\\n fidelities: The fidelity for each stage. Must have the same length as\\n `num_configs'.\\n config_sampler: Configuration Sampler object that suggests a new\\n configuration for evaluation given a fidelity.\\n config_promotion_function: Function that decides which configurations are\\n promoted. Check\\n `blackboxopt.optimizers.utils.staged_iteration.greedy_promotion` for\\n the signature.\\n objective: The objective of the optimization.\\n logger: A standard logger to which some debug output might be written.\\n \\\"\\\"\\\"\\n assert len(fidelities) == len(\\n num_configs\\n ), \\\"Please specify the number of configuration and the fidelities.\\\"\\n self.logger = logging.getLogger(\\\"blackboxopt\\\") if logger is None else logger\\n self.iteration = iteration\\n self.fidelities = fidelities\\n self.num_configs = num_configs\\n self.config_sampler = config_sampler\\n self.config_promotion_function = config_promotion_function\\n self.objective = objective\\n self.current_stage = 0\\n self.evaluation_data: List[List[Datum]] = [[]]\\n self.eval_specs: Dict[Tuple[int, int, int], EvaluationSpecification] = {}\\n self.pending_evaluations: Dict[UUID, int] = {}\\n self.finished = False\\n\\n def generate_evaluation_specification(self) -> Optional[EvaluationSpecification]:\\n \\\"\\\"\\\"Pick the next evaluation specification with a budget i.e. fidelity to run.\\n\\n Returns:\\n [description]\\n \\\"\\\"\\\"\\n if self.finished:\\n return None\\n\\n # try to find a queued entry first\\n for i, d in enumerate(self.evaluation_data[self.current_stage]):\\n if d.status == \\\"QUEUED\\\":\\n es = copy.deepcopy(self.eval_specs[d.config_key])\\n es.settings[\\\"fidelity\\\"] = self.fidelities[self.current_stage]\\n d.status = \\\"RUNNING\\\"\\n self.pending_evaluations[es.optimizer_info[\\\"id\\\"]] = i\\n return es\\n\\n # sample a new configuration if there are empty slots to be filled\\n if (\\n len(self.evaluation_data[self.current_stage])\\n < self.num_configs[self.current_stage]\\n ):\\n conf_key = (\\n self.iteration,\\n self.current_stage,\\n len(self.evaluation_data[self.current_stage]),\\n )\\n conf, opt_info = self.config_sampler.sample_configuration()\\n opt_info.update({\\\"configuration_key\\\": conf_key, \\\"id\\\": str(uuid4())})\\n self.eval_specs[conf_key] = EvaluationSpecification(\\n configuration=conf, settings={}, optimizer_info=opt_info\\n )\\n self.evaluation_data[self.current_stage].append(Datum(conf_key, \\\"QUEUED\\\"))\\n # To understand recursion, you first must understand recursion :)\\n return self.generate_evaluation_specification()\\n\\n # at this point there are pending evaluations and this iteration has to wait\\n return None\\n\\n def digest_evaluation(\\n self, evaluation_specificiation_id: UUID, evaluation: Evaluation\\n ):\\n \\\"\\\"\\\"Registers the result of an evaluation.\\n\\n Args:\\n id: [description]\\n evaluation: [description]\\n \\\"\\\"\\\"\\n self.config_sampler.digest_evaluation(evaluation)\\n i = self.pending_evaluations.pop(evaluation_specificiation_id)\\n d = self.evaluation_data[self.current_stage][i]\\n d.status = \\\"FINISHED\\\" if not evaluation.all_objectives_none else \\\"CRASHED\\\"\\n objective_value = evaluation.objectives[self.objective.name]\\n if objective_value is not None:\\n d.loss = (\\n -objective_value\\n if self.objective.greater_is_better\\n else objective_value\\n )\\n\\n # quick check if all configurations have finished yet\\n if len(self.evaluation_data[self.current_stage]) == self.num_configs[\\n self.current_stage\\n ] and all(\\n [\\n e.status in [\\\"FINISHED\\\", \\\"CRASHED\\\"]\\n for e in self.evaluation_data[self.current_stage]\\n ]\\n ):\\n self._progress_to_next_stage()\\n\\n def _progress_to_next_stage(self):\\n \\\"\\\"\\\"Implements logic to promote configurations to the next stage.\\\"\\\"\\\"\\n # filter out crashed configurations\\n data = [\\n d for d in self.evaluation_data[self.current_stage] if np.isfinite(d.loss)\\n ]\\n self.current_stage += 1\\n if self.current_stage == len(self.num_configs):\\n self.finished = True\\n return\\n\\n config_keys = self.config_promotion_function(\\n data, self.num_configs[self.current_stage]\\n )\\n self.logger.debug(\\n \\\"Iteration %i: Advancing configurations %s to stage %i.\\\",\\n self.iteration,\\n str(config_keys),\\n self.current_stage,\\n )\\n self.evaluation_data.append(\\n [Datum(config_key, \\\"QUEUED\\\") for config_key in config_keys]\\n )\\n\"\n]"},"apis":{"kind":"list like","value":[["numpy.isfinite"]],"string":"[\n [\n \"numpy.isfinite\"\n ]\n]"},"possible_versions":{"kind":"list like","value":[{"matplotlib":[],"numpy":[],"pandas":[],"scipy":[],"tensorflow":[]}],"string":"[\n {\n \"matplotlib\": [],\n \"numpy\": [],\n \"pandas\": [],\n \"scipy\": [],\n \"tensorflow\": []\n }\n]"}}},{"rowIdx":72535,"cells":{"repo_name":{"kind":"string","value":"vijoin/ibis"},"hexsha":{"kind":"list like","value":["9d1086d7d29c2d3760c8150d8641ab51799720cd"],"string":"[\n \"9d1086d7d29c2d3760c8150d8641ab51799720cd\"\n]"},"file_path":{"kind":"list like","value":["ibis/expr/datatypes.py"],"string":"[\n \"ibis/expr/datatypes.py\"\n]"},"code":{"kind":"list like","value":["import builtins\nimport collections\nimport datetime\nimport functools\nimport itertools\nimport numbers\nimport re\nimport typing\nfrom typing import Any as GenericAny\nfrom typing import (\n Callable,\n Iterator,\n List,\n Mapping,\n NamedTuple,\n Optional,\n Sequence,\n)\nfrom typing import Set as GenericSet\nfrom typing import Tuple, TypeVar, Union\n\nimport pandas as pd\nimport toolz\nfrom multipledispatch import Dispatcher\n\nimport ibis.common.exceptions as com\nimport ibis.expr.types as ir\nfrom ibis import util\n\nIS_SHAPELY_AVAILABLE = False\ntry:\n import shapely.geometry\n\n IS_SHAPELY_AVAILABLE = True\nexcept ImportError:\n ...\n\n\nclass DataType:\n\n __slots__ = ('nullable',)\n\n def __init__(self, nullable: bool = True) -> None:\n self.nullable = nullable\n\n def __call__(self, nullable: bool = True) -> 'DataType':\n if nullable is not True and nullable is not False:\n raise TypeError(\n \"__call__ only accepts the 'nullable' argument. \"\n \"Please construct a new instance of the type to change the \"\n \"values of the attributes.\"\n )\n return self._factory(nullable=nullable)\n\n def _factory(self, nullable: bool = True) -> 'DataType':\n slots = {\n slot: getattr(self, slot)\n for slot in self.__slots__\n if slot != 'nullable'\n }\n return type(self)(nullable=nullable, **slots)\n\n def __eq__(self, other) -> bool:\n return self.equals(other)\n\n def __ne__(self, other) -> bool:\n return not (self == other)\n\n def __hash__(self) -> int:\n custom_parts = tuple(\n getattr(self, slot)\n for slot in toolz.unique(self.__slots__ + ('nullable',))\n )\n return hash((type(self),) + custom_parts)\n\n def __repr__(self) -> str:\n return '{}({})'.format(\n self.name,\n ', '.join(\n '{}={!r}'.format(slot, getattr(self, slot))\n for slot in toolz.unique(self.__slots__ + ('nullable',))\n ),\n )\n\n def __str__(self) -> str:\n return '{}{}'.format(\n self.name.lower(), '[non-nullable]' if not self.nullable else ''\n )\n\n @property\n def name(self) -> str:\n return type(self).__name__\n\n def equals(\n self,\n other: 'DataType',\n cache: Optional[Mapping[GenericAny, bool]] = None,\n ) -> bool:\n if isinstance(other, str):\n raise TypeError(\n 'Comparing datatypes to strings is not allowed. Convert '\n '{!r} to the equivalent DataType instance.'.format(other)\n )\n return (\n isinstance(other, type(self))\n and self.nullable == other.nullable\n and self.__slots__ == other.__slots__\n and all(\n getattr(self, slot) == getattr(other, slot)\n for slot in self.__slots__\n )\n )\n\n def castable(self, target, **kwargs):\n return castable(self, target, **kwargs)\n\n def cast(self, target, **kwargs):\n return cast(self, target, **kwargs)\n\n def scalar_type(self):\n return functools.partial(self.scalar, dtype=self)\n\n def column_type(self):\n return functools.partial(self.column, dtype=self)\n\n def _literal_value_hash_key(self, value) -> int:\n \"\"\"Return a hash for `value`.\"\"\"\n return self, value\n\n\nclass Any(DataType):\n __slots__ = ()\n\n\nclass Primitive(DataType):\n __slots__ = ()\n\n def __repr__(self) -> str:\n name = self.name.lower()\n if not self.nullable:\n return '{}[non-nullable]'.format(name)\n return name\n\n\nclass Null(DataType):\n scalar = ir.NullScalar\n column = ir.NullColumn\n\n __slots__ = ()\n\n\nclass Variadic(DataType):\n __slots__ = ()\n\n\nclass Boolean(Primitive):\n scalar = ir.BooleanScalar\n column = ir.BooleanColumn\n\n __slots__ = ()\n\n\nBounds = NamedTuple('Bounds', [('lower', int), ('upper', int)])\n\n\nclass Integer(Primitive):\n scalar = ir.IntegerScalar\n column = ir.IntegerColumn\n\n __slots__ = ()\n\n @property\n def _nbytes(self) -> int:\n raise TypeError(\n \"Cannot determine the size in bytes of an abstract integer type.\"\n )\n\n\nclass String(Variadic):\n \"\"\"A type representing a string.\n\n Notes\n -----\n Because of differences in the way different backends handle strings, we\n cannot assume that strings are UTF-8 encoded.\n \"\"\"\n\n scalar = ir.StringScalar\n column = ir.StringColumn\n\n __slots__ = ()\n\n\nclass Binary(Variadic):\n \"\"\"A type representing a blob of bytes.\n\n Notes\n -----\n Some databases treat strings and blobs of equally, and some do not. For\n example, Impala doesn't make a distinction between string and binary types\n but PostgreSQL has a TEXT type and a BYTEA type which are distinct types\n that behave differently.\n \"\"\"\n\n scalar = ir.BinaryScalar\n column = ir.BinaryColumn\n\n __slots__ = ()\n\n\nclass Date(Primitive):\n scalar = ir.DateScalar\n column = ir.DateColumn\n\n __slots__ = ()\n\n\nclass Time(Primitive):\n scalar = ir.TimeScalar\n column = ir.TimeColumn\n\n __slots__ = ()\n\n\nclass Timestamp(DataType):\n scalar = ir.TimestampScalar\n column = ir.TimestampColumn\n\n __slots__ = ('timezone',)\n\n def __init__(\n self, timezone: Optional[str] = None, nullable: bool = True\n ) -> None:\n super().__init__(nullable=nullable)\n self.timezone = timezone\n\n def __str__(self) -> str:\n timezone = self.timezone\n typename = self.name.lower()\n if timezone is None:\n return typename\n return '{}({!r})'.format(typename, timezone)\n\n\nclass SignedInteger(Integer):\n @property\n def largest(self):\n return int64\n\n @property\n def bounds(self):\n exp = self._nbytes * 8 - 1\n upper = (1 << exp) - 1\n return Bounds(lower=~upper, upper=upper)\n\n\nclass UnsignedInteger(Integer):\n @property\n def largest(self):\n return uint64\n\n @property\n def bounds(self):\n exp = self._nbytes * 8 - 1\n upper = 1 << exp\n return Bounds(lower=0, upper=upper)\n\n\nclass Floating(Primitive):\n scalar = ir.FloatingScalar\n column = ir.FloatingColumn\n\n __slots__ = ()\n\n @property\n def largest(self):\n return float64\n\n @property\n def _nbytes(self) -> int:\n raise TypeError(\n \"Cannot determine the size in bytes of an abstract floating \"\n \"point type.\"\n )\n\n\nclass Int8(SignedInteger):\n __slots__ = ()\n _nbytes = 1\n\n\nclass Int16(SignedInteger):\n __slots__ = ()\n _nbytes = 2\n\n\nclass Int32(SignedInteger):\n __slots__ = ()\n _nbytes = 4\n\n\nclass Int64(SignedInteger):\n __slots__ = ()\n _nbytes = 8\n\n\nclass UInt8(UnsignedInteger):\n __slots__ = ()\n _nbytes = 1\n\n\nclass UInt16(UnsignedInteger):\n __slots__ = ()\n _nbytes = 2\n\n\nclass UInt32(UnsignedInteger):\n __slots__ = ()\n _nbytes = 4\n\n\nclass UInt64(UnsignedInteger):\n __slots__ = ()\n _nbytes = 8\n\n\nclass Float16(Floating):\n __slots__ = ()\n _nbytes = 2\n\n\nclass Float32(Floating):\n __slots__ = ()\n _nbytes = 4\n\n\nclass Float64(Floating):\n __slots__ = ()\n _nbytes = 8\n\n\nHalffloat = Float16\nFloat = Float32\nDouble = Float64\n\n\nclass Decimal(DataType):\n scalar = ir.DecimalScalar\n column = ir.DecimalColumn\n\n __slots__ = 'precision', 'scale'\n\n def __init__(\n self, precision: int, scale: int, nullable: bool = True\n ) -> None:\n if not isinstance(precision, numbers.Integral):\n raise TypeError('Decimal type precision must be an integer')\n if not isinstance(scale, numbers.Integral):\n raise TypeError('Decimal type scale must be an integer')\n if precision < 0:\n raise ValueError('Decimal type precision cannot be negative')\n if not precision:\n raise ValueError('Decimal type precision cannot be zero')\n if scale < 0:\n raise ValueError('Decimal type scale cannot be negative')\n if precision < scale:\n raise ValueError(\n 'Decimal type precision must be greater than or equal to '\n 'scale. Got precision={:d} and scale={:d}'.format(\n precision, scale\n )\n )\n\n super().__init__(nullable=nullable)\n self.precision = precision # type: int\n self.scale = scale # type: int\n\n def __str__(self) -> str:\n return '{}({:d}, {:d})'.format(\n self.name.lower(), self.precision, self.scale\n )\n\n @property\n def largest(self) -> 'Decimal':\n return Decimal(38, self.scale)\n\n\nclass Interval(DataType):\n scalar = ir.IntervalScalar\n column = ir.IntervalColumn\n\n __slots__ = 'value_type', 'unit'\n\n # based on numpy's units\n _units = dict(\n Y='year',\n Q='quarter',\n M='month',\n W='week',\n D='day',\n h='hour',\n m='minute',\n s='second',\n ms='millisecond',\n us='microsecond',\n ns='nanosecond',\n )\n\n _timedelta_to_interval_units = dict(\n days='D',\n hours='h',\n minutes='m',\n seconds='s',\n milliseconds='ms',\n microseconds='us',\n nanoseconds='ns',\n )\n\n def _convert_timedelta_unit_to_interval_unit(self, unit: str):\n if unit not in self._timedelta_to_interval_units:\n raise ValueError\n return self._timedelta_to_interval_units[unit]\n\n def __init__(\n self,\n unit: str = 's',\n value_type: Integer = None,\n nullable: bool = True,\n ) -> None:\n super().__init__(nullable=nullable)\n if unit not in self._units:\n try:\n unit = self._convert_timedelta_unit_to_interval_unit(unit)\n except ValueError:\n raise ValueError('Unsupported interval unit `{}`'.format(unit))\n\n if value_type is None:\n value_type = int32\n else:\n value_type = dtype(value_type)\n\n if not isinstance(value_type, Integer):\n raise TypeError(\"Interval's inner type must be an Integer subtype\")\n\n self.unit = unit\n self.value_type = value_type\n\n @property\n def bounds(self):\n return self.value_type.bounds\n\n @property\n def resolution(self):\n \"\"\"Unit's name\"\"\"\n return self._units[self.unit]\n\n def __str__(self):\n unit = self.unit\n typename = self.name.lower()\n value_type_name = self.value_type.name.lower()\n return '{}<{}>(unit={!r})'.format(typename, value_type_name, unit)\n\n\nclass Category(DataType):\n scalar = ir.CategoryScalar\n column = ir.CategoryColumn\n\n __slots__ = ('cardinality',)\n\n def __init__(self, cardinality=None, nullable=True):\n super().__init__(nullable=nullable)\n self.cardinality = cardinality\n\n def __repr__(self):\n if self.cardinality is not None:\n cardinality = self.cardinality\n else:\n cardinality = 'unknown'\n return '{}(cardinality={!r})'.format(self.name, cardinality)\n\n def to_integer_type(self):\n # TODO: this should be removed I guess\n if self.cardinality is None:\n return int64\n else:\n return infer(self.cardinality)\n\n\nclass Struct(DataType):\n scalar = ir.StructScalar\n column = ir.StructColumn\n\n __slots__ = 'names', 'types'\n\n def __init__(\n self, names: List[str], types: List[DataType], nullable: bool = True\n ) -> None:\n \"\"\"Construct a ``Struct`` type from a `names` and `types`.\n\n Parameters\n ----------\n names : Sequence[str]\n Sequence of strings indicating the name of each field in the\n struct.\n types : Sequence[Union[str, DataType]]\n Sequence of strings or :class:`~ibis.expr.datatypes.DataType`\n instances, one for each field\n nullable : bool, optional\n Whether the struct can be null\n \"\"\"\n if not (names and types):\n raise ValueError('names and types must not be empty')\n if len(names) != len(types):\n raise ValueError('names and types must have the same length')\n\n super().__init__(nullable=nullable)\n self.names = names\n self.types = types\n\n @classmethod\n def from_tuples(\n cls,\n pairs: Sequence[Tuple[str, Union[str, DataType]]],\n nullable: bool = True,\n ) -> 'Struct':\n names, types = zip(*pairs)\n return cls(list(names), list(map(dtype, types)), nullable=nullable)\n\n @property\n def pairs(self) -> Mapping:\n return collections.OrderedDict(zip(self.names, self.types))\n\n def __getitem__(self, key: str) -> DataType:\n return self.pairs[key]\n\n def __hash__(self) -> int:\n return hash(\n (type(self), tuple(self.names), tuple(self.types), self.nullable)\n )\n\n def __repr__(self) -> str:\n return '{}({}, nullable={})'.format(\n self.name, list(self.pairs.items()), self.nullable\n )\n\n def __str__(self) -> str:\n return '{}<{}>'.format(\n self.name.lower(),\n ', '.join(itertools.starmap('{}: {}'.format, self.pairs.items())),\n )\n\n def _literal_value_hash_key(self, value):\n return self, _tuplize(value.items())\n\n\ndef _tuplize(values):\n \"\"\"Recursively convert `values` to a tuple of tuples.\"\"\"\n\n def tuplize_iter(values):\n yield from (\n tuple(tuplize_iter(value)) if util.is_iterable(value) else value\n for value in values\n )\n\n return tuple(tuplize_iter(values))\n\n\nclass Array(Variadic):\n scalar = ir.ArrayScalar\n column = ir.ArrayColumn\n\n __slots__ = ('value_type',)\n\n def __init__(\n self, value_type: Union[str, DataType], nullable: bool = True\n ) -> None:\n super().__init__(nullable=nullable)\n self.value_type = dtype(value_type)\n\n def __str__(self) -> str:\n return '{}<{}>'.format(self.name.lower(), self.value_type)\n\n def _literal_value_hash_key(self, value):\n return self, _tuplize(value)\n\n\nclass Set(Variadic):\n scalar = ir.SetScalar\n column = ir.SetColumn\n\n __slots__ = ('value_type',)\n\n def __init__(\n self, value_type: Union[str, DataType], nullable: bool = True\n ) -> None:\n super().__init__(nullable=nullable)\n self.value_type = dtype(value_type)\n\n def __str__(self) -> str:\n return '{}<{}>'.format(self.name.lower(), self.value_type)\n\n\nclass Enum(DataType):\n scalar = ir.EnumScalar\n column = ir.EnumColumn\n\n __slots__ = 'rep_type', 'value_type'\n\n def __init__(\n self, rep_type: DataType, value_type: DataType, nullable: bool = True\n ) -> None:\n super().__init__(nullable=nullable)\n self.rep_type = dtype(rep_type)\n self.value_type = dtype(value_type)\n\n\nclass Map(Variadic):\n scalar = ir.MapScalar\n column = ir.MapColumn\n\n __slots__ = 'key_type', 'value_type'\n\n def __init__(\n self, key_type: DataType, value_type: DataType, nullable: bool = True\n ) -> None:\n super().__init__(nullable=nullable)\n self.key_type = dtype(key_type)\n self.value_type = dtype(value_type)\n\n def __str__(self) -> str:\n return '{}<{}, {}>'.format(\n self.name.lower(), self.key_type, self.value_type\n )\n\n def _literal_value_hash_key(self, value):\n return self, _tuplize(value.items())\n\n\nclass JSON(String):\n \"\"\"JSON (JavaScript Object Notation) text format.\"\"\"\n\n scalar = ir.JSONScalar\n column = ir.JSONColumn\n\n\nclass JSONB(Binary):\n \"\"\"JSON (JavaScript Object Notation) data stored as a binary\n representation, which eliminates whitespace, duplicate keys,\n and key ordering.\n \"\"\"\n\n scalar = ir.JSONBScalar\n column = ir.JSONBColumn\n\n\nclass GeoSpatial(DataType):\n __slots__ = 'geotype', 'srid'\n\n column = ir.GeoSpatialColumn\n scalar = ir.GeoSpatialScalar\n\n def __init__(\n self, geotype: str = None, srid: int = None, nullable: bool = True\n ):\n \"\"\"Geospatial data type base class\n\n Parameters\n ----------\n geotype : str\n Specification of geospatial type which could be `geography` or\n `geometry`.\n srid : int\n Spatial Reference System Identifier\n nullable : bool, optional\n Whether the struct can be null\n \"\"\"\n super().__init__(nullable=nullable)\n\n if geotype not in (None, 'geometry', 'geography'):\n raise ValueError(\n 'The `geotype` parameter should be `geometry` or `geography`'\n )\n\n self.geotype = geotype\n self.srid = srid\n\n def __str__(self) -> str:\n geo_op = self.name.lower()\n if self.geotype is not None:\n geo_op += ':' + self.geotype\n if self.srid is not None:\n geo_op += ';' + str(self.srid)\n return geo_op\n\n def _literal_value_hash_key(self, value):\n if IS_SHAPELY_AVAILABLE:\n geo_shapes = (\n shapely.geometry.Point,\n shapely.geometry.LineString,\n shapely.geometry.Polygon,\n shapely.geometry.MultiLineString,\n shapely.geometry.MultiPoint,\n shapely.geometry.MultiPolygon,\n )\n if isinstance(value, geo_shapes):\n return self, value.wkt\n return self, value\n\n\nclass Geometry(GeoSpatial):\n \"\"\"Geometry is used to cast from geography types.\"\"\"\n\n column = ir.GeoSpatialColumn\n scalar = ir.GeoSpatialScalar\n\n __slots__ = ()\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.geotype = 'geometry'\n\n def __str__(self) -> str:\n return self.name.lower()\n\n\nclass Geography(GeoSpatial):\n \"\"\"Geography is used to cast from geometry types.\"\"\"\n\n column = ir.GeoSpatialColumn\n scalar = ir.GeoSpatialScalar\n\n __slots__ = ()\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.geotype = 'geography'\n\n def __str__(self) -> str:\n return self.name.lower()\n\n\nclass Point(GeoSpatial):\n \"\"\"A point described by two coordinates.\"\"\"\n\n scalar = ir.PointScalar\n column = ir.PointColumn\n\n __slots__ = ()\n\n\nclass LineString(GeoSpatial):\n \"\"\"A sequence of 2 or more points.\"\"\"\n\n scalar = ir.LineStringScalar\n column = ir.LineStringColumn\n\n __slots__ = ()\n\n\nclass Polygon(GeoSpatial):\n \"\"\"A set of one or more rings (closed line strings), with the first\n representing the shape (external ring) and the rest representing holes in\n that shape (internal rings).\n \"\"\"\n\n scalar = ir.PolygonScalar\n column = ir.PolygonColumn\n\n __slots__ = ()\n\n\nclass MultiLineString(GeoSpatial):\n \"\"\"A set of one or more line strings.\"\"\"\n\n scalar = ir.MultiLineStringScalar\n column = ir.MultiLineStringColumn\n\n __slots__ = ()\n\n\nclass MultiPoint(GeoSpatial):\n \"\"\"A set of one or more points.\"\"\"\n\n scalar = ir.MultiPointScalar\n column = ir.MultiPointColumn\n\n __slots__ = ()\n\n\nclass MultiPolygon(GeoSpatial):\n \"\"\"A set of one or more polygons.\"\"\"\n\n scalar = ir.MultiPolygonScalar\n column = ir.MultiPolygonColumn\n\n __slots__ = ()\n\n\nclass UUID(String):\n \"\"\"A universally unique identifier (UUID) is a 128-bit number used to\n identify information in computer systems.\n \"\"\"\n\n scalar = ir.UUIDScalar\n column = ir.UUIDColumn\n\n __slots__ = ()\n\n\n# ---------------------------------------------------------------------\nany = Any()\nnull = Null()\nboolean = Boolean()\nint_ = Integer()\nint8 = Int8()\nint16 = Int16()\nint32 = Int32()\nint64 = Int64()\nuint_ = UnsignedInteger()\nuint8 = UInt8()\nuint16 = UInt16()\nuint32 = UInt32()\nuint64 = UInt64()\nfloat = Float()\nhalffloat = Halffloat()\nfloat16 = Halffloat()\nfloat32 = Float32()\nfloat64 = Float64()\ndouble = Double()\nstring = String()\nbinary = Binary()\ndate = Date()\ntime = Time()\ntimestamp = Timestamp()\ninterval = Interval()\ncategory = Category()\n# geo spatial data type\ngeometry = GeoSpatial()\ngeography = GeoSpatial()\npoint = Point()\nlinestring = LineString()\npolygon = Polygon()\nmultilinestring = MultiLineString()\nmultipoint = MultiPoint()\nmultipolygon = MultiPolygon()\n# json\njson = JSON()\njsonb = JSONB()\n# special string based data type\nuuid = UUID()\n\n_primitive_types = [\n ('any', any),\n ('null', null),\n ('boolean', boolean),\n ('bool', boolean),\n ('int8', int8),\n ('int16', int16),\n ('int32', int32),\n ('int64', int64),\n ('uint8', uint8),\n ('uint16', uint16),\n ('uint32', uint32),\n ('uint64', uint64),\n ('float16', float16),\n ('float32', float32),\n ('float64', float64),\n ('float', float),\n ('halffloat', float16),\n ('double', double),\n ('string', string),\n ('binary', binary),\n ('date', date),\n ('time', time),\n ('timestamp', timestamp),\n ('interval', interval),\n ('category', category),\n] # type: List[Tuple[str, DataType]]\n\n\nclass Tokens:\n \"\"\"Class to hold tokens for lexing.\"\"\"\n\n __slots__ = ()\n\n ANY = 0\n NULL = 1\n PRIMITIVE = 2\n DECIMAL = 3\n VARCHAR = 4\n CHAR = 5\n ARRAY = 6\n MAP = 7\n STRUCT = 8\n INTEGER = 9\n FIELD = 10\n COMMA = 11\n COLON = 12\n LPAREN = 13\n RPAREN = 14\n LBRACKET = 15\n RBRACKET = 16\n STRARG = 17\n TIMESTAMP = 18\n TIME = 19\n INTERVAL = 20\n SET = 21\n GEOGRAPHY = 22\n GEOMETRY = 23\n POINT = 24\n LINESTRING = 25\n POLYGON = 26\n MULTILINESTRING = 27\n MULTIPOINT = 28\n MULTIPOLYGON = 29\n SEMICOLON = 30\n JSON = 31\n JSONB = 32\n UUID = 33\n\n @staticmethod\n def name(value):\n return _token_names[value]\n\n\n_token_names = dict(\n (getattr(Tokens, n), n) for n in dir(Tokens) if n.isalpha() and n.isupper()\n)\n\nToken = collections.namedtuple('Token', ('type', 'value'))\n\n\n# Adapted from tokenize.String\n_STRING_REGEX = \"\"\"('[^\\n'\\\\\\\\]*(?:\\\\\\\\.[^\\n'\\\\\\\\]*)*'|\"[^\\n\"\\\\\\\\\"]*(?:\\\\\\\\.[^\\n\"\\\\\\\\]*)*\")\"\"\" # noqa: E501\n\n\nAction = Optional[Callable[[str], Token]]\n\n\n_TYPE_RULES = collections.OrderedDict(\n [\n # any, null, bool|boolean\n ('(?Pany)', lambda token: Token(Tokens.ANY, any)),\n ('(?Pnull)', lambda token: Token(Tokens.NULL, null)),\n (\n '(?Pbool(?:ean)?)',\n typing.cast(\n Action, lambda token: Token(Tokens.PRIMITIVE, boolean)\n ),\n ),\n ]\n + [\n # primitive types\n (\n '(?P<{}>{})'.format(token.upper(), token),\n typing.cast(\n Action,\n lambda token, value=value: Token(Tokens.PRIMITIVE, value),\n ),\n )\n for token, value in _primitive_types\n if token\n not in {'any', 'null', 'timestamp', 'time', 'interval', 'boolean'}\n ]\n + [\n # timestamp\n (\n r'(?Ptimestamp)',\n lambda token: Token(Tokens.TIMESTAMP, token),\n )\n ]\n + [\n # interval - should remove?\n (\n r'(?Pinterval)',\n lambda token: Token(Tokens.INTERVAL, token),\n )\n ]\n + [\n # time\n (r'(?P