{"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \n#include \n\n#include \"swtypes.hxx\"\n#include \"cmdid.h\"\n#include \"envprt.hxx\"\n#include \"envlop.hxx\"\n#include \"uitool.hxx\"\n\n#include \"envprt.hrc\"\n\nSwEnvPrtPage::SwEnvPrtPage(Window* pParent, const SfxItemSet& rSet)\n : SfxTabPage(pParent, \"EnvPrinterPage\",\n \"modules\/swriter\/ui\/envprinterpage.ui\", rSet)\n{\n get(m_pAlignBox, \"alignbox\");\n get(m_pTopButton, \"top\");\n get(m_pBottomButton, \"bottom\");\n get(m_pRightField, \"right\");\n get(m_pDownField, \"down\");\n get(m_pPrinterInfo, \"printername\");\n get(m_pPrtSetup, \"setup\");\n SetExchangeSupport();\n\n \/\/ Metrics\n FieldUnit eUnit = ::GetDfltMetric(sal_False);\n SetMetric(*m_pRightField, eUnit);\n SetMetric(*m_pDownField, eUnit);\n\n \/\/ Install handlers\n m_pTopButton->SetClickHdl(LINK(this, SwEnvPrtPage, ClickHdl));\n m_pBottomButton->SetClickHdl(LINK(this, SwEnvPrtPage, ClickHdl));\n\n m_pPrtSetup->SetClickHdl(LINK(this, SwEnvPrtPage, ButtonHdl));\n\n \/\/ Bitmaps\n m_pBottomButton->GetClickHdl().Call(m_pBottomButton);\n\n \/\/ ToolBox\n m_pAlignBox->SetClickHdl(LINK(this, SwEnvPrtPage, AlignHdl));\n m_aIds[ENV_HOR_LEFT] = m_pAlignBox->GetItemId(\"horileft\");\n m_aIds[ENV_HOR_CNTR] = m_pAlignBox->GetItemId(\"horicenter\");\n m_aIds[ENV_HOR_RGHT] = m_pAlignBox->GetItemId(\"horiright\");\n m_aIds[ENV_VER_LEFT] = m_pAlignBox->GetItemId(\"vertleft\");\n m_aIds[ENV_VER_CNTR] = m_pAlignBox->GetItemId(\"vertcenter\");\n m_aIds[ENV_VER_RGHT] = m_pAlignBox->GetItemId(\"vertright\");\n}\n\nIMPL_LINK_NOARG(SwEnvPrtPage, ClickHdl)\n{\n if (m_pBottomButton->IsChecked())\n {\n \/\/ Envelope from botton\n m_pAlignBox->SetItemImage(m_aIds[ENV_HOR_LEFT], Image(Bitmap(SW_RES(BMP_HOR_LEFT_LOWER))));\n m_pAlignBox->SetItemImage(m_aIds[ENV_HOR_CNTR], Image(Bitmap(SW_RES(BMP_HOR_CNTR_LOWER))));\n m_pAlignBox->SetItemImage(m_aIds[ENV_HOR_RGHT], Image(Bitmap(SW_RES(BMP_HOR_RGHT_LOWER))));\n m_pAlignBox->SetItemImage(m_aIds[ENV_VER_LEFT], Image(Bitmap(SW_RES(BMP_VER_LEFT_LOWER))));\n m_pAlignBox->SetItemImage(m_aIds[ENV_VER_CNTR], Image(Bitmap(SW_RES(BMP_VER_CNTR_LOWER))));\n m_pAlignBox->SetItemImage(m_aIds[ENV_VER_RGHT], Image(Bitmap(SW_RES(BMP_VER_RGHT_LOWER))));\n }\n else\n {\n \/\/ Envelope from top\n m_pAlignBox->SetItemImage(m_aIds[ENV_HOR_LEFT], Image(Bitmap(SW_RES(BMP_HOR_LEFT_UPPER))));\n m_pAlignBox->SetItemImage(m_aIds[ENV_HOR_CNTR], Image(Bitmap(SW_RES(BMP_HOR_CNTR_UPPER))));\n m_pAlignBox->SetItemImage(m_aIds[ENV_HOR_RGHT], Image(Bitmap(SW_RES(BMP_HOR_RGHT_UPPER))));\n m_pAlignBox->SetItemImage(m_aIds[ENV_VER_LEFT], Image(Bitmap(SW_RES(BMP_VER_LEFT_UPPER))));\n m_pAlignBox->SetItemImage(m_aIds[ENV_VER_CNTR], Image(Bitmap(SW_RES(BMP_VER_CNTR_UPPER))));\n m_pAlignBox->SetItemImage(m_aIds[ENV_VER_RGHT], Image(Bitmap(SW_RES(BMP_VER_RGHT_UPPER))));\n }\n return 0;\n}\n\nIMPL_LINK( SwEnvPrtPage, ButtonHdl, Button *, pBtn )\n{\n if (pBtn == m_pPrtSetup)\n {\n \/\/ Call printer setup\n if (pPrt)\n {\n PrinterSetupDialog* pDlg = new PrinterSetupDialog(this );\n pDlg->SetPrinter(pPrt);\n pDlg->Execute();\n delete pDlg;\n GrabFocus();\n m_pPrinterInfo->SetText(pPrt->GetName());\n }\n }\n return 0;\n}\n\nIMPL_LINK_NOARG(SwEnvPrtPage, AlignHdl)\n{\n if (m_pAlignBox->GetCurItemId())\n {\n for (sal_uInt16 i = ENV_HOR_LEFT; i <= ENV_VER_RGHT; ++i)\n m_pAlignBox->CheckItem(m_aIds[i], false);\n m_pAlignBox->CheckItem(m_pAlignBox->GetCurItemId(), true);\n }\n else\n {\n \/\/ GetCurItemId() == 0 is possible!\n const SwEnvItem& rItem = (const SwEnvItem&) GetItemSet().Get(FN_ENVELOP);\n m_pAlignBox->CheckItem(m_aIds[rItem.eAlign], true);\n }\n return 0;\n}\n\nSfxTabPage* SwEnvPrtPage::Create(Window* pParent, const SfxItemSet& rSet)\n{\n return new SwEnvPrtPage(pParent, rSet);\n}\n\nvoid SwEnvPrtPage::ActivatePage(const SfxItemSet&)\n{\n if (pPrt)\n m_pPrinterInfo->SetText(pPrt->GetName());\n}\n\nint SwEnvPrtPage::DeactivatePage(SfxItemSet* _pSet)\n{\n if( _pSet )\n FillItemSet(*_pSet);\n return SfxTabPage::LEAVE_PAGE;\n}\n\nvoid SwEnvPrtPage::FillItem(SwEnvItem& rItem)\n{\n sal_uInt16 nOrient = 0;\n for (sal_uInt16 i = ENV_HOR_LEFT; i <= ENV_VER_RGHT; ++i)\n {\n if (m_pAlignBox->IsItemChecked(m_aIds[i]))\n {\n nOrient = i;\n break;\n }\n }\n\n rItem.eAlign = (SwEnvAlign) (nOrient);\n rItem.bPrintFromAbove = m_pTopButton->IsChecked();\n rItem.lShiftRight = static_cast< sal_Int32 >(GetFldVal(*m_pRightField));\n rItem.lShiftDown = static_cast< sal_Int32 >(GetFldVal(*m_pDownField ));\n}\n\nbool SwEnvPrtPage::FillItemSet(SfxItemSet& rSet)\n{\n FillItem(GetParentSwEnvDlg()->aEnvItem);\n rSet.Put(GetParentSwEnvDlg()->aEnvItem);\n return true;\n}\n\nvoid SwEnvPrtPage::Reset(const SfxItemSet& rSet)\n{\n \/\/ Read item\n const SwEnvItem& rItem = (const SwEnvItem&) rSet.Get(FN_ENVELOP);\n m_pAlignBox->CheckItem(m_aIds[rItem.eAlign]);\n\n if (rItem.bPrintFromAbove)\n m_pTopButton->Check();\n else\n m_pBottomButton->Check();\n\n SetFldVal(*m_pRightField, rItem.lShiftRight);\n SetFldVal(*m_pDownField , rItem.lShiftDown );\n\n ActivatePage(rSet);\n ClickHdl(m_pTopButton);\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\nsal_uInt16 to int\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \n#include \n\n#include \"swtypes.hxx\"\n#include \"cmdid.h\"\n#include \"envprt.hxx\"\n#include \"envlop.hxx\"\n#include \"uitool.hxx\"\n\n#include \"envprt.hrc\"\n\nSwEnvPrtPage::SwEnvPrtPage(Window* pParent, const SfxItemSet& rSet)\n : SfxTabPage(pParent, \"EnvPrinterPage\",\n \"modules\/swriter\/ui\/envprinterpage.ui\", rSet)\n{\n get(m_pAlignBox, \"alignbox\");\n get(m_pTopButton, \"top\");\n get(m_pBottomButton, \"bottom\");\n get(m_pRightField, \"right\");\n get(m_pDownField, \"down\");\n get(m_pPrinterInfo, \"printername\");\n get(m_pPrtSetup, \"setup\");\n SetExchangeSupport();\n\n \/\/ Metrics\n FieldUnit eUnit = ::GetDfltMetric(sal_False);\n SetMetric(*m_pRightField, eUnit);\n SetMetric(*m_pDownField, eUnit);\n\n \/\/ Install handlers\n m_pTopButton->SetClickHdl(LINK(this, SwEnvPrtPage, ClickHdl));\n m_pBottomButton->SetClickHdl(LINK(this, SwEnvPrtPage, ClickHdl));\n\n m_pPrtSetup->SetClickHdl(LINK(this, SwEnvPrtPage, ButtonHdl));\n\n \/\/ Bitmaps\n m_pBottomButton->GetClickHdl().Call(m_pBottomButton);\n\n \/\/ ToolBox\n m_pAlignBox->SetClickHdl(LINK(this, SwEnvPrtPage, AlignHdl));\n m_aIds[ENV_HOR_LEFT] = m_pAlignBox->GetItemId(\"horileft\");\n m_aIds[ENV_HOR_CNTR] = m_pAlignBox->GetItemId(\"horicenter\");\n m_aIds[ENV_HOR_RGHT] = m_pAlignBox->GetItemId(\"horiright\");\n m_aIds[ENV_VER_LEFT] = m_pAlignBox->GetItemId(\"vertleft\");\n m_aIds[ENV_VER_CNTR] = m_pAlignBox->GetItemId(\"vertcenter\");\n m_aIds[ENV_VER_RGHT] = m_pAlignBox->GetItemId(\"vertright\");\n}\n\nIMPL_LINK_NOARG(SwEnvPrtPage, ClickHdl)\n{\n if (m_pBottomButton->IsChecked())\n {\n \/\/ Envelope from botton\n m_pAlignBox->SetItemImage(m_aIds[ENV_HOR_LEFT], Image(Bitmap(SW_RES(BMP_HOR_LEFT_LOWER))));\n m_pAlignBox->SetItemImage(m_aIds[ENV_HOR_CNTR], Image(Bitmap(SW_RES(BMP_HOR_CNTR_LOWER))));\n m_pAlignBox->SetItemImage(m_aIds[ENV_HOR_RGHT], Image(Bitmap(SW_RES(BMP_HOR_RGHT_LOWER))));\n m_pAlignBox->SetItemImage(m_aIds[ENV_VER_LEFT], Image(Bitmap(SW_RES(BMP_VER_LEFT_LOWER))));\n m_pAlignBox->SetItemImage(m_aIds[ENV_VER_CNTR], Image(Bitmap(SW_RES(BMP_VER_CNTR_LOWER))));\n m_pAlignBox->SetItemImage(m_aIds[ENV_VER_RGHT], Image(Bitmap(SW_RES(BMP_VER_RGHT_LOWER))));\n }\n else\n {\n \/\/ Envelope from top\n m_pAlignBox->SetItemImage(m_aIds[ENV_HOR_LEFT], Image(Bitmap(SW_RES(BMP_HOR_LEFT_UPPER))));\n m_pAlignBox->SetItemImage(m_aIds[ENV_HOR_CNTR], Image(Bitmap(SW_RES(BMP_HOR_CNTR_UPPER))));\n m_pAlignBox->SetItemImage(m_aIds[ENV_HOR_RGHT], Image(Bitmap(SW_RES(BMP_HOR_RGHT_UPPER))));\n m_pAlignBox->SetItemImage(m_aIds[ENV_VER_LEFT], Image(Bitmap(SW_RES(BMP_VER_LEFT_UPPER))));\n m_pAlignBox->SetItemImage(m_aIds[ENV_VER_CNTR], Image(Bitmap(SW_RES(BMP_VER_CNTR_UPPER))));\n m_pAlignBox->SetItemImage(m_aIds[ENV_VER_RGHT], Image(Bitmap(SW_RES(BMP_VER_RGHT_UPPER))));\n }\n return 0;\n}\n\nIMPL_LINK( SwEnvPrtPage, ButtonHdl, Button *, pBtn )\n{\n if (pBtn == m_pPrtSetup)\n {\n \/\/ Call printer setup\n if (pPrt)\n {\n PrinterSetupDialog* pDlg = new PrinterSetupDialog(this );\n pDlg->SetPrinter(pPrt);\n pDlg->Execute();\n delete pDlg;\n GrabFocus();\n m_pPrinterInfo->SetText(pPrt->GetName());\n }\n }\n return 0;\n}\n\nIMPL_LINK_NOARG(SwEnvPrtPage, AlignHdl)\n{\n if (m_pAlignBox->GetCurItemId())\n {\n for (int i = ENV_HOR_LEFT; i <= ENV_VER_RGHT; ++i)\n m_pAlignBox->CheckItem(m_aIds[i], false);\n m_pAlignBox->CheckItem(m_pAlignBox->GetCurItemId(), true);\n }\n else\n {\n \/\/ GetCurItemId() == 0 is possible!\n const SwEnvItem& rItem = (const SwEnvItem&) GetItemSet().Get(FN_ENVELOP);\n m_pAlignBox->CheckItem(m_aIds[rItem.eAlign], true);\n }\n return 0;\n}\n\nSfxTabPage* SwEnvPrtPage::Create(Window* pParent, const SfxItemSet& rSet)\n{\n return new SwEnvPrtPage(pParent, rSet);\n}\n\nvoid SwEnvPrtPage::ActivatePage(const SfxItemSet&)\n{\n if (pPrt)\n m_pPrinterInfo->SetText(pPrt->GetName());\n}\n\nint SwEnvPrtPage::DeactivatePage(SfxItemSet* _pSet)\n{\n if( _pSet )\n FillItemSet(*_pSet);\n return SfxTabPage::LEAVE_PAGE;\n}\n\nvoid SwEnvPrtPage::FillItem(SwEnvItem& rItem)\n{\n int nOrient = 0;\n for (int i = ENV_HOR_LEFT; i <= ENV_VER_RGHT; ++i)\n {\n if (m_pAlignBox->IsItemChecked(m_aIds[i]))\n {\n nOrient = i;\n break;\n }\n }\n\n rItem.eAlign = (SwEnvAlign) (nOrient);\n rItem.bPrintFromAbove = m_pTopButton->IsChecked();\n rItem.lShiftRight = static_cast< sal_Int32 >(GetFldVal(*m_pRightField));\n rItem.lShiftDown = static_cast< sal_Int32 >(GetFldVal(*m_pDownField ));\n}\n\nbool SwEnvPrtPage::FillItemSet(SfxItemSet& rSet)\n{\n FillItem(GetParentSwEnvDlg()->aEnvItem);\n rSet.Put(GetParentSwEnvDlg()->aEnvItem);\n return true;\n}\n\nvoid SwEnvPrtPage::Reset(const SfxItemSet& rSet)\n{\n \/\/ Read item\n const SwEnvItem& rItem = (const SwEnvItem&) rSet.Get(FN_ENVELOP);\n m_pAlignBox->CheckItem(m_aIds[rItem.eAlign]);\n\n if (rItem.bPrintFromAbove)\n m_pTopButton->Check();\n else\n m_pBottomButton->Check();\n\n SetFldVal(*m_pRightField, rItem.lShiftRight);\n SetFldVal(*m_pDownField , rItem.lShiftDown );\n\n ActivatePage(rSet);\n ClickHdl(m_pTopButton);\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"\/\/ Copyright 2019 The TCMalloc Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n#include \"absl\/strings\/str_format.h\"\n#include \"absl\/strings\/string_view.h\"\n#include \"tcmalloc\/common.h\"\n#include \"tcmalloc\/internal\/logging.h\"\n#include \"tcmalloc\/internal\/parameter_accessors.h\"\n#include \"tcmalloc\/malloc_extension.h\"\n#include \"tcmalloc\/testing\/testutil.h\"\n\nnamespace tcmalloc {\nnamespace {\n\nusing ::testing::ContainsRegex;\nusing ::testing::HasSubstr;\n\nvoid DumpHeapStats(absl::string_view label) {\n std::string buffer = MallocExtension::GetStats();\n absl::FPrintF(stderr, \"%s\\n%s\\n\", label, buffer);\n}\n\n\/\/ Fixture for friend access to MallocExtension.\nclass LimitTest : public ::testing::Test {\n protected:\n void SetLimit(size_t limit, bool is_hard) {\n MallocExtension::MemoryLimit v;\n v.limit = limit;\n v.hard = is_hard;\n MallocExtension::SetMemoryLimit(v);\n }\n\n size_t GetLimit(bool is_hard) {\n MallocExtension::MemoryLimit v = MallocExtension::GetMemoryLimit();\n if (v.hard == is_hard) {\n return v.limit;\n } else {\n \/\/ Return no limit, as we do not have a limit matching is_hard.\n return std::numeric_limits::max();\n }\n }\n\n \/\/ avoid fragmentation in local caches\n void *malloc_pages(size_t bytes) {\n CHECK_CONDITION(bytes % kPageSize == 0);\n void *ptr;\n CHECK_CONDITION(posix_memalign(&ptr, kPageSize, bytes) == 0);\n return ptr;\n }\n\n size_t physical_memory_used() {\n std::map m =\n MallocExtension::GetProperties();\n auto i = m.find(\"generic.physical_memory_used\");\n CHECK_CONDITION(i != m.end());\n return i->second.value;\n }\n};\n\nTEST_F(LimitTest, LimitRespected) {\n static const size_t kLim = 4ul * 1024 * 1024 * 1024;\n SetLimit(kLim, false);\n\n std::string statsBuf = MallocExtension::GetStats();\n std::string statsPbtxt = GetStatsInPbTxt();\n EXPECT_THAT(statsBuf, HasSubstr(absl::StrFormat(\n \"PARAMETER desired_usage_limit_bytes %u\", kLim)));\n EXPECT_THAT(statsBuf, HasSubstr(\"Number of times limit was hit: 0\"));\n EXPECT_THAT(statsPbtxt, HasSubstr(absl::StrFormat(\n \"desired_usage_limit_bytes: %u\", kLim)));\n EXPECT_THAT(statsPbtxt, HasSubstr(\"hard_limit: false\"));\n EXPECT_THAT(statsPbtxt, HasSubstr(\"limit_hits: 0\"));\n\n \/\/ Avoid failing due to usage by test itself.\n static const size_t kLimForUse = kLim * 9 \/ 10;\n \/\/ First allocate many small objects...\n size_t used = 0;\n std::vector ptrs;\n while (used < kLimForUse) {\n ptrs.push_back(malloc_pages(kPageSize));\n used += kPageSize;\n }\n DumpHeapStats(\"after allocating small objects\");\n \/\/ return much of the space, fragmented...\n bool ret = false;\n for (auto &p : ptrs) {\n if (ret) {\n free(p);\n p = nullptr;\n used -= kPageSize;\n }\n ret = !ret;\n }\n DumpHeapStats(\"after freeing many small objects\");\n \/\/ Now ensure we can re use it for large allocations.\n\n while (used < kLimForUse) {\n const size_t large = kPageSize * 10;\n ptrs.push_back(malloc_pages(large));\n used += large;\n }\n DumpHeapStats(\"after allocating large objects\");\n EXPECT_LE(physical_memory_used(), kLim);\n\n statsBuf = MallocExtension::GetStats();\n statsPbtxt = GetStatsInPbTxt();\n \/\/ The HugePageAwareAllocator hits the limit more than once.\n EXPECT_THAT(statsBuf,\n ContainsRegex(R\"(Number of times limit was hit: [1-9]\\d*)\"));\n EXPECT_THAT(statsPbtxt, ContainsRegex(R\"(limit_hits: [1-9]\\d*)\"));\n\n for (auto p : ptrs) {\n free(p);\n }\n}\n\n TEST_F(LimitTest, DISABLED_HardLimitRespected) { \/\/ b\/143314400\n static const size_t kLim = 300 << 20;\n SetLimit(kLim, true);\n\n std::string statsBuf = MallocExtension::GetStats();\n std::string statsPbtxt = GetStatsInPbTxt();\n EXPECT_THAT(statsBuf,\n HasSubstr(absl::StrFormat(\n \"PARAMETER desired_usage_limit_bytes %u (hard)\", kLim)));\n EXPECT_THAT(statsPbtxt, HasSubstr(absl::StrFormat(\n \"desired_usage_limit_bytes: %u\", kLim)));\n EXPECT_THAT(statsPbtxt, HasSubstr(\"hard_limit: true\"));\n\n void *ptr = malloc_pages(50 << 20);\n ASSERT_DEATH(malloc_pages(400 << 20), \"limit\");\n free(ptr);\n SetLimit(std::numeric_limits::max(), false);\n}\n\nTEST_F(LimitTest, HardLimitRespectsNoSubrelease) {\n static const size_t kLim = 300 << 20;\n SetLimit(kLim, true);\n TCMalloc_Internal_SetHPAASubrelease(false);\n EXPECT_FALSE(TCMalloc_Internal_GetHPAASubrelease());\n\n std::string statsBuf = MallocExtension::GetStats();\n std::string statsPbtxt = GetStatsInPbTxt();\n EXPECT_THAT(statsBuf,\n HasSubstr(absl::StrFormat(\n \"PARAMETER desired_usage_limit_bytes %u (hard)\", kLim)));\n EXPECT_THAT(statsPbtxt, HasSubstr(absl::StrFormat(\n \"desired_usage_limit_bytes: %u\", kLim)));\n EXPECT_THAT(statsPbtxt, HasSubstr(\"hard_limit: true\"));\n\n ASSERT_DEATH(\n []() {\n \/\/ Allocate a bunch of medium objects, free half of them to cause some\n \/\/ fragmentation, then allocate some large objects. If we subrelease we\n \/\/ could stay under our hard limit, but if we don't then we should go\n \/\/ over.\n std::vector ptrs;\n constexpr size_t kNumMediumObjs = 400;\n constexpr size_t kNumLargeObjs = 200;\n for (size_t i = 0; i < kNumMediumObjs; i++) {\n ptrs.push_back(::operator new(512 << 10));\n }\n DumpHeapStats(\"after allocating medium objects\");\n for (size_t i = 0; i < ptrs.size(); i++) {\n if (i % 2) continue;\n ::operator delete(ptrs[i]);\n ptrs[i] = static_cast(0);\n }\n DumpHeapStats(\"after freeing half of medium objects\");\n for (size_t i = 0; i < kNumLargeObjs; i++) {\n ptrs.push_back(::operator new(1 << 20));\n }\n DumpHeapStats(\"after allocating large objects\");\n while (!ptrs.empty()) {\n ::operator delete(ptrs.back());\n ptrs.pop_back();\n }\n DumpHeapStats(\"after freeing all objects\");\n }(),\n \"limit\");\n SetLimit(std::numeric_limits::max(), false);\n}\n\n} \/\/ namespace\n} \/\/ namespace tcmalloc\nEnable hard limit test.\/\/ Copyright 2019 The TCMalloc Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n#include \"absl\/strings\/str_format.h\"\n#include \"absl\/strings\/string_view.h\"\n#include \"tcmalloc\/common.h\"\n#include \"tcmalloc\/internal\/logging.h\"\n#include \"tcmalloc\/internal\/parameter_accessors.h\"\n#include \"tcmalloc\/malloc_extension.h\"\n#include \"tcmalloc\/testing\/testutil.h\"\n\nnamespace tcmalloc {\nnamespace {\n\nusing ::testing::ContainsRegex;\nusing ::testing::HasSubstr;\n\nvoid DumpHeapStats(absl::string_view label) {\n std::string buffer = MallocExtension::GetStats();\n absl::FPrintF(stderr, \"%s\\n%s\\n\", label, buffer);\n}\n\n\/\/ Fixture for friend access to MallocExtension.\nclass LimitTest : public ::testing::Test {\n protected:\n void SetLimit(size_t limit, bool is_hard) {\n MallocExtension::MemoryLimit v;\n v.limit = limit;\n v.hard = is_hard;\n MallocExtension::SetMemoryLimit(v);\n }\n\n size_t GetLimit(bool is_hard) {\n MallocExtension::MemoryLimit v = MallocExtension::GetMemoryLimit();\n if (v.hard == is_hard) {\n return v.limit;\n } else {\n \/\/ Return no limit, as we do not have a limit matching is_hard.\n return std::numeric_limits::max();\n }\n }\n\n \/\/ avoid fragmentation in local caches\n void *malloc_pages(size_t bytes) {\n CHECK_CONDITION(bytes % kPageSize == 0);\n void *ptr;\n CHECK_CONDITION(posix_memalign(&ptr, kPageSize, bytes) == 0);\n return ptr;\n }\n\n size_t physical_memory_used() {\n std::map m =\n MallocExtension::GetProperties();\n auto i = m.find(\"generic.physical_memory_used\");\n CHECK_CONDITION(i != m.end());\n return i->second.value;\n }\n};\n\nTEST_F(LimitTest, LimitRespected) {\n static const size_t kLim = 4ul * 1024 * 1024 * 1024;\n SetLimit(kLim, false);\n\n std::string statsBuf = MallocExtension::GetStats();\n std::string statsPbtxt = GetStatsInPbTxt();\n EXPECT_THAT(statsBuf, HasSubstr(absl::StrFormat(\n \"PARAMETER desired_usage_limit_bytes %u\", kLim)));\n EXPECT_THAT(statsBuf, HasSubstr(\"Number of times limit was hit: 0\"));\n EXPECT_THAT(statsPbtxt, HasSubstr(absl::StrFormat(\n \"desired_usage_limit_bytes: %u\", kLim)));\n EXPECT_THAT(statsPbtxt, HasSubstr(\"hard_limit: false\"));\n EXPECT_THAT(statsPbtxt, HasSubstr(\"limit_hits: 0\"));\n\n \/\/ Avoid failing due to usage by test itself.\n static const size_t kLimForUse = kLim * 9 \/ 10;\n \/\/ First allocate many small objects...\n size_t used = 0;\n std::vector ptrs;\n while (used < kLimForUse) {\n ptrs.push_back(malloc_pages(kPageSize));\n used += kPageSize;\n }\n DumpHeapStats(\"after allocating small objects\");\n \/\/ return much of the space, fragmented...\n bool ret = false;\n for (auto &p : ptrs) {\n if (ret) {\n free(p);\n p = nullptr;\n used -= kPageSize;\n }\n ret = !ret;\n }\n DumpHeapStats(\"after freeing many small objects\");\n \/\/ Now ensure we can re use it for large allocations.\n\n while (used < kLimForUse) {\n const size_t large = kPageSize * 10;\n ptrs.push_back(malloc_pages(large));\n used += large;\n }\n DumpHeapStats(\"after allocating large objects\");\n EXPECT_LE(physical_memory_used(), kLim);\n\n statsBuf = MallocExtension::GetStats();\n statsPbtxt = GetStatsInPbTxt();\n \/\/ The HugePageAwareAllocator hits the limit more than once.\n EXPECT_THAT(statsBuf,\n ContainsRegex(R\"(Number of times limit was hit: [1-9]\\d*)\"));\n EXPECT_THAT(statsPbtxt, ContainsRegex(R\"(limit_hits: [1-9]\\d*)\"));\n\n for (auto p : ptrs) {\n free(p);\n }\n}\n\nTEST_F(LimitTest, HardLimitRespected) {\n static const size_t kLim = 300 << 20;\n SetLimit(kLim, true);\n\n std::string statsBuf = MallocExtension::GetStats();\n std::string statsPbtxt = GetStatsInPbTxt();\n EXPECT_THAT(statsBuf,\n HasSubstr(absl::StrFormat(\n \"PARAMETER desired_usage_limit_bytes %u (hard)\", kLim)));\n EXPECT_THAT(statsPbtxt, HasSubstr(absl::StrFormat(\n \"desired_usage_limit_bytes: %u\", kLim)));\n EXPECT_THAT(statsPbtxt, HasSubstr(\"hard_limit: true\"));\n\n void *ptr = malloc_pages(50 << 20);\n ASSERT_DEATH(malloc_pages(400 << 20), \"limit\");\n free(ptr);\n SetLimit(std::numeric_limits::max(), false);\n}\n\nTEST_F(LimitTest, HardLimitRespectsNoSubrelease) {\n static const size_t kLim = 300 << 20;\n SetLimit(kLim, true);\n TCMalloc_Internal_SetHPAASubrelease(false);\n EXPECT_FALSE(TCMalloc_Internal_GetHPAASubrelease());\n\n std::string statsBuf = MallocExtension::GetStats();\n std::string statsPbtxt = GetStatsInPbTxt();\n EXPECT_THAT(statsBuf,\n HasSubstr(absl::StrFormat(\n \"PARAMETER desired_usage_limit_bytes %u (hard)\", kLim)));\n EXPECT_THAT(statsPbtxt, HasSubstr(absl::StrFormat(\n \"desired_usage_limit_bytes: %u\", kLim)));\n EXPECT_THAT(statsPbtxt, HasSubstr(\"hard_limit: true\"));\n\n ASSERT_DEATH(\n []() {\n \/\/ Allocate a bunch of medium objects, free half of them to cause some\n \/\/ fragmentation, then allocate some large objects. If we subrelease we\n \/\/ could stay under our hard limit, but if we don't then we should go\n \/\/ over.\n std::vector ptrs;\n constexpr size_t kNumMediumObjs = 400;\n constexpr size_t kNumLargeObjs = 200;\n for (size_t i = 0; i < kNumMediumObjs; i++) {\n ptrs.push_back(::operator new(512 << 10));\n }\n DumpHeapStats(\"after allocating medium objects\");\n for (size_t i = 0; i < ptrs.size(); i++) {\n if (i % 2) continue;\n ::operator delete(ptrs[i]);\n ptrs[i] = static_cast(0);\n }\n DumpHeapStats(\"after freeing half of medium objects\");\n for (size_t i = 0; i < kNumLargeObjs; i++) {\n ptrs.push_back(::operator new(1 << 20));\n }\n DumpHeapStats(\"after allocating large objects\");\n while (!ptrs.empty()) {\n ::operator delete(ptrs.back());\n ptrs.pop_back();\n }\n DumpHeapStats(\"after freeing all objects\");\n }(),\n \"limit\");\n SetLimit(std::numeric_limits::max(), false);\n}\n\n} \/\/ namespace\n} \/\/ namespace tcmalloc\n<|endoftext|>"} {"text":"\/**\n * @file lcc_main.cpp\n * @author Nishant Mehta\n *\n * Executable for Local Coordinate Coding.\n *\/\n#include \n#include \"lcc.hpp\"\n\nPROGRAM_INFO(\"Local Coordinate Coding\",\n \"An implementation of Local Coordinate Coding (LCC), which \"\n \"codes data that approximately lives on a manifold using a variation of l1-\"\n \"norm regularized sparse coding. Given a dense data matrix X with n points\"\n \" and d dimensions, LCC seeks to find a dense dictionary matrix D with k \"\n \"atoms in d dimensions, and a coding matrix Z with n points in k \"\n \"dimensions. Because of the regularization method used, the atoms in D \"\n \"should lie close to the manifold on which the data points lie.\"\n \"\\n\\n\"\n \"The original data matrix X can then be reconstructed as D * Z. Therefore,\"\n \" this program finds a representation of each point in X as a sparse linear\"\n \" combination of atoms in the dictionary D.\"\n \"\\n\\n\"\n \"The coding is found with an algorithm which alternates between a \"\n \"dictionary step, which updates the dictionary D, and a coding step, which \"\n \"updates the coding matrix Z.\"\n \"\\n\\n\"\n \"To run this program, the input matrix X must be specified (with -i), along\"\n \" with the number of atoms in the dictionary (-k). An initial dictionary \"\n \"may also be specified with the --initial_dictionary option. The l1-norm \"\n \"regularization parameter is specified with -l. For example, to run LCC on\"\n \" the dataset in data.csv using 200 atoms and an l1-regularization \"\n \"parameter of 0.1, saving the dictionary into dict.csv and the codes into \"\n \"codes.csv, use \"\n \"\\n\\n\"\n \"$ local_coordinate_coding -i data.csv -k 200 -l 0.1 -d dict.csv -c \"\n \"codes.csv\"\n \"\\n\\n\"\n \"The maximum number of iterations may be specified with the -n option. \"\n \"Optionally, the input data matrix X can be normalized before coding with \"\n \"the -N option.\");\n\nPARAM_STRING_REQ(\"input_file\", \"Filename of the input data.\", \"i\");\nPARAM_INT_REQ(\"atoms\", \"Number of atoms in the dictionary.\", \"k\");\n\nPARAM_DOUBLE(\"lambda\", \"Weighted l1-norm regularization parameter.\", \"l\", 0.0);\n\nPARAM_INT(\"max_iterations\", \"Maximum number of iterations for LCC (0 indicates \"\n \"no limit).\", \"n\", 0);\n\nPARAM_STRING(\"initial_dictionary\", \"Filename for optional initial dictionary.\",\n \"D\", \"\");\n\nPARAM_STRING(\"dictionary_file\", \"Filename to save the output dictionary to.\",\n \"d\", \"dictionary.csv\");\nPARAM_STRING(\"codes_file\", \"Filename to save the output codes to.\", \"c\",\n \"codes.csv\");\n\nPARAM_FLAG(\"normalize\", \"If set, the input data matrix will be normalized \"\n \"before coding.\", \"N\");\n\nPARAM_INT(\"seed\", \"Random seed. If 0, 'std::time(NULL)' is used.\", \"s\", 0);\n\nPARAM_DOUBLE(\"objective_tolerance\", \"Tolerance for objective function.\", \"o\",\n 0.01);\n\nusing namespace arma;\nusing namespace std;\nusing namespace mlpack;\nusing namespace mlpack::math;\nusing namespace mlpack::lcc;\nusing namespace mlpack::sparse_coding; \/\/ For NothingInitializer.\n\nint main(int argc, char* argv[])\n{\n CLI::ParseCommandLine(argc, argv);\n\n if (CLI::GetParam(\"seed\") != 0)\n RandomSeed((size_t) CLI::GetParam(\"seed\"));\n else\n RandomSeed((size_t) std::time(NULL));\n\n const double lambda = CLI::GetParam(\"lambda\");\n\n const string inputFile = CLI::GetParam(\"input_file\");\n const string dictionaryFile = CLI::GetParam(\"dictionary_file\");\n const string codesFile = CLI::GetParam(\"codes_file\");\n const string initialDictionaryFile =\n CLI::GetParam(\"initial_dictionary\");\n\n const size_t maxIterations = CLI::GetParam(\"max_iterations\");\n const size_t atoms = CLI::GetParam(\"atoms\");\n\n const bool normalize = CLI::HasParam(\"normalize\");\n\n const double objTolerance = CLI::GetParam(\"objective_tolerance\");\n\n mat input;\n data::Load(inputFile, input, true);\n\n Log::Info << \"Loaded \" << input.n_cols << \" point in \" << input.n_rows\n << \" dimensions.\" << endl;\n\n \/\/ Normalize each point if the user asked for it.\n if (normalize)\n {\n Log::Info << \"Normalizing data before coding...\" << endl;\n for (size_t i = 0; i < input.n_cols; ++i)\n input.col(i) \/= norm(input.col(i), 2);\n }\n\n \/\/ If there is an initial dictionary, be sure we do not initialize one.\n if (initialDictionaryFile != \"\")\n {\n LocalCoordinateCoding lcc(atoms, lambda, maxIterations, objTolerance);\n\n \/\/ Load initial dictionary directly into LCC object.\n data::Load(initialDictionaryFile, lcc.Dictionary(), true);\n\n \/\/ Validate size of initial dictionary.\n if (lcc.Dictionary().n_cols != atoms)\n {\n Log::Fatal << \"The initial dictionary has \" << lcc.Dictionary().n_cols\n << \" atoms, but the number of atoms was specified to be \" << atoms\n << \"!\" << endl;\n }\n\n if (lcc.Dictionary().n_rows != input.n_rows)\n {\n Log::Fatal << \"The initial dictionary has \" << lcc.Dictionary().n_rows\n << \" dimensions, but the data has \" << input.n_rows << \" dimensions!\"\n << endl;\n }\n\n \/\/ Run LCC.\n lcc.Train(input);\n\n \/\/ Save the results.\n Log::Info << \"Saving dictionary matrix to '\" << dictionaryFile << \"'.\\n\";\n data::Save(dictionaryFile, lcc.Dictionary());\n\n mat codes;\n lcc.Encode(input, codes);\n\n Log::Info << \"Saving sparse codes to '\" << codesFile << \"'.\\n\";\n data::Save(codesFile, codes);\n }\n else\n {\n \/\/ No initial dictionary.\n LocalCoordinateCoding lcc(input, atoms, lambda, maxIterations,\n objTolerance);\n\n \/\/ Save the results.\n Log::Info << \"Saving dictionary matrix to '\" << dictionaryFile << \"'.\\n\";\n data::Save(dictionaryFile, lcc.Dictionary());\n\n mat codes;\n lcc.Encode(input, codes);\n\n Log::Info << \"Saving sparse codes to '\" << codesFile << \"'.\\n\";\n data::Save(codesFile, codes);\n }\n}\nRefactor lcc program.\/**\n * @file lcc_main.cpp\n * @author Nishant Mehta\n *\n * Executable for Local Coordinate Coding.\n *\/\n#include \n#include \"lcc.hpp\"\n\nPROGRAM_INFO(\"Local Coordinate Coding\",\n \"An implementation of Local Coordinate Coding (LCC), which \"\n \"codes data that approximately lives on a manifold using a variation of l1-\"\n \"norm regularized sparse coding. Given a dense data matrix X with n points\"\n \" and d dimensions, LCC seeks to find a dense dictionary matrix D with k \"\n \"atoms in d dimensions, and a coding matrix Z with n points in k \"\n \"dimensions. Because of the regularization method used, the atoms in D \"\n \"should lie close to the manifold on which the data points lie.\"\n \"\\n\\n\"\n \"The original data matrix X can then be reconstructed as D * Z. Therefore,\"\n \" this program finds a representation of each point in X as a sparse linear\"\n \" combination of atoms in the dictionary D.\"\n \"\\n\\n\"\n \"The coding is found with an algorithm which alternates between a \"\n \"dictionary step, which updates the dictionary D, and a coding step, which \"\n \"updates the coding matrix Z.\"\n \"\\n\\n\"\n \"To run this program, the input matrix X must be specified (with -i), along\"\n \" with the number of atoms in the dictionary (-k). An initial dictionary \"\n \"may also be specified with the --initial_dictionary option. The l1-norm \"\n \"regularization parameter is specified with -l. For example, to run LCC on\"\n \" the dataset in data.csv using 200 atoms and an l1-regularization \"\n \"parameter of 0.1, saving the dictionary into dict.csv and the codes into \"\n \"codes.csv, use \"\n \"\\n\\n\"\n \"$ local_coordinate_coding -i data.csv -k 200 -l 0.1 -d dict.csv -c \"\n \"codes.csv\"\n \"\\n\\n\"\n \"The maximum number of iterations may be specified with the -n option. \"\n \"Optionally, the input data matrix X can be normalized before coding with \"\n \"the -N option.\");\n\n\/\/ Training parameters.\nPARAM_STRING(\"training_file\", \"Filename of the training data (X).\", \"t\", \"\");\nPARAM_INT(\"atoms\", \"Number of atoms in the dictionary.\", \"k\", 0);\nPARAM_DOUBLE(\"lambda\", \"Weighted l1-norm regularization parameter.\", \"l\", 0.0);\nPARAM_INT(\"max_iterations\", \"Maximum number of iterations for LCC (0 indicates \"\n \"no limit).\", \"n\", 0);\nPARAM_STRING(\"initial_dictionary\", \"Filename for optional initial dictionary.\",\n \"i\", \"\");\nPARAM_FLAG(\"normalize\", \"If set, the input data matrix will be normalized \"\n \"before coding.\", \"N\");\nPARAM_DOUBLE(\"tolerance\", \"Tolerance for objective function.\", \"o\", 0.01);\n\n\/\/ Load\/save a model.\nPARAM_STRING(\"input_model_file\", \"File containing input LCC model.\", \"m\", \"\");\nPARAM_STRING(\"output_model_file\", \"File to save trained LCC model to.\", \"M\",\n \"\");\n\n\/\/ Test on another dataset.\nPARAM_STRING(\"test_file\", \"File of test points to encode.\", \"T\", \"\");\nPARAM_STRING(\"dictionary_file\", \"Filename to save the output dictionary to.\",\n \"d\", \"\");\nPARAM_STRING(\"codes_file\", \"Filename to save the output codes to.\", \"c\", \"\");\n\nPARAM_INT(\"seed\", \"Random seed. If 0, 'std::time(NULL)' is used.\", \"s\", 0);\n\nusing namespace arma;\nusing namespace std;\nusing namespace mlpack;\nusing namespace mlpack::math;\nusing namespace mlpack::lcc;\nusing namespace mlpack::sparse_coding; \/\/ For NothingInitializer.\n\nint main(int argc, char* argv[])\n{\n CLI::ParseCommandLine(argc, argv);\n\n if (CLI::GetParam(\"seed\") != 0)\n RandomSeed((size_t) CLI::GetParam(\"seed\"));\n else\n RandomSeed((size_t) std::time(NULL));\n\n \/\/ Check for parameter validity.\n if (CLI::HasParam(\"input_model_file\") && CLI::HasParam(\"initial_dictionary\"))\n Log::Fatal << \"Cannot specify both --input_model_file (-m) and \"\n << \"--initial_dictionary (-i)!\" << endl;\n\n if (CLI::HasParam(\"training_file\") && !CLI::HasParam(\"atoms\"))\n Log::Fatal << \"If --training_file is specified, the number of atoms in the \"\n << \"dictionary must be specified with --atoms (-k)!\" << endl;\n\n if (!CLI::HasParam(\"training_file\") && !CLI::HasParam(\"input_model_file\"))\n Log::Fatal << \"One of --training_file (-t) or --input_model_file (-m) must \"\n << \"be specified!\" << endl;\n\n if (!CLI::HasParam(\"codes_file\") && !CLI::HasParam(\"dictionary_file\") &&\n !CLI::HasParam(\"output_model_file\"))\n Log::Warn << \"Neither --codes_file (-c), --dictionary_file (-d), nor \"\n << \"--output_model_file (-M) are specified; no output will be saved.\"\n << endl;\n\n if (CLI::HasParam(\"codes_file\") && !CLI::HasParam(\"test_file\"))\n Log::Fatal << \"--codes_file (-c) is specified, but no test matrix (\"\n << \"specified with --test_file or -T) is given to encode!\" << endl;\n\n if (!CLI::HasParam(\"training_file\"))\n {\n if (CLI::HasParam(\"atoms\"))\n Log::Warn << \"--atoms (-k) ignored because --training_file (-t) is not \"\n << \"specified.\" << endl;\n if (CLI::HasParam(\"lambda\"))\n Log::Warn << \"--lambda (-l) ignored because --training_file (-t) is not \"\n << \"specified.\" << endl;\n if (CLI::HasParam(\"initial_dictionary\"))\n Log::Warn << \"--initial_dictionary (-i) ignored because --training_file \"\n << \"(-t) is not specified.\" << endl;\n if (CLI::HasParam(\"max_iterations\"))\n Log::Warn << \"--max_iterations (-n) ignored because --training_file (-t) \"\n << \"is not specified.\" << endl;\n if (CLI::HasParam(\"normalize\"))\n Log::Warn << \"--normalize (-N) ignored because --training_file (-t) is \"\n << \"not specified.\" << endl;\n if (CLI::HasParam(\"tolerance\"))\n Log::Warn << \"--tolerance (-o) ignored because --training_file (-t) is \"\n << \"not specified.\" << endl;\n }\n\n \/\/ Do we have an existing model?\n LocalCoordinateCoding lcc(0, 0.0);\n if (CLI::HasParam(\"input_model_file\"))\n {\n data::Load(CLI::GetParam(\"input_model_file\"), \"lcc_model\", lcc,\n true);\n }\n\n if (CLI::HasParam(\"training_file\"))\n {\n mat matX;\n data::Load(CLI::GetParam(\"training_file\"), matX, true);\n\n \/\/ Normalize each point if the user asked for it.\n if (CLI::HasParam(\"normalize\"))\n {\n Log::Info << \"Normalizing data before coding...\" << endl;\n for (size_t i = 0; i < matX.n_cols; ++i)\n matX.col(i) \/= norm(matX.col(i), 2);\n }\n\n lcc.Lambda() = CLI::GetParam(\"lambda\");\n lcc.Atoms() = (size_t) CLI::GetParam(\"atoms\");\n lcc.MaxIterations() = (size_t) CLI::GetParam(\"max_iterations\");\n lcc.Tolerance() = CLI::GetParam(\"tolerance\");\n\n \/\/ Inform the user if we are overwriting their model.\n if (CLI::HasParam(\"input_model_file\"))\n {\n Log::Info << \"Using dictionary from existing model in '\"\n << CLI::GetParam(\"input_model_file\") << \"' as initial \"\n << \"dictionary for training.\" << endl;\n lcc.Train(matX);\n }\n else if (CLI::HasParam(\"initial_dictionary\"))\n {\n \/\/ Load initial dictionary directly into LCC object.\n data::Load(CLI::GetParam(\"initial_dictionary\"), lcc.Dictionary(),\n true);\n\n \/\/ Validate the size of the initial dictionary.\n if (lcc.Dictionary().n_cols != lcc.Atoms())\n {\n Log::Fatal << \"The initial dictionary has \" << lcc.Dictionary().n_cols\n << \" atoms, but the number of atoms was specified to be \"\n << lcc.Atoms() << \"!\" << endl;\n }\n\n if (lcc.Dictionary().n_rows != matX.n_rows)\n {\n Log::Fatal << \"The initial dictionary has \" << lcc.Dictionary().n_rows\n << \" dimensions, but the data has \" << matX.n_rows << \" dimensions!\"\n << endl;\n }\n\n \/\/ Train the model.\n lcc.Train(matX);\n }\n else\n {\n \/\/ Run with the default initialization.\n lcc.Train(matX);\n }\n }\n\n \/\/ Now, do we have any matrix to encode?\n if (CLI::HasParam(\"test_file\"))\n {\n mat matY;\n data::Load(CLI::GetParam(\"test_file\"), matY, true);\n\n if (matY.n_rows != lcc.Dictionary().n_rows)\n Log::Fatal << \"Model was trained with a dimensionality of \"\n << lcc.Dictionary().n_rows << \", but data in test file \"\n << CLI::GetParam(\"test_file\") << \" has a dimensionality of \"\n << matY.n_rows << \"!\" << endl;\n\n \/\/ Normalize each point if the user asked for it.\n if (CLI::HasParam(\"normalize\"))\n {\n Log::Info << \"Normalizing test data before coding...\" << endl;\n for (size_t i = 0; i < matY.n_cols; ++i)\n matY.col(i) \/= norm(matY.col(i), 2);\n }\n\n mat codes;\n lcc.Encode(matY, codes);\n\n if (CLI::HasParam(\"codes_file\"))\n data::Save(CLI::GetParam(\"codes_file\"), codes);\n }\n\n \/\/ Did the user want to save the dictionary?\n if (CLI::HasParam(\"dictionary_file\"))\n data::Save(CLI::GetParam(\"dictionary_file\"), lcc.Dictionary());\n\n \/\/ Did the user want to save the model?\n if (CLI::HasParam(\"output_model_file\"))\n data::Save(CLI::GetParam(\"output_model_file\"), \"lcc_model\", lcc,\n false); \/\/ Non-fatal on failure.\n}\n<|endoftext|>"} {"text":"\/**\n * @file sparse_coding_impl.hpp\n * @author Nishant Mehta\n *\n * Implementation of Sparse Coding with Dictionary Learning using l1 (LASSO) or\n * l1+l2 (Elastic Net) regularization.\n *\/\n#ifndef __MLPACK_METHODS_SPARSE_CODING_SPARSE_CODING_IMPL_HPP\n#define __MLPACK_METHODS_SPARSE_CODING_SPARSE_CODING_IMPL_HPP\n\n\/\/ In case it hasn't already been included.\n#include \"sparse_coding.hpp\"\n\nnamespace mlpack {\nnamespace sparse_coding {\n\n\/\/ TODO: parameterizable; options to methods?\n#define OBJ_TOL 1e-2 \/\/ 1E-9\n#define NEWTON_TOL 1e-6 \/\/ 1E-9\n\ntemplate\nSparseCoding::SparseCoding(const arma::mat& data,\n const size_t atoms,\n const double lambda1,\n const double lambda2) :\n atoms(atoms),\n data(data),\n codes(atoms, data.n_cols),\n lambda1(lambda1),\n lambda2(lambda2)\n{\n \/\/ Initialize the dictionary.\n DictionaryInitializer::Initialize(data, atoms, dictionary);\n}\n\ntemplate\nvoid SparseCoding::Encode(const size_t maxIterations)\n{\n double lastObjVal = DBL_MAX;\n\n \/\/ Take the initial coding step, which has to happen before entering the main\n \/\/ optimization loop.\n Log::Info << \"Initial Coding Step.\" << std::endl;\n\n OptimizeCode();\n arma::uvec adjacencies = find(codes);\n\n Log::Info << \" Sparsity level: \" << 100.0 * ((double) (adjacencies.n_elem))\n \/ ((double) (atoms * data.n_cols)) << \"%.\" << std::endl;\n Log::Info << \" Objective value: \" << Objective() << \".\" << std::endl;\n\n for (size_t t = 1; t != maxIterations; ++t)\n {\n Log::Info << \"Iteration \" << t << \" of \" << maxIterations << \".\"\n << std::endl;\n\n \/\/ First step: optimize the dictionary.\n Log::Info << \"Performing dictionary step... \" << std::endl;\n OptimizeDictionary(adjacencies);\n Log::Info << \" Objective value: \" << Objective() << \".\" << std::endl;\n\n \/\/ Second step: perform the coding.\n Log::Info << \"Performing coding step...\" << std::endl;\n OptimizeCode();\n \/\/ Get the indices of all the nonzero elements in the codes.\n adjacencies = find(codes);\n Log::Info << \" Sparsity level: \" << 100.0 * ((double) (adjacencies.n_elem))\n \/ ((double) (atoms * data.n_cols)) << \"%.\" << std::endl;\n\n \/\/ Find the new objective value and improvement so we can check for\n \/\/ convergence.\n double curObjVal = Objective();\n double improvement = lastObjVal - curObjVal;\n Log::Info << \" Objective value: \" << curObjVal << \" (improvement \"\n << std::scientific << improvement << \").\" << std::endl;\n\n \/\/ Have we converged?\n if (improvement < OBJ_TOL)\n {\n Log::Info << \"Converged within tolerance \" << OBJ_TOL << \".\\n\";\n break;\n }\n\n lastObjVal = curObjVal;\n }\n}\n\ntemplate\nvoid SparseCoding::OptimizeCode()\n{\n \/\/ When using the Cholesky version of LARS, this is correct even if\n \/\/ lambda2 > 0.\n arma::mat matGram = trans(dictionary) * dictionary;\n\n for (size_t i = 0; i < data.n_cols; ++i)\n {\n \/\/ Report progress.\n if ((i % 100) == 0)\n Log::Debug << \"Optimization at point \" << i << \".\" << std::endl;\n\n bool useCholesky = true;\n regression::LARS lars(useCholesky, matGram, lambda1, lambda2);\n\n \/\/ Create an alias of the code (using the same memory), and then LARS will\n \/\/ place the result directly into that; then we will not need to have an\n \/\/ extra copy.\n arma::vec code = codes.unsafe_col(i);\n lars.Regress(dictionary, data.unsafe_col(i), code, true);\n }\n}\n\n\/\/ Dictionary step for optimization.\ntemplate\nvoid SparseCoding::OptimizeDictionary(\n const arma::uvec& adjacencies)\n{\n \/\/ Count the number of atomic neighbors for each point x^i.\n arma::uvec neighborCounts = arma::zeros(data.n_cols, 1);\n\n if (adjacencies.n_elem > 0)\n {\n \/\/ This gets the column index. Intentional integer division.\n size_t curPointInd = (size_t) (adjacencies(0) \/ atoms);\n\n size_t nextColIndex = (curPointInd + 1) * atoms;\n for (size_t l = 1; l < adjacencies.n_elem; ++l)\n {\n \/\/ If l no longer refers to an element in this column, advance the column\n \/\/ number accordingly.\n if (adjacencies(l) >= nextColIndex)\n {\n curPointInd = (size_t) (adjacencies(l) \/ atoms);\n nextColIndex = (curPointInd + 1) * atoms;\n }\n\n ++neighborCounts(curPointInd);\n }\n }\n\n \/\/ Handle the case of inactive atoms (atoms not used in the given coding).\n std::vector inactiveAtoms;\n std::vector activeAtoms;\n activeAtoms.reserve(atoms);\n\n for (size_t j = 0; j < atoms; ++j)\n {\n if (accu(codes.row(j) != 0) == 0)\n inactiveAtoms.push_back(j);\n }\n\n const size_t nInactiveAtoms = inactiveAtoms.size();\n const size_t nActiveAtoms = atoms - nInactiveAtoms;\n\n \/\/ Efficient construction of Z restricted to active atoms.\n arma::mat matActiveZ;\n if (inactiveAtoms.empty())\n {\n matActiveZ = codes;\n }\n else\n {\n arma::uvec inactiveAtomsVec =\n arma::conv_to::from(inactiveAtoms);\n RemoveRows(codes, inactiveAtomsVec, matActiveZ);\n }\n\n if (nInactiveAtoms > 0)\n {\n Log::Warn << \"There are \" << nInactiveAtoms\n << \" inactive atoms. They will be re-initialized randomly.\\n\";\n }\n\n Log::Debug << \"Solving Dual via Newton's Method.\\n\";\n\n \/\/ Solve using Newton's method in the dual - note that the final dot\n \/\/ multiplication with inv(A) seems to be unavoidable. Although more\n \/\/ expensive, the code written this way (we use solve()) should be more\n \/\/ numerically stable than just using inv(A) for everything.\n arma::vec dualVars = arma::zeros(nActiveAtoms);\n\n \/\/vec dualVars = 1e-14 * ones(nActiveAtoms);\n\n \/\/ Method used by feature sign code - fails miserably here. Perhaps the\n \/\/ MATLAB optimizer fmincon does something clever?\n \/\/vec dualVars = 10.0 * randu(nActiveAtoms, 1);\n\n \/\/vec dualVars = diagvec(solve(dictionary, data * trans(codes))\n \/\/ - codes * trans(codes));\n \/\/for (size_t i = 0; i < dualVars.n_elem; i++)\n \/\/ if (dualVars(i) < 0)\n \/\/ dualVars(i) = 0;\n\n bool converged = false;\n arma::mat codesXT = matActiveZ * trans(data);\n arma::mat codesZT = matActiveZ * trans(matActiveZ);\n\n double improvement;\n for (size_t t = 1; !converged; ++t)\n {\n arma::mat A = codesZT + diagmat(dualVars);\n\n arma::mat matAInvZXT = solve(A, codesXT);\n\n arma::vec gradient = -(arma::sum(arma::square(matAInvZXT), 1) -\n arma::ones(nActiveAtoms));\n\n arma::mat hessian = -(-2 * (matAInvZXT * trans(matAInvZXT)) % inv(A));\n\n arma::vec searchDirection = -solve(hessian, gradient);\n\n \/\/ Armijo line search.\n const double c = 1e-4;\n double alpha = 1.0;\n const double rho = 0.9;\n double sufficientDecrease = c * dot(gradient, searchDirection);\n\n while (true)\n {\n \/\/ Calculate objective.\n double sumDualVars = sum(dualVars);\n double fOld = -(-trace(trans(codesXT) * matAInvZXT) - sumDualVars);\n double fNew = -(-trace(trans(codesXT) * solve(codesZT +\n diagmat(dualVars + alpha * searchDirection), codesXT)) -\n (sumDualVars + alpha * sum(searchDirection)));\n\n if (fNew <= fOld + alpha * sufficientDecrease)\n {\n searchDirection = alpha * searchDirection;\n improvement = fOld - fNew;\n break;\n }\n\n alpha *= rho;\n }\n\n \/\/ Take step and print useful information.\n dualVars += searchDirection;\n double normGradient = norm(gradient, 2);\n Log::Debug << \"Newton Method iteration \" << t << \":\" << std::endl;\n Log::Debug << \" Gradient norm: \" << std::scientific << normGradient\n << \".\" << std::endl;\n Log::Debug << \" Improvement: \" << std::scientific << improvement << \".\\n\";\n\n if (improvement < NEWTON_TOL)\n converged = true;\n }\n\n if (inactiveAtoms.empty())\n {\n \/\/ Directly update dictionary.\n dictionary = trans(solve(codesZT + diagmat(dualVars), codesXT));\n }\n else\n {\n arma::mat activeDictionary = trans(solve(codesZT +\n diagmat(dualVars), codesXT));\n\n \/\/ Update all atoms.\n size_t currentInactiveIndex = 0;\n for (size_t i = 0; i < atoms; ++i)\n {\n if (inactiveAtoms[currentInactiveIndex] == i)\n {\n \/\/ This atom is inactive. Reinitialize it randomly.\n dictionary.col(i) = (data.col(math::RandInt(data.n_cols)) +\n data.col(math::RandInt(data.n_cols)) +\n data.col(math::RandInt(data.n_cols)));\n\n dictionary.col(i) \/= norm(dictionary.col(i), 2);\n\n \/\/ Increment inactive index counter.\n ++currentInactiveIndex;\n }\n else\n {\n \/\/ Update estimate.\n dictionary.col(i) = activeDictionary.col(i - currentInactiveIndex);\n }\n }\n }\n}\n\n\/\/ Project each atom of the dictionary back into the unit ball (if necessary).\ntemplate\nvoid SparseCoding::ProjectDictionary()\n{\n for (size_t j = 0; j < atoms; j++)\n {\n double atomNorm = norm(dictionary.col(j), 2);\n if (atomNorm > 1)\n {\n Log::Info << \"Norm of atom \" << j << \" exceeds 1 (\" << std::scientific\n << atomNorm << \"). Shrinking...\\n\";\n dictionary.col(j) \/= atomNorm;\n }\n }\n}\n\n\/\/ Compute the objective function.\ntemplate\ndouble SparseCoding::Objective()\n{\n double l11NormZ = sum(sum(abs(codes)));\n double froNormResidual = norm(data - (dictionary * codes), \"fro\");\n\n if (lambda2 > 0)\n {\n double froNormZ = norm(codes, \"fro\");\n return 0.5 * (std::pow(froNormResidual, 2.0) + (lambda2 *\n std::pow(froNormZ, 2.0))) + (lambda1 * l11NormZ);\n }\n else \/\/ It can be simpler.\n {\n return 0.5 * std::pow(froNormResidual, 2.0) + lambda1 * l11NormZ;\n }\n}\n\nvoid RemoveRows(const arma::mat& X,\n const arma::uvec& rowsToRemove,\n arma::mat& modX)\n{\n const size_t cols = X.n_cols;\n const size_t rows = X.n_rows;\n const size_t nRemove = rowsToRemove.n_elem;\n const size_t nKeep = rows - nRemove;\n\n if (nRemove == 0)\n {\n modX = X;\n }\n else\n {\n modX.set_size(nKeep, cols);\n\n size_t curRow = 0;\n size_t removeInd = 0;\n \/\/ First, check 0 to first row to remove.\n if (rowsToRemove(0) > 0)\n {\n \/\/ Note that this implies that n_rows > 1.\n size_t height = rowsToRemove(0);\n modX(arma::span(curRow, curRow + height - 1), arma::span::all) =\n X(arma::span(0, rowsToRemove(0) - 1), arma::span::all);\n curRow += height;\n }\n \/\/ Now, check i'th row to remove to (i + 1)'th row to remove, until i is the\n \/\/ penultimate row.\n while (removeInd < nRemove - 1)\n {\n size_t height = rowsToRemove[removeInd + 1] -\n rowsToRemove[removeInd] - 1;\n\n if (height > 0)\n {\n modX(arma::span(curRow, curRow + height - 1), arma::span::all) =\n X(arma::span(rowsToRemove[removeInd] + 1,\n rowsToRemove[removeInd + 1] - 1), arma::span::all);\n curRow += height;\n }\n\n removeInd++;\n }\n\n \/\/ Now that i is the last row to remove, check last row to remove to last\n \/\/ row.\n if (rowsToRemove[removeInd] < rows - 1)\n {\n modX(arma::span(curRow, nKeep - 1), arma::span::all) =\n X(arma::span(rowsToRemove[removeInd] + 1, rows - 1),\n arma::span::all);\n }\n }\n}\n\n}; \/\/ namespace sparse_coding\n}; \/\/ namespace mlpack\n\n#endif\nAvoid a matrix copy for matActiveZ and potentially speed up gradient calculation by avoiding instantiation of arma::ones (Armadillo may have already been smart enough to avoid that anyway).\/**\n * @file sparse_coding_impl.hpp\n * @author Nishant Mehta\n *\n * Implementation of Sparse Coding with Dictionary Learning using l1 (LASSO) or\n * l1+l2 (Elastic Net) regularization.\n *\/\n#ifndef __MLPACK_METHODS_SPARSE_CODING_SPARSE_CODING_IMPL_HPP\n#define __MLPACK_METHODS_SPARSE_CODING_SPARSE_CODING_IMPL_HPP\n\n\/\/ In case it hasn't already been included.\n#include \"sparse_coding.hpp\"\n\nnamespace mlpack {\nnamespace sparse_coding {\n\n\/\/ TODO: parameterizable; options to methods?\n#define OBJ_TOL 1e-2 \/\/ 1E-9\n#define NEWTON_TOL 1e-6 \/\/ 1E-9\n\ntemplate\nSparseCoding::SparseCoding(const arma::mat& data,\n const size_t atoms,\n const double lambda1,\n const double lambda2) :\n atoms(atoms),\n data(data),\n codes(atoms, data.n_cols),\n lambda1(lambda1),\n lambda2(lambda2)\n{\n \/\/ Initialize the dictionary.\n DictionaryInitializer::Initialize(data, atoms, dictionary);\n}\n\ntemplate\nvoid SparseCoding::Encode(const size_t maxIterations)\n{\n double lastObjVal = DBL_MAX;\n\n \/\/ Take the initial coding step, which has to happen before entering the main\n \/\/ optimization loop.\n Log::Info << \"Initial Coding Step.\" << std::endl;\n\n OptimizeCode();\n arma::uvec adjacencies = find(codes);\n\n Log::Info << \" Sparsity level: \" << 100.0 * ((double) (adjacencies.n_elem))\n \/ ((double) (atoms * data.n_cols)) << \"%.\" << std::endl;\n Log::Info << \" Objective value: \" << Objective() << \".\" << std::endl;\n\n for (size_t t = 1; t != maxIterations; ++t)\n {\n Log::Info << \"Iteration \" << t << \" of \" << maxIterations << \".\"\n << std::endl;\n\n \/\/ First step: optimize the dictionary.\n Log::Info << \"Performing dictionary step... \" << std::endl;\n OptimizeDictionary(adjacencies);\n Log::Info << \" Objective value: \" << Objective() << \".\" << std::endl;\n\n \/\/ Second step: perform the coding.\n Log::Info << \"Performing coding step...\" << std::endl;\n OptimizeCode();\n \/\/ Get the indices of all the nonzero elements in the codes.\n adjacencies = find(codes);\n Log::Info << \" Sparsity level: \" << 100.0 * ((double) (adjacencies.n_elem))\n \/ ((double) (atoms * data.n_cols)) << \"%.\" << std::endl;\n\n \/\/ Find the new objective value and improvement so we can check for\n \/\/ convergence.\n double curObjVal = Objective();\n double improvement = lastObjVal - curObjVal;\n Log::Info << \" Objective value: \" << curObjVal << \" (improvement \"\n << std::scientific << improvement << \").\" << std::endl;\n\n \/\/ Have we converged?\n if (improvement < OBJ_TOL)\n {\n Log::Info << \"Converged within tolerance \" << OBJ_TOL << \".\\n\";\n break;\n }\n\n lastObjVal = curObjVal;\n }\n}\n\ntemplate\nvoid SparseCoding::OptimizeCode()\n{\n \/\/ When using the Cholesky version of LARS, this is correct even if\n \/\/ lambda2 > 0.\n arma::mat matGram = trans(dictionary) * dictionary;\n\n for (size_t i = 0; i < data.n_cols; ++i)\n {\n \/\/ Report progress.\n if ((i % 100) == 0)\n Log::Debug << \"Optimization at point \" << i << \".\" << std::endl;\n\n bool useCholesky = true;\n regression::LARS lars(useCholesky, matGram, lambda1, lambda2);\n\n \/\/ Create an alias of the code (using the same memory), and then LARS will\n \/\/ place the result directly into that; then we will not need to have an\n \/\/ extra copy.\n arma::vec code = codes.unsafe_col(i);\n lars.Regress(dictionary, data.unsafe_col(i), code, true);\n }\n}\n\n\/\/ Dictionary step for optimization.\ntemplate\nvoid SparseCoding::OptimizeDictionary(\n const arma::uvec& adjacencies)\n{\n \/\/ Count the number of atomic neighbors for each point x^i.\n arma::uvec neighborCounts = arma::zeros(data.n_cols, 1);\n\n if (adjacencies.n_elem > 0)\n {\n \/\/ This gets the column index. Intentional integer division.\n size_t curPointInd = (size_t) (adjacencies(0) \/ atoms);\n\n size_t nextColIndex = (curPointInd + 1) * atoms;\n for (size_t l = 1; l < adjacencies.n_elem; ++l)\n {\n \/\/ If l no longer refers to an element in this column, advance the column\n \/\/ number accordingly.\n if (adjacencies(l) >= nextColIndex)\n {\n curPointInd = (size_t) (adjacencies(l) \/ atoms);\n nextColIndex = (curPointInd + 1) * atoms;\n }\n\n ++neighborCounts(curPointInd);\n }\n }\n\n \/\/ Handle the case of inactive atoms (atoms not used in the given coding).\n std::vector inactiveAtoms;\n std::vector activeAtoms;\n activeAtoms.reserve(atoms);\n\n for (size_t j = 0; j < atoms; ++j)\n {\n if (accu(codes.row(j) != 0) == 0)\n inactiveAtoms.push_back(j);\n }\n\n const size_t nInactiveAtoms = inactiveAtoms.size();\n const size_t nActiveAtoms = atoms - nInactiveAtoms;\n\n \/\/ Efficient construction of Z restricted to active atoms.\n arma::mat matActiveZ;\n if (!inactiveAtoms.empty())\n {\n arma::uvec inactiveAtomsVec =\n arma::conv_to::from(inactiveAtoms);\n RemoveRows(codes, inactiveAtomsVec, matActiveZ);\n }\n\n if (nInactiveAtoms > 0)\n {\n Log::Warn << \"There are \" << nInactiveAtoms\n << \" inactive atoms. They will be re-initialized randomly.\\n\";\n }\n\n Log::Debug << \"Solving Dual via Newton's Method.\\n\";\n\n \/\/ Solve using Newton's method in the dual - note that the final dot\n \/\/ multiplication with inv(A) seems to be unavoidable. Although more\n \/\/ expensive, the code written this way (we use solve()) should be more\n \/\/ numerically stable than just using inv(A) for everything.\n arma::vec dualVars = arma::zeros(nActiveAtoms);\n\n \/\/vec dualVars = 1e-14 * ones(nActiveAtoms);\n\n \/\/ Method used by feature sign code - fails miserably here. Perhaps the\n \/\/ MATLAB optimizer fmincon does something clever?\n \/\/vec dualVars = 10.0 * randu(nActiveAtoms, 1);\n\n \/\/vec dualVars = diagvec(solve(dictionary, data * trans(codes))\n \/\/ - codes * trans(codes));\n \/\/for (size_t i = 0; i < dualVars.n_elem; i++)\n \/\/ if (dualVars(i) < 0)\n \/\/ dualVars(i) = 0;\n\n bool converged = false;\n\n \/\/ If we have any inactive atoms, we must construct these differently.\n arma::mat codesXT;\n arma::mat codesZT;\n\n if (inactiveAtoms.empty())\n {\n codesXT = codes * trans(data);\n codesZT = codes * trans(codes);\n }\n else\n {\n codesXT = matActiveZ * trans(data);\n codesZT = matActiveZ * trans(matActiveZ);\n }\n\n double improvement;\n for (size_t t = 1; !converged; ++t)\n {\n arma::mat A = codesZT + diagmat(dualVars);\n\n arma::mat matAInvZXT = solve(A, codesXT);\n\n arma::vec gradient = -arma::sum(arma::square(matAInvZXT), 1);\n gradient += 1;\n\n arma::mat hessian = -(-2 * (matAInvZXT * trans(matAInvZXT)) % inv(A));\n\n arma::vec searchDirection = -solve(hessian, gradient);\n\n \/\/ Armijo line search.\n const double c = 1e-4;\n double alpha = 1.0;\n const double rho = 0.9;\n double sufficientDecrease = c * dot(gradient, searchDirection);\n\n while (true)\n {\n \/\/ Calculate objective.\n double sumDualVars = sum(dualVars);\n double fOld = -(-trace(trans(codesXT) * matAInvZXT) - sumDualVars);\n double fNew = -(-trace(trans(codesXT) * solve(codesZT +\n diagmat(dualVars + alpha * searchDirection), codesXT)) -\n (sumDualVars + alpha * sum(searchDirection)));\n\n if (fNew <= fOld + alpha * sufficientDecrease)\n {\n searchDirection = alpha * searchDirection;\n improvement = fOld - fNew;\n break;\n }\n\n alpha *= rho;\n }\n\n \/\/ Take step and print useful information.\n dualVars += searchDirection;\n double normGradient = norm(gradient, 2);\n Log::Debug << \"Newton Method iteration \" << t << \":\" << std::endl;\n Log::Debug << \" Gradient norm: \" << std::scientific << normGradient\n << \".\" << std::endl;\n Log::Debug << \" Improvement: \" << std::scientific << improvement << \".\\n\";\n\n if (improvement < NEWTON_TOL)\n converged = true;\n }\n\n if (inactiveAtoms.empty())\n {\n \/\/ Directly update dictionary.\n dictionary = trans(solve(codesZT + diagmat(dualVars), codesXT));\n }\n else\n {\n arma::mat activeDictionary = trans(solve(codesZT +\n diagmat(dualVars), codesXT));\n\n \/\/ Update all atoms.\n size_t currentInactiveIndex = 0;\n for (size_t i = 0; i < atoms; ++i)\n {\n if (inactiveAtoms[currentInactiveIndex] == i)\n {\n \/\/ This atom is inactive. Reinitialize it randomly.\n dictionary.col(i) = (data.col(math::RandInt(data.n_cols)) +\n data.col(math::RandInt(data.n_cols)) +\n data.col(math::RandInt(data.n_cols)));\n\n dictionary.col(i) \/= norm(dictionary.col(i), 2);\n\n \/\/ Increment inactive index counter.\n ++currentInactiveIndex;\n }\n else\n {\n \/\/ Update estimate.\n dictionary.col(i) = activeDictionary.col(i - currentInactiveIndex);\n }\n }\n }\n}\n\n\/\/ Project each atom of the dictionary back into the unit ball (if necessary).\ntemplate\nvoid SparseCoding::ProjectDictionary()\n{\n for (size_t j = 0; j < atoms; j++)\n {\n double atomNorm = norm(dictionary.col(j), 2);\n if (atomNorm > 1)\n {\n Log::Info << \"Norm of atom \" << j << \" exceeds 1 (\" << std::scientific\n << atomNorm << \"). Shrinking...\\n\";\n dictionary.col(j) \/= atomNorm;\n }\n }\n}\n\n\/\/ Compute the objective function.\ntemplate\ndouble SparseCoding::Objective()\n{\n double l11NormZ = sum(sum(abs(codes)));\n double froNormResidual = norm(data - (dictionary * codes), \"fro\");\n\n if (lambda2 > 0)\n {\n double froNormZ = norm(codes, \"fro\");\n return 0.5 * (std::pow(froNormResidual, 2.0) + (lambda2 *\n std::pow(froNormZ, 2.0))) + (lambda1 * l11NormZ);\n }\n else \/\/ It can be simpler.\n {\n return 0.5 * std::pow(froNormResidual, 2.0) + lambda1 * l11NormZ;\n }\n}\n\nvoid RemoveRows(const arma::mat& X,\n const arma::uvec& rowsToRemove,\n arma::mat& modX)\n{\n const size_t cols = X.n_cols;\n const size_t rows = X.n_rows;\n const size_t nRemove = rowsToRemove.n_elem;\n const size_t nKeep = rows - nRemove;\n\n if (nRemove == 0)\n {\n modX = X;\n }\n else\n {\n modX.set_size(nKeep, cols);\n\n size_t curRow = 0;\n size_t removeInd = 0;\n \/\/ First, check 0 to first row to remove.\n if (rowsToRemove(0) > 0)\n {\n \/\/ Note that this implies that n_rows > 1.\n size_t height = rowsToRemove(0);\n modX(arma::span(curRow, curRow + height - 1), arma::span::all) =\n X(arma::span(0, rowsToRemove(0) - 1), arma::span::all);\n curRow += height;\n }\n \/\/ Now, check i'th row to remove to (i + 1)'th row to remove, until i is the\n \/\/ penultimate row.\n while (removeInd < nRemove - 1)\n {\n size_t height = rowsToRemove[removeInd + 1] -\n rowsToRemove[removeInd] - 1;\n\n if (height > 0)\n {\n modX(arma::span(curRow, curRow + height - 1), arma::span::all) =\n X(arma::span(rowsToRemove[removeInd] + 1,\n rowsToRemove[removeInd + 1] - 1), arma::span::all);\n curRow += height;\n }\n\n removeInd++;\n }\n\n \/\/ Now that i is the last row to remove, check last row to remove to last\n \/\/ row.\n if (rowsToRemove[removeInd] < rows - 1)\n {\n modX(arma::span(curRow, nKeep - 1), arma::span::all) =\n X(arma::span(rowsToRemove[removeInd] + 1, rows - 1),\n arma::span::all);\n }\n }\n}\n\n}; \/\/ namespace sparse_coding\n}; \/\/ namespace mlpack\n\n#endif\n<|endoftext|>"} {"text":"\/**\n * @file\n * @brief Implementation of ROOT data file reader module\n * @copyright Copyright (c) 2017 CERN and the Allpix Squared authors.\n * This software is distributed under the terms of the MIT License, copied verbatim in the file \"LICENSE.md\".\n * In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an\n * Intergovernmental Organization or submit itself to any jurisdiction.\n *\/\n\n#include \"ROOTObjectReaderModule.hpp\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"core\/messenger\/Messenger.hpp\"\n#include \"core\/utils\/log.h\"\n#include \"core\/utils\/type.h\"\n\n#include \"objects\/Object.hpp\"\n#include \"objects\/objects.h\"\n\n#include \"core\/utils\/type.h\"\n\nusing namespace allpix;\n\nROOTObjectReaderModule::ROOTObjectReaderModule(Configuration& config, Messenger* messenger, GeometryManager* geo_mgr)\n : Module(config), messenger_(messenger), geo_mgr_(geo_mgr) {}\n\n\/**\n * @note Objects cannot be stored in smart pointers due to internal ROOT logic\n *\/\nROOTObjectReaderModule::~ROOTObjectReaderModule() {\n for(auto message_inf : message_info_array_) {\n delete message_inf.objects;\n }\n}\n\n\/**\n * Adds lambda function map to convert a vector of generic objects to a templated message containing this particular type of\n * object from its typeid.\n *\/\ntemplate static void add_creator(ROOTObjectReaderModule::MessageCreatorMap& map) {\n map[typeid(T)] = [&](std::vector objects, std::shared_ptr detector = nullptr) {\n std::vector data;\n for(auto& object : objects) {\n data.emplace_back(std::move(*static_cast(object)));\n }\n\n if(detector == nullptr) {\n return std::make_shared>(data);\n }\n return std::make_shared>(data, detector);\n };\n}\n\n\/**\n * Uses SFINAE trick to call the add_creator function for all template arguments of a container class. Used to add creators\n * for every object in a tuple of objects.\n *\/\ntemplate