<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/tab_contents/tab_specific_content_settings.h"

#include "base/utf_string_conversions.h"
#include "chrome/browser/browsing_data_appcache_helper.h"
#include "chrome/browser/browsing_data_database_helper.h"
#include "chrome/browser/browsing_data_indexed_db_helper.h"
#include "chrome/browser/browsing_data_local_storage_helper.h"
#include "chrome/browser/cookies_tree_model.h"
#include "chrome/browser/prerender/prerender_manager.h"
#include "net/base/cookie_monster.h"

bool TabSpecificContentSettings::LocalSharedObjectsContainer::empty() const {
  return cookies_->GetAllCookies().empty() &&
      appcaches_->empty() &&
      databases_->empty() &&
      indexed_dbs_->empty() &&
      local_storages_->empty() &&
      session_storages_->empty();
}

bool TabSpecificContentSettings::IsContentBlocked(
    ContentSettingsType content_type) const {
  DCHECK(content_type != CONTENT_SETTINGS_TYPE_GEOLOCATION)
      << "Geolocation settings handled by ContentSettingGeolocationImageModel";
  DCHECK(content_type != CONTENT_SETTINGS_TYPE_NOTIFICATIONS)
      << "Notifications settings handled by "
      << "ContentSettingsNotificationsImageModel";

  if (content_type == CONTENT_SETTINGS_TYPE_IMAGES ||
      content_type == CONTENT_SETTINGS_TYPE_JAVASCRIPT ||
      content_type == CONTENT_SETTINGS_TYPE_PLUGINS ||
      content_type == CONTENT_SETTINGS_TYPE_COOKIES ||
      content_type == CONTENT_SETTINGS_TYPE_POPUPS)
    return content_blocked_[content_type];

  NOTREACHED();
  return false;
}

bool TabSpecificContentSettings::IsBlockageIndicated(
    ContentSettingsType content_type) const {
  return content_blockage_indicated_to_user_[content_type];
}

void TabSpecificContentSettings::SetBlockageHasBeenIndicated(
    ContentSettingsType content_type) {
  content_blockage_indicated_to_user_[content_type] = true;
}

bool TabSpecificContentSettings::IsContentAccessed(
    ContentSettingsType content_type) const {
  // This method currently only returns meaningful values for cookies.
  if (content_type != CONTENT_SETTINGS_TYPE_COOKIES)
    return false;

  return content_accessed_[content_type];
}

const std::set<std::string>&
    TabSpecificContentSettings::BlockedResourcesForType(
        ContentSettingsType content_type) const {
  if (blocked_resources_[content_type].get()) {
    return *blocked_resources_[content_type];
  } else {
    static std::set<std::string> empty_set;
    return empty_set;
  }
}

void TabSpecificContentSettings::AddBlockedResource(
    ContentSettingsType content_type,
    const std::string& resource_identifier) {
  if (!blocked_resources_[content_type].get())
    blocked_resources_[content_type].reset(new std::set<std::string>());
  blocked_resources_[content_type]->insert(resource_identifier);
}

void TabSpecificContentSettings::OnContentBlocked(
    ContentSettingsType type,
    const std::string& resource_identifier) {
  DCHECK(type != CONTENT_SETTINGS_TYPE_GEOLOCATION)
      << "Geolocation settings handled by OnGeolocationPermissionSet";
  content_accessed_[type] = true;
  if (!resource_identifier.empty())
    AddBlockedResource(type, resource_identifier);
  if (!content_blocked_[type]) {
    content_blocked_[type] = true;
    if (delegate_)
      delegate_->OnContentSettingsAccessed(true);
  }
}

void TabSpecificContentSettings::OnContentAccessed(ContentSettingsType type) {
  DCHECK(type != CONTENT_SETTINGS_TYPE_GEOLOCATION)
      << "Geolocation settings handled by OnGeolocationPermissionSet";
  if (!content_accessed_[type]) {
    content_accessed_[type] = true;
    if (delegate_)
      delegate_->OnContentSettingsAccessed(false);
  }
}

void TabSpecificContentSettings::OnCookiesRead(
    const GURL& url,
    const net::CookieList& cookie_list,
    bool blocked_by_policy) {
  if (cookie_list.empty())
    return;
  LocalSharedObjectsContainer& container = blocked_by_policy ?
      blocked_local_shared_objects_ : allowed_local_shared_objects_;
  typedef net::CookieList::const_iterator cookie_iterator;
  for (cookie_iterator cookie = cookie_list.begin();
       cookie != cookie_list.end(); ++cookie) {
    container.cookies()->ValidateMap(prerender::PrerenderManager::GetMode());
    container.cookies()->SetCookieWithDetails(url,
                                              cookie->Name(),
                                              cookie->Value(),
                                              cookie->Domain(),
                                              cookie->Path(),
                                              cookie->ExpiryDate(),
                                              cookie->IsSecure(),
                                              cookie->IsHttpOnly());
    container.cookies()->ValidateMap(prerender::PrerenderManager::GetMode());
  }
  if (blocked_by_policy)
    OnContentBlocked(CONTENT_SETTINGS_TYPE_COOKIES, std::string());
  else
    OnContentAccessed(CONTENT_SETTINGS_TYPE_COOKIES);
}

void TabSpecificContentSettings::OnCookieChanged(
    const GURL& url,
    const std::string& cookie_line,
    const net::CookieOptions& options,
    bool blocked_by_policy) {
  if (blocked_by_policy) {
    blocked_local_shared_objects_.cookies()->ValidateMap(
        prerender::PrerenderManager::GetMode());
    blocked_local_shared_objects_.cookies()->SetCookieWithOptions(
        url, cookie_line, options);
    blocked_local_shared_objects_.cookies()->ValidateMap(
        prerender::PrerenderManager::GetMode());
    OnContentBlocked(CONTENT_SETTINGS_TYPE_COOKIES, std::string());
  } else {
    allowed_local_shared_objects_.cookies()->ValidateMap(
        prerender::PrerenderManager::GetMode());
    allowed_local_shared_objects_.cookies()->SetCookieWithOptions(
        url, cookie_line, options);
    allowed_local_shared_objects_.cookies()->ValidateMap(
        prerender::PrerenderManager::GetMode());
    OnContentAccessed(CONTENT_SETTINGS_TYPE_COOKIES);
  }
}

void TabSpecificContentSettings::OnIndexedDBAccessed(
    const GURL& url,
    const string16& description,
    bool blocked_by_policy) {
  if (blocked_by_policy) {
    blocked_local_shared_objects_.indexed_dbs()->AddIndexedDB(
        url, description);
    OnContentBlocked(CONTENT_SETTINGS_TYPE_COOKIES, std::string());
  }else {
    allowed_local_shared_objects_.indexed_dbs()->AddIndexedDB(
        url, description);
    OnContentAccessed(CONTENT_SETTINGS_TYPE_COOKIES);
  }
}

void TabSpecificContentSettings::OnLocalStorageAccessed(
    const GURL& url,
    DOMStorageType storage_type,
    bool blocked_by_policy) {
  LocalSharedObjectsContainer& container = blocked_by_policy ?
      blocked_local_shared_objects_ : allowed_local_shared_objects_;
  CannedBrowsingDataLocalStorageHelper* helper =
      storage_type == DOM_STORAGE_LOCAL ?
          container.local_storages() : container.session_storages();
  helper->AddLocalStorage(url);

  if (blocked_by_policy)
    OnContentBlocked(CONTENT_SETTINGS_TYPE_COOKIES, std::string());
  else
    OnContentAccessed(CONTENT_SETTINGS_TYPE_COOKIES);
}

void TabSpecificContentSettings::OnWebDatabaseAccessed(
    const GURL& url,
    const string16& name,
    const string16& display_name,
    unsigned long estimated_size,
    bool blocked_by_policy) {
  if (blocked_by_policy) {
    blocked_local_shared_objects_.databases()->AddDatabase(
        url, UTF16ToUTF8(name), UTF16ToUTF8(display_name));
    OnContentBlocked(CONTENT_SETTINGS_TYPE_COOKIES, std::string());
  } else {
    allowed_local_shared_objects_.databases()->AddDatabase(
        url, UTF16ToUTF8(name), UTF16ToUTF8(display_name));
    OnContentAccessed(CONTENT_SETTINGS_TYPE_COOKIES);
  }
}

void TabSpecificContentSettings::OnAppCacheAccessed(
    const GURL& manifest_url, bool blocked_by_policy) {
  if (blocked_by_policy) {
    blocked_local_shared_objects_.appcaches()->AddAppCache(manifest_url);
    OnContentBlocked(CONTENT_SETTINGS_TYPE_COOKIES, std::string());
  } else {
    allowed_local_shared_objects_.appcaches()->AddAppCache(manifest_url);
    OnContentAccessed(CONTENT_SETTINGS_TYPE_COOKIES);
  }
}

void TabSpecificContentSettings::OnGeolocationPermissionSet(
    const GURL& requesting_origin,
    bool allowed) {
  geolocation_settings_state_.OnGeolocationPermissionSet(requesting_origin,
                                                         allowed);
  if (delegate_)
    delegate_->OnContentSettingsAccessed(!allowed);
}

TabSpecificContentSettings::TabSpecificContentSettings(
    Delegate* delegate, Profile* profile)
    : allowed_local_shared_objects_(profile),
      blocked_local_shared_objects_(profile),
      geolocation_settings_state_(profile),
      load_plugins_link_enabled_(true),
      delegate_(NULL) {
  ClearBlockedContentSettingsExceptForCookies();
  ClearCookieSpecificContentSettings();
  delegate_ = delegate;
}

void TabSpecificContentSettings::ClearBlockedContentSettingsExceptForCookies() {
  for (size_t i = 0; i < arraysize(content_blocked_); ++i) {
    if (i == CONTENT_SETTINGS_TYPE_COOKIES)
      continue;
    blocked_resources_[i].reset();
    content_blocked_[i] = false;
    content_accessed_[i] = false;
    content_blockage_indicated_to_user_[i] = false;
  }
  load_plugins_link_enabled_ = true;
  if (delegate_)
    delegate_->OnContentSettingsAccessed(false);
}

void TabSpecificContentSettings::ClearCookieSpecificContentSettings() {
  blocked_local_shared_objects_.Reset();
  allowed_local_shared_objects_.Reset();
  content_blocked_[CONTENT_SETTINGS_TYPE_COOKIES] = false;
  content_accessed_[CONTENT_SETTINGS_TYPE_COOKIES] = false;
  content_blockage_indicated_to_user_[CONTENT_SETTINGS_TYPE_COOKIES] = false;
  if (delegate_)
    delegate_->OnContentSettingsAccessed(false);
}

void TabSpecificContentSettings::SetPopupsBlocked(bool blocked) {
  content_blocked_[CONTENT_SETTINGS_TYPE_POPUPS] = blocked;
  content_blockage_indicated_to_user_[CONTENT_SETTINGS_TYPE_POPUPS] = false;
  if (delegate_)
    delegate_->OnContentSettingsAccessed(blocked);
}

void TabSpecificContentSettings::GeolocationDidNavigate(
      const NavigationController::LoadCommittedDetails& details) {
  geolocation_settings_state_.DidNavigate(details);
}

void TabSpecificContentSettings::ClearGeolocationContentSettings() {
  geolocation_settings_state_.ClearStateMap();
}

CookiesTreeModel* TabSpecificContentSettings::GetAllowedCookiesTreeModel() {
  return allowed_local_shared_objects_.GetCookiesTreeModel();
}

CookiesTreeModel* TabSpecificContentSettings::GetBlockedCookiesTreeModel() {
  return blocked_local_shared_objects_.GetCookiesTreeModel();
}

TabSpecificContentSettings::LocalSharedObjectsContainer::
    LocalSharedObjectsContainer(Profile* profile)
    : cookies_(new net::CookieMonster(NULL, NULL)),
      appcaches_(new CannedBrowsingDataAppCacheHelper(profile)),
      databases_(new CannedBrowsingDataDatabaseHelper(profile)),
      indexed_dbs_(new CannedBrowsingDataIndexedDBHelper(profile)),
      local_storages_(new CannedBrowsingDataLocalStorageHelper(profile)),
      session_storages_(new CannedBrowsingDataLocalStorageHelper(profile)) {
}

TabSpecificContentSettings::LocalSharedObjectsContainer::
    ~LocalSharedObjectsContainer() {
  cookies_->ValidateMap(prerender::PrerenderManager::GetMode());
}

void TabSpecificContentSettings::LocalSharedObjectsContainer::Reset() {
  cookies_->ValidateMap(prerender::PrerenderManager::GetMode());
  cookies_->DeleteAll(false);
  cookies_->ValidateMap(prerender::PrerenderManager::GetMode());
  appcaches_->Reset();
  databases_->Reset();
  indexed_dbs_->Reset();
  local_storages_->Reset();
  session_storages_->Reset();
}

CookiesTreeModel*
TabSpecificContentSettings::LocalSharedObjectsContainer::GetCookiesTreeModel() {
  return new CookiesTreeModel(cookies_,
                              databases_,
                              local_storages_,
                              session_storages_,
                              appcaches_,
                              indexed_dbs_);
}
<commit_msg>Replace the cookie monster on navigations instead of reusing it.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/tab_contents/tab_specific_content_settings.h"

#include "base/utf_string_conversions.h"
#include "chrome/browser/browsing_data_appcache_helper.h"
#include "chrome/browser/browsing_data_database_helper.h"
#include "chrome/browser/browsing_data_indexed_db_helper.h"
#include "chrome/browser/browsing_data_local_storage_helper.h"
#include "chrome/browser/cookies_tree_model.h"
#include "chrome/browser/prerender/prerender_manager.h"
#include "net/base/cookie_monster.h"

bool TabSpecificContentSettings::LocalSharedObjectsContainer::empty() const {
  return cookies_->GetAllCookies().empty() &&
      appcaches_->empty() &&
      databases_->empty() &&
      indexed_dbs_->empty() &&
      local_storages_->empty() &&
      session_storages_->empty();
}

bool TabSpecificContentSettings::IsContentBlocked(
    ContentSettingsType content_type) const {
  DCHECK(content_type != CONTENT_SETTINGS_TYPE_GEOLOCATION)
      << "Geolocation settings handled by ContentSettingGeolocationImageModel";
  DCHECK(content_type != CONTENT_SETTINGS_TYPE_NOTIFICATIONS)
      << "Notifications settings handled by "
      << "ContentSettingsNotificationsImageModel";

  if (content_type == CONTENT_SETTINGS_TYPE_IMAGES ||
      content_type == CONTENT_SETTINGS_TYPE_JAVASCRIPT ||
      content_type == CONTENT_SETTINGS_TYPE_PLUGINS ||
      content_type == CONTENT_SETTINGS_TYPE_COOKIES ||
      content_type == CONTENT_SETTINGS_TYPE_POPUPS)
    return content_blocked_[content_type];

  NOTREACHED();
  return false;
}

bool TabSpecificContentSettings::IsBlockageIndicated(
    ContentSettingsType content_type) const {
  return content_blockage_indicated_to_user_[content_type];
}

void TabSpecificContentSettings::SetBlockageHasBeenIndicated(
    ContentSettingsType content_type) {
  content_blockage_indicated_to_user_[content_type] = true;
}

bool TabSpecificContentSettings::IsContentAccessed(
    ContentSettingsType content_type) const {
  // This method currently only returns meaningful values for cookies.
  if (content_type != CONTENT_SETTINGS_TYPE_COOKIES)
    return false;

  return content_accessed_[content_type];
}

const std::set<std::string>&
    TabSpecificContentSettings::BlockedResourcesForType(
        ContentSettingsType content_type) const {
  if (blocked_resources_[content_type].get()) {
    return *blocked_resources_[content_type];
  } else {
    static std::set<std::string> empty_set;
    return empty_set;
  }
}

void TabSpecificContentSettings::AddBlockedResource(
    ContentSettingsType content_type,
    const std::string& resource_identifier) {
  if (!blocked_resources_[content_type].get())
    blocked_resources_[content_type].reset(new std::set<std::string>());
  blocked_resources_[content_type]->insert(resource_identifier);
}

void TabSpecificContentSettings::OnContentBlocked(
    ContentSettingsType type,
    const std::string& resource_identifier) {
  DCHECK(type != CONTENT_SETTINGS_TYPE_GEOLOCATION)
      << "Geolocation settings handled by OnGeolocationPermissionSet";
  content_accessed_[type] = true;
  if (!resource_identifier.empty())
    AddBlockedResource(type, resource_identifier);
  if (!content_blocked_[type]) {
    content_blocked_[type] = true;
    if (delegate_)
      delegate_->OnContentSettingsAccessed(true);
  }
}

void TabSpecificContentSettings::OnContentAccessed(ContentSettingsType type) {
  DCHECK(type != CONTENT_SETTINGS_TYPE_GEOLOCATION)
      << "Geolocation settings handled by OnGeolocationPermissionSet";
  if (!content_accessed_[type]) {
    content_accessed_[type] = true;
    if (delegate_)
      delegate_->OnContentSettingsAccessed(false);
  }
}

void TabSpecificContentSettings::OnCookiesRead(
    const GURL& url,
    const net::CookieList& cookie_list,
    bool blocked_by_policy) {
  if (cookie_list.empty())
    return;
  LocalSharedObjectsContainer& container = blocked_by_policy ?
      blocked_local_shared_objects_ : allowed_local_shared_objects_;
  typedef net::CookieList::const_iterator cookie_iterator;
  for (cookie_iterator cookie = cookie_list.begin();
       cookie != cookie_list.end(); ++cookie) {
    container.cookies()->ValidateMap(prerender::PrerenderManager::GetMode());
    container.cookies()->SetCookieWithDetails(url,
                                              cookie->Name(),
                                              cookie->Value(),
                                              cookie->Domain(),
                                              cookie->Path(),
                                              cookie->ExpiryDate(),
                                              cookie->IsSecure(),
                                              cookie->IsHttpOnly());
    container.cookies()->ValidateMap(prerender::PrerenderManager::GetMode());
  }
  if (blocked_by_policy)
    OnContentBlocked(CONTENT_SETTINGS_TYPE_COOKIES, std::string());
  else
    OnContentAccessed(CONTENT_SETTINGS_TYPE_COOKIES);
}

void TabSpecificContentSettings::OnCookieChanged(
    const GURL& url,
    const std::string& cookie_line,
    const net::CookieOptions& options,
    bool blocked_by_policy) {
  if (blocked_by_policy) {
    blocked_local_shared_objects_.cookies()->ValidateMap(
        prerender::PrerenderManager::GetMode());
    blocked_local_shared_objects_.cookies()->SetCookieWithOptions(
        url, cookie_line, options);
    blocked_local_shared_objects_.cookies()->ValidateMap(
        prerender::PrerenderManager::GetMode());
    OnContentBlocked(CONTENT_SETTINGS_TYPE_COOKIES, std::string());
  } else {
    allowed_local_shared_objects_.cookies()->ValidateMap(
        prerender::PrerenderManager::GetMode());
    allowed_local_shared_objects_.cookies()->SetCookieWithOptions(
        url, cookie_line, options);
    allowed_local_shared_objects_.cookies()->ValidateMap(
        prerender::PrerenderManager::GetMode());
    OnContentAccessed(CONTENT_SETTINGS_TYPE_COOKIES);
  }
}

void TabSpecificContentSettings::OnIndexedDBAccessed(
    const GURL& url,
    const string16& description,
    bool blocked_by_policy) {
  if (blocked_by_policy) {
    blocked_local_shared_objects_.indexed_dbs()->AddIndexedDB(
        url, description);
    OnContentBlocked(CONTENT_SETTINGS_TYPE_COOKIES, std::string());
  }else {
    allowed_local_shared_objects_.indexed_dbs()->AddIndexedDB(
        url, description);
    OnContentAccessed(CONTENT_SETTINGS_TYPE_COOKIES);
  }
}

void TabSpecificContentSettings::OnLocalStorageAccessed(
    const GURL& url,
    DOMStorageType storage_type,
    bool blocked_by_policy) {
  LocalSharedObjectsContainer& container = blocked_by_policy ?
      blocked_local_shared_objects_ : allowed_local_shared_objects_;
  CannedBrowsingDataLocalStorageHelper* helper =
      storage_type == DOM_STORAGE_LOCAL ?
          container.local_storages() : container.session_storages();
  helper->AddLocalStorage(url);

  if (blocked_by_policy)
    OnContentBlocked(CONTENT_SETTINGS_TYPE_COOKIES, std::string());
  else
    OnContentAccessed(CONTENT_SETTINGS_TYPE_COOKIES);
}

void TabSpecificContentSettings::OnWebDatabaseAccessed(
    const GURL& url,
    const string16& name,
    const string16& display_name,
    unsigned long estimated_size,
    bool blocked_by_policy) {
  if (blocked_by_policy) {
    blocked_local_shared_objects_.databases()->AddDatabase(
        url, UTF16ToUTF8(name), UTF16ToUTF8(display_name));
    OnContentBlocked(CONTENT_SETTINGS_TYPE_COOKIES, std::string());
  } else {
    allowed_local_shared_objects_.databases()->AddDatabase(
        url, UTF16ToUTF8(name), UTF16ToUTF8(display_name));
    OnContentAccessed(CONTENT_SETTINGS_TYPE_COOKIES);
  }
}

void TabSpecificContentSettings::OnAppCacheAccessed(
    const GURL& manifest_url, bool blocked_by_policy) {
  if (blocked_by_policy) {
    blocked_local_shared_objects_.appcaches()->AddAppCache(manifest_url);
    OnContentBlocked(CONTENT_SETTINGS_TYPE_COOKIES, std::string());
  } else {
    allowed_local_shared_objects_.appcaches()->AddAppCache(manifest_url);
    OnContentAccessed(CONTENT_SETTINGS_TYPE_COOKIES);
  }
}

void TabSpecificContentSettings::OnGeolocationPermissionSet(
    const GURL& requesting_origin,
    bool allowed) {
  geolocation_settings_state_.OnGeolocationPermissionSet(requesting_origin,
                                                         allowed);
  if (delegate_)
    delegate_->OnContentSettingsAccessed(!allowed);
}

TabSpecificContentSettings::TabSpecificContentSettings(
    Delegate* delegate, Profile* profile)
    : allowed_local_shared_objects_(profile),
      blocked_local_shared_objects_(profile),
      geolocation_settings_state_(profile),
      load_plugins_link_enabled_(true),
      delegate_(NULL) {
  ClearBlockedContentSettingsExceptForCookies();
  ClearCookieSpecificContentSettings();
  delegate_ = delegate;
}

void TabSpecificContentSettings::ClearBlockedContentSettingsExceptForCookies() {
  for (size_t i = 0; i < arraysize(content_blocked_); ++i) {
    if (i == CONTENT_SETTINGS_TYPE_COOKIES)
      continue;
    blocked_resources_[i].reset();
    content_blocked_[i] = false;
    content_accessed_[i] = false;
    content_blockage_indicated_to_user_[i] = false;
  }
  load_plugins_link_enabled_ = true;
  if (delegate_)
    delegate_->OnContentSettingsAccessed(false);
}

void TabSpecificContentSettings::ClearCookieSpecificContentSettings() {
  blocked_local_shared_objects_.Reset();
  allowed_local_shared_objects_.Reset();
  content_blocked_[CONTENT_SETTINGS_TYPE_COOKIES] = false;
  content_accessed_[CONTENT_SETTINGS_TYPE_COOKIES] = false;
  content_blockage_indicated_to_user_[CONTENT_SETTINGS_TYPE_COOKIES] = false;
  if (delegate_)
    delegate_->OnContentSettingsAccessed(false);
}

void TabSpecificContentSettings::SetPopupsBlocked(bool blocked) {
  content_blocked_[CONTENT_SETTINGS_TYPE_POPUPS] = blocked;
  content_blockage_indicated_to_user_[CONTENT_SETTINGS_TYPE_POPUPS] = false;
  if (delegate_)
    delegate_->OnContentSettingsAccessed(blocked);
}

void TabSpecificContentSettings::GeolocationDidNavigate(
      const NavigationController::LoadCommittedDetails& details) {
  geolocation_settings_state_.DidNavigate(details);
}

void TabSpecificContentSettings::ClearGeolocationContentSettings() {
  geolocation_settings_state_.ClearStateMap();
}

CookiesTreeModel* TabSpecificContentSettings::GetAllowedCookiesTreeModel() {
  return allowed_local_shared_objects_.GetCookiesTreeModel();
}

CookiesTreeModel* TabSpecificContentSettings::GetBlockedCookiesTreeModel() {
  return blocked_local_shared_objects_.GetCookiesTreeModel();
}

TabSpecificContentSettings::LocalSharedObjectsContainer::
    LocalSharedObjectsContainer(Profile* profile)
    : cookies_(new net::CookieMonster(NULL, NULL)),
      appcaches_(new CannedBrowsingDataAppCacheHelper(profile)),
      databases_(new CannedBrowsingDataDatabaseHelper(profile)),
      indexed_dbs_(new CannedBrowsingDataIndexedDBHelper(profile)),
      local_storages_(new CannedBrowsingDataLocalStorageHelper(profile)),
      session_storages_(new CannedBrowsingDataLocalStorageHelper(profile)) {
}

TabSpecificContentSettings::LocalSharedObjectsContainer::
    ~LocalSharedObjectsContainer() {
  cookies_->ValidateMap(prerender::PrerenderManager::GetMode());
}

void TabSpecificContentSettings::LocalSharedObjectsContainer::Reset() {
  cookies_ = new net::CookieMonster(NULL, NULL);
  appcaches_->Reset();
  databases_->Reset();
  indexed_dbs_->Reset();
  local_storages_->Reset();
  session_storages_->Reset();
}

CookiesTreeModel*
TabSpecificContentSettings::LocalSharedObjectsContainer::GetCookiesTreeModel() {
  return new CookiesTreeModel(cookies_,
                              databases_,
                              local_storages_,
                              session_storages_,
                              appcaches_,
                              indexed_dbs_);
}
<|endoftext|>


<commit_before>#pragma once

#include "net.hpp"
#include "net_raw.hpp"
#include "net_raw_utils.hpp"

#include "net_gpu_impl.hpp"
template <typename activation, typename error>
inline void gpu_train_batch(FeedForward_Network<activation, error>& network,
    arma::Mat<float> inputs, arma::Mat<float> targets, float learning_rate, int batch_size) {

  network.resize_activation(batch_size);
  Raw_FeedForward_Network<activation, error> raw_net = convert_to_raw(network);
  Raw_FeedForward_Network<activation, error> * d_network = network_to_gpu(raw_net);
  int input_size = network.input_size;
  int hidden_size = network.hidden_size;
  int output_size = network.output_size;

  int batches_in_train = targets.n_rows/batch_size - 1;
  //batches_in_train = 1000;
  for (int i = 0; i < batches_in_train; ++i) {
    arma::Mat<float> input_slice = inputs.rows(i*batch_size, (i+1) * batch_size - 1);

    Raw_Matrix raw_input = to_raw(input_slice);
    Raw_Matrix * d_input = matrix_to_gpu(raw_input);
    int num_trials = input_slice.n_rows;

    calculate_activation(num_trials, input_size, hidden_size, output_size, d_network, d_input);
    //TODO make this memory shared as to not realloc
    free_gpu_matrix(d_input);

    arma::Mat<float> targets_slice = targets.rows(i*batch_size, (i+1) * batch_size - 1);

    Raw_Matrix raw_targets = to_raw(targets_slice);
    Raw_Matrix * d_targets = matrix_to_gpu(raw_targets);

    backprop(num_trials, input_size, hidden_size, output_size, d_network, d_targets, learning_rate);
    free_gpu_matrix(d_targets);
  }

  network_to_cpu_free(d_network, raw_net);
  update_from_raw(network, raw_net);

}

template <typename activation, typename error>
inline arma::Mat<float> gpu_predict(FeedForward_Network<activation, error>& network,
    arma::Mat<float> inputs) {
  network.resize_activation(inputs.n_rows);
  Raw_FeedForward_Network<activation, error> raw_net = convert_to_raw(network);
  Raw_FeedForward_Network<activation, error> * d_network = network_to_gpu(raw_net);
  Raw_Matrix raw_inputs = to_raw(inputs);
  Raw_Matrix * d_inputs = matrix_to_gpu(raw_inputs);

  int num_trials = inputs.n_rows;
  int input_size = network.input_size;
  int hidden_size = network.hidden_size;
  int output_size = network.output_size;

  calculate_activation(num_trials, input_size, hidden_size, output_size, d_network, d_inputs);

  network_to_cpu_free(d_network, raw_net);
  update_from_raw(network, raw_net);
  return network.activation_output;
}
<commit_msg>fixed a few more cuda Memory leaks.<commit_after>#pragma once

#include "net.hpp"
#include "net_raw.hpp"
#include "net_raw_utils.hpp"

#include "net_gpu_impl.hpp"
template <typename activation, typename error>
inline void gpu_train_batch(FeedForward_Network<activation, error>& network,
    arma::Mat<float> inputs, arma::Mat<float> targets, float learning_rate, int batch_size) {

  network.resize_activation(batch_size);
  Raw_FeedForward_Network<activation, error> raw_net = convert_to_raw(network);
  Raw_FeedForward_Network<activation, error> * d_network = network_to_gpu(raw_net);
  int input_size = network.input_size;
  int hidden_size = network.hidden_size;
  int output_size = network.output_size;

  int batches_in_train = targets.n_rows/batch_size - 1;
  //batches_in_train = 1000;
  for (int i = 0; i < batches_in_train; ++i) {
    arma::Mat<float> input_slice = inputs.rows(i*batch_size, (i+1) * batch_size - 1);

    Raw_Matrix raw_input = to_raw(input_slice);
    Raw_Matrix * d_input = matrix_to_gpu(raw_input);
    int num_trials = input_slice.n_rows;

    calculate_activation(num_trials, input_size, hidden_size, output_size, d_network, d_input);
    //TODO make this memory shared as to not realloc
    free_gpu_matrix(d_input);

    arma::Mat<float> targets_slice = targets.rows(i*batch_size, (i+1) * batch_size - 1);

    Raw_Matrix raw_targets = to_raw(targets_slice);
    Raw_Matrix * d_targets = matrix_to_gpu(raw_targets);

    backprop(num_trials, input_size, hidden_size, output_size, d_network, d_targets, learning_rate);
    free_gpu_matrix(d_targets);
  }

  network_to_cpu_free(d_network, raw_net);
  update_from_raw(network, raw_net);

}

template <typename activation, typename error>
inline arma::Mat<float> gpu_predict(FeedForward_Network<activation, error>& network,
    arma::Mat<float> inputs) {
  network.resize_activation(inputs.n_rows);
  Raw_FeedForward_Network<activation, error> raw_net = convert_to_raw(network);
  Raw_FeedForward_Network<activation, error> * d_network = network_to_gpu(raw_net);
  Raw_Matrix raw_inputs = to_raw(inputs);
  Raw_Matrix * d_inputs = matrix_to_gpu(raw_inputs);

  int num_trials = inputs.n_rows;
  int input_size = network.input_size;
  int hidden_size = network.hidden_size;
  int output_size = network.output_size;

  calculate_activation(num_trials, input_size, hidden_size, output_size, d_network, d_inputs);
  free_gpu_matrix(d_inputs);

  network_to_cpu_free(d_network, raw_net);
  update_from_raw(network, raw_net);
  return network.activation_output;
}
<|endoftext|>


<commit_before>#include <cstdint>
#include <iostream>
#include <memory>
#include <algorithm>
#include <boost/regex.hpp>

#include <osmium/area/assembler.hpp>
#include <osmium/area/multipolygon_collector.hpp>

#include <osmium/index/map/dummy.hpp>
#include <osmium/index/map/sparse_mem_array.hpp>

#include <osmium/handler/node_locations_for_ways.hpp>

#include <osmium/io/any_input.hpp>
#include <osmium/handler.hpp>
#include <osmium/visitor.hpp>
#include <proj_api.h>
//#include "earcut.hxx"
#include "ObjWriter.hxx"
#include "elevation.hxx"

using namespace std;
using namespace boost;
using namespace osmwave;

typedef osmium::index::map::Map<osmium::unsigned_object_id_type, osmium::Location> index_type;
typedef osmium::handler::NodeLocationsForWays<index_type> location_handler_type;

projPJ wgs84 = pj_init_plus("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs");
const double METERS_PER_LEVEL = 3.0;

class ObjHandler : public osmium::handler::Handler {
    projPJ proj;
    ObjWriter writer;
    vector<double> wayCoords;
    Elevation& elevation;
    double defaultBuildingHeight;

public:
    ObjHandler(projPJ p, ObjWriter writer, Elevation& elevation, double defaultBuildingHeight = 8) :
        proj(p), writer(writer), elevation(elevation), defaultBuildingHeight(defaultBuildingHeight) {}

    void area(osmium::Area& area) {
        const osmium::TagList& tags = area.tags();
        const char* building = tags.get_value_by_key("building");
        const char* highway = tags.get_value_by_key("highway");

        if (!building /*&& !highway*/) {
            return;
        }

        double height = getBuildingHeight(tags, defaultBuildingHeight, "height", "building:levels");
        double baseHeight = getBuildingHeight(tags, 0, "min_height", "building:min_level");

        for (auto oit = area.cbegin<osmium::OuterRing>(); oit != area.cend<osmium::OuterRing>(); ++oit) {
            const osmium::NodeRefList& nodes = *oit;
            int nNodes = nodes.size();

            if (wayCoords.capacity() < nNodes) {
                wayCoords.reserve(nNodes * 2);
            }

            double minElevation = numeric_limits<double>::max();
            for (auto& nr : nodes) {
                double lon = nr.lon();
                double lat = nr.lat();
                wayCoords.push_back(lon * DEG_TO_RAD);
                wayCoords.push_back(lat * DEG_TO_RAD);
                minElevation = min(minElevation, elevation.elevation(lat, lon));
            }

            pj_transform(wgs84, proj, nodes.size(), 2, wayCoords.data(), wayCoords.data() + 1, nullptr);

            ringWalls(wayCoords, minElevation + baseHeight, height - baseHeight);
            flatRoof(nNodes);

            wayCoords.clear();
        }
    }

private:
    void ringWalls(vector<double> wayCoords, double elevation, double height) {
        int nVerts = wayCoords.size() / 2;
        int vertexCount = 0;
        writer.checkpoint();
        for (vector<double>::iterator i = wayCoords.begin(); i != wayCoords.end(); i += 2) {
            writer.vertex(*(i + 1), elevation, *i);
            writer.vertex(*(i + 1), elevation + height, *i);

            if (vertexCount) {
                writer.beginFace();
                writer << (vertexCount - 2) << (vertexCount) << (vertexCount + 1) << (vertexCount - 1);
                writer.endFace();
            }

            vertexCount += 2;
        }
    }

    void flatRoof(int nVerts) {
        writer.beginFace();
        for (int i = 0; i < nVerts; i++) {
            writer << (i * 2 + 1);
        }
        writer.endFace();
    }

    double getBuildingHeight(const osmium::TagList& tags, double defaultHeight, const char* heightTagName, const char* levelTagName) {
        regex heightexpr("^\\s*([0-9\\.]+)\\s*(\\S*)\\s*$");
        const char* heightTag = tags[heightTagName];
        double height = defaultHeight;

        if (heightTag) {
            string heightStr(heightTag);
            auto match_begin =
                sregex_iterator(heightStr.begin(), heightStr.end(), heightexpr);
            auto match_end = sregex_iterator();

            if (match_begin != match_end) {
                smatch match = *match_begin;
                height = stod(match[1]);
            }
        } else {
            const char* levelsTag = tags[levelTagName];
            if (levelsTag) {
                string levelsStr(levelsTag);
                try {
                    double levels = stod(levelsStr);
                    height = levels * METERS_PER_LEVEL;
                } catch (const invalid_argument& ia) {
                    cerr << "Unparseable value for \"building:levels\" tag: \"" << levelsStr << "\"" << endl;
                }
            }
        }

        return height;
    }
};

string* get_proj(osmium::io::Header& header) {
    auto& box = header.boxes()[0];
    float clat = (box.bottom_left().lat() + box.top_right().lat()) / 2;
    float clon = (box.bottom_left().lon() + box.top_right().lon()) / 2;

    ostringstream stream;
    stream << "+proj=tmerc +lat_0=" << clat << " +lon_0=" << clon << " +k=1.000000 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs";
    return new string(stream.str());
}

namespace osmwave {
    void write_obj_header(ObjWriter& objWriter, const string& osmFile, const osmium::Location& sw, const osmium::Location& ne, projPJ proj) {
        ostringstream c;
        c.precision(7);

        objWriter.comment("Created with OSMWAVE");
        objWriter.comment("");

        c << "Input file: " << osmFile;
        objWriter.comment(c.str());
        cerr << c.str() << endl;

        c.str("");
        c << "Lat/lng bounds: (" << sw.lat() << ", " << sw.lon() << ") - (" << ne.lat() << ", " << ne.lon() << ")";
        objWriter.comment(c.str());
        cerr << c.str() << endl;

        c.str("");
        c << "Projection: " << pj_get_def(proj, 0);
        objWriter.comment(c.str());
        cerr << c.str() << endl;

        double coord[2];
        c.str("");
        c << "Projected bounds: (";
        coord[0] = sw.lon() * DEG_TO_RAD;
        coord[1] = sw.lat() * DEG_TO_RAD;
        pj_transform(wgs84, proj, 1, 2, coord, coord + 1, nullptr);
        c << coord[0] << ", " << coord[1];
        c << ") - (";
        coord[0] = ne.lon() * DEG_TO_RAD;
        coord[1] = ne.lat() * DEG_TO_RAD;
        pj_transform(wgs84, proj, 1, 2, coord, coord + 1, nullptr);
        c << coord[0] << ", " << coord[1];
        c << ")";
        objWriter.comment(c.str());
        cerr << c.str() << endl;
    }

    void osm_to_obj(const std::string& osmFile, const std::string& elevationPath, const std::string* projDef) {
        ObjWriter objWriter(cout);

        osmium::io::File infile(osmFile);
        osmium::area::Assembler::config_type assembler_config;
        osmium::area::MultipolygonCollector<osmium::area::Assembler> collector(assembler_config);

        osmium::io::Reader reader1(infile, osmium::osm_entity_bits::relation);
        collector.read_relations(reader1);
        reader1.close();

        osmium::io::Reader reader2(osmFile);
        osmium::io::Header header = reader2.header();
        projPJ proj;

        auto& box = header.boxes()[0];
        auto& sw = box.bottom_left();
        auto& ne = box.top_right();
        float clat = (box.bottom_left().lat() + box.top_right().lat()) / 2;
        float clon = (box.bottom_left().lon() + box.top_right().lon()) / 2;
        if (!projDef) {
            projDef = get_proj(header);
            proj = pj_init_plus(projDef->c_str());
            delete projDef;
        } else {
            proj = pj_init_plus(projDef->c_str());
        }

        write_obj_header(objWriter, osmFile, sw, ne, proj);

        const auto& map_factory = osmium::index::MapFactory<osmium::unsigned_object_id_type, osmium::Location>::instance();
        unique_ptr<index_type> index = map_factory.create_map("sparse_mem_array");
        location_handler_type location_handler(*index);
        location_handler.ignore_errors();

        Elevation elevation((int)floor(sw.lat()), (int)floor(sw.lon()), (int)floor(ne.lat()), (int)floor(ne.lon()), elevationPath);
        ObjHandler handler(proj, objWriter, elevation);
        osmium::apply(reader2, location_handler, collector.handler([&handler](osmium::memory::Buffer&& buffer) {
            osmium::apply(buffer, handler);
        }));
        reader2.close();
    }
}

<commit_msg>Include building:part<commit_after>#include <cstdint>
#include <iostream>
#include <memory>
#include <algorithm>
#include <boost/regex.hpp>

#include <osmium/area/assembler.hpp>
#include <osmium/area/multipolygon_collector.hpp>

#include <osmium/index/map/dummy.hpp>
#include <osmium/index/map/sparse_mem_array.hpp>

#include <osmium/handler/node_locations_for_ways.hpp>

#include <osmium/io/any_input.hpp>
#include <osmium/handler.hpp>
#include <osmium/visitor.hpp>
#include <proj_api.h>
//#include "earcut.hxx"
#include "ObjWriter.hxx"
#include "elevation.hxx"

using namespace std;
using namespace boost;
using namespace osmwave;

typedef osmium::index::map::Map<osmium::unsigned_object_id_type, osmium::Location> index_type;
typedef osmium::handler::NodeLocationsForWays<index_type> location_handler_type;

projPJ wgs84 = pj_init_plus("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs");
const double METERS_PER_LEVEL = 3.0;

class ObjHandler : public osmium::handler::Handler {
    projPJ proj;
    ObjWriter writer;
    vector<double> wayCoords;
    Elevation& elevation;
    double defaultBuildingHeight;

public:
    ObjHandler(projPJ p, ObjWriter writer, Elevation& elevation, double defaultBuildingHeight = 8) :
        proj(p), writer(writer), elevation(elevation), defaultBuildingHeight(defaultBuildingHeight) {}

    void area(osmium::Area& area) {
        const osmium::TagList& tags = area.tags();
        const char* building = tags.get_value_by_key("building");
        const char* buildingPart = tags.get_value_by_key("building:part");
        const char* highway = tags.get_value_by_key("highway");

        if (!building && !buildingPart /*&& !highway*/) {
            return;
        }

        double height = getBuildingHeight(tags, defaultBuildingHeight, "height", "building:levels");
        double baseHeight = getBuildingHeight(tags, 0, "min_height", "building:min_level");

        for (auto oit = area.cbegin<osmium::OuterRing>(); oit != area.cend<osmium::OuterRing>(); ++oit) {
            const osmium::NodeRefList& nodes = *oit;
            int nNodes = nodes.size();

            if (wayCoords.capacity() < nNodes) {
                wayCoords.reserve(nNodes * 2);
            }

            double minElevation = numeric_limits<double>::max();
            for (auto& nr : nodes) {
                double lon = nr.lon();
                double lat = nr.lat();
                wayCoords.push_back(lon * DEG_TO_RAD);
                wayCoords.push_back(lat * DEG_TO_RAD);
                minElevation = min(minElevation, elevation.elevation(lat, lon));
            }

            pj_transform(wgs84, proj, nodes.size(), 2, wayCoords.data(), wayCoords.data() + 1, nullptr);

            ringWalls(wayCoords, minElevation + baseHeight, height - baseHeight);
            flatRoof(nNodes);

            wayCoords.clear();
        }
    }

private:
    void ringWalls(vector<double> wayCoords, double elevation, double height) {
        int nVerts = wayCoords.size() / 2;
        int vertexCount = 0;
        writer.checkpoint();
        for (vector<double>::iterator i = wayCoords.begin(); i != wayCoords.end(); i += 2) {
            writer.vertex(*(i + 1), elevation, *i);
            writer.vertex(*(i + 1), elevation + height, *i);

            if (vertexCount) {
                writer.beginFace();
                writer << (vertexCount - 2) << (vertexCount) << (vertexCount + 1) << (vertexCount - 1);
                writer.endFace();
            }

            vertexCount += 2;
        }
    }

    void flatRoof(int nVerts) {
        writer.beginFace();
        for (int i = 0; i < nVerts; i++) {
            writer << (i * 2 + 1);
        }
        writer.endFace();
    }

    double getBuildingHeight(const osmium::TagList& tags, double defaultHeight, const char* heightTagName, const char* levelTagName) {
        regex heightexpr("^\\s*([0-9\\.]+)\\s*(\\S*)\\s*$");
        const char* heightTag = tags[heightTagName];
        double height = defaultHeight;

        if (heightTag) {
            string heightStr(heightTag);
            auto match_begin =
                sregex_iterator(heightStr.begin(), heightStr.end(), heightexpr);
            auto match_end = sregex_iterator();

            if (match_begin != match_end) {
                smatch match = *match_begin;
                height = stod(match[1]);
            }
        } else {
            const char* levelsTag = tags[levelTagName];
            if (levelsTag) {
                string levelsStr(levelsTag);
                try {
                    double levels = stod(levelsStr);
                    height = levels * METERS_PER_LEVEL;
                } catch (const invalid_argument& ia) {
                    cerr << "Unparseable value for \"building:levels\" tag: \"" << levelsStr << "\"" << endl;
                }
            }
        }

        return height;
    }
};

string* get_proj(osmium::io::Header& header) {
    auto& box = header.boxes()[0];
    float clat = (box.bottom_left().lat() + box.top_right().lat()) / 2;
    float clon = (box.bottom_left().lon() + box.top_right().lon()) / 2;

    ostringstream stream;
    stream << "+proj=tmerc +lat_0=" << clat << " +lon_0=" << clon << " +k=1.000000 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs";
    return new string(stream.str());
}

namespace osmwave {
    void write_obj_header(ObjWriter& objWriter, const string& osmFile, const osmium::Location& sw, const osmium::Location& ne, projPJ proj) {
        ostringstream c;
        c.precision(7);

        objWriter.comment("Created with OSMWAVE");
        objWriter.comment("");

        c << "Input file: " << osmFile;
        objWriter.comment(c.str());
        cerr << c.str() << endl;

        c.str("");
        c << "Lat/lng bounds: (" << sw.lat() << ", " << sw.lon() << ") - (" << ne.lat() << ", " << ne.lon() << ")";
        objWriter.comment(c.str());
        cerr << c.str() << endl;

        c.str("");
        c << "Projection: " << pj_get_def(proj, 0);
        objWriter.comment(c.str());
        cerr << c.str() << endl;

        double coord[2];
        c.str("");
        c << "Projected bounds: (";
        coord[0] = sw.lon() * DEG_TO_RAD;
        coord[1] = sw.lat() * DEG_TO_RAD;
        pj_transform(wgs84, proj, 1, 2, coord, coord + 1, nullptr);
        c << coord[0] << ", " << coord[1];
        c << ") - (";
        coord[0] = ne.lon() * DEG_TO_RAD;
        coord[1] = ne.lat() * DEG_TO_RAD;
        pj_transform(wgs84, proj, 1, 2, coord, coord + 1, nullptr);
        c << coord[0] << ", " << coord[1];
        c << ")";
        objWriter.comment(c.str());
        cerr << c.str() << endl;
    }

    void osm_to_obj(const std::string& osmFile, const std::string& elevationPath, const std::string* projDef) {
        ObjWriter objWriter(cout);

        osmium::io::File infile(osmFile);
        osmium::area::Assembler::config_type assembler_config;
        osmium::area::MultipolygonCollector<osmium::area::Assembler> collector(assembler_config);

        osmium::io::Reader reader1(infile, osmium::osm_entity_bits::relation);
        collector.read_relations(reader1);
        reader1.close();

        osmium::io::Reader reader2(osmFile);
        osmium::io::Header header = reader2.header();
        projPJ proj;

        auto& box = header.boxes()[0];
        auto& sw = box.bottom_left();
        auto& ne = box.top_right();
        float clat = (box.bottom_left().lat() + box.top_right().lat()) / 2;
        float clon = (box.bottom_left().lon() + box.top_right().lon()) / 2;
        if (!projDef) {
            projDef = get_proj(header);
            proj = pj_init_plus(projDef->c_str());
            delete projDef;
        } else {
            proj = pj_init_plus(projDef->c_str());
        }

        write_obj_header(objWriter, osmFile, sw, ne, proj);

        const auto& map_factory = osmium::index::MapFactory<osmium::unsigned_object_id_type, osmium::Location>::instance();
        unique_ptr<index_type> index = map_factory.create_map("sparse_mem_array");
        location_handler_type location_handler(*index);
        location_handler.ignore_errors();

        Elevation elevation((int)floor(sw.lat()), (int)floor(sw.lon()), (int)floor(ne.lat()), (int)floor(ne.lon()), elevationPath);
        ObjHandler handler(proj, objWriter, elevation);
        osmium::apply(reader2, location_handler, collector.handler([&handler](osmium::memory::Buffer&& buffer) {
            osmium::apply(buffer, handler);
        }));
        reader2.close();
    }
}

<|endoftext|>


<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include <mitkBaseDataIOFactory.h>
#include <mitkBaseData.h>
#include <mitkImageCast.h>
#include <mitkImageToItk.h>
#include <itkEvaluateDirectionImagesFilter.h>
#include <itkTractsToVectorImageFilter.h>
#include <usAny.h>
#include <itkImageFileWriter.h>
#include <mitkIOUtil.h>
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <fstream>
#include <itksys/SystemTools.hxx>
#include <mitkTestingMacros.h>
#include <mitkCompareImageDataFilter.h>
#include <mitkFiberBundleXWriter.h>

#define _USE_MATH_DEFINES
#include <math.h>

using namespace std;

int mitkLocalFiberPlausibilityTest(int argc, char* argv[])
{
    MITK_TEST_BEGIN("mitkLocalFiberPlausibilityTest");
    MITK_TEST_CONDITION_REQUIRED(argc==8,"check for input data")

            string fibFile = argv[1];
    vector< string > referenceImages;
    referenceImages.push_back(argv[2]);
    referenceImages.push_back(argv[3]);
    string LDFP_ERROR_IMAGE = argv[4];
    string LDFP_NUM_DIRECTIONS = argv[5];
    string LDFP_VECTOR_FIELD = argv[6];
    string LDFP_ERROR_IMAGE_IGNORE = argv[7];

    float angularThreshold = 25;

    try
    {
        typedef itk::Image<unsigned char, 3>                                    ItkUcharImgType;
        typedef itk::Image< itk::Vector< float, 3>, 3 >                         ItkDirectionImage3DType;
        typedef itk::VectorContainer< unsigned int, ItkDirectionImage3DType::Pointer >   ItkDirectionImageContainerType;
        typedef itk::EvaluateDirectionImagesFilter< float >                     EvaluationFilterType;

        // load fiber bundle
        mitk::FiberBundleX::Pointer inputTractogram = dynamic_cast<mitk::FiberBundleX*>(mitk::IOUtil::LoadDataNode(fibFile)->GetData());

        // load reference directions
        ItkDirectionImageContainerType::Pointer referenceImageContainer = ItkDirectionImageContainerType::New();
        for (unsigned int i=0; i<referenceImages.size(); i++)
        {
            try
            {
                mitk::Image::Pointer img = dynamic_cast<mitk::Image*>(mitk::IOUtil::LoadDataNode(referenceImages.at(i))->GetData());
                typedef mitk::ImageToItk< ItkDirectionImage3DType > CasterType;
                CasterType::Pointer caster = CasterType::New();
                caster->SetInput(img);
                caster->Update();
                ItkDirectionImage3DType::Pointer itkImg = caster->GetOutput();
                referenceImageContainer->InsertElement(referenceImageContainer->Size(),itkImg);
            }
            catch(...){ MITK_INFO << "could not load: " << referenceImages.at(i); }
        }

        ItkUcharImgType::Pointer itkMaskImage = ItkUcharImgType::New();
        ItkDirectionImage3DType::Pointer dirImg = referenceImageContainer->GetElement(0);
        itkMaskImage->SetSpacing( dirImg->GetSpacing() );
        itkMaskImage->SetOrigin( dirImg->GetOrigin() );
        itkMaskImage->SetDirection( dirImg->GetDirection() );
        itkMaskImage->SetLargestPossibleRegion( dirImg->GetLargestPossibleRegion() );
        itkMaskImage->SetBufferedRegion( dirImg->GetLargestPossibleRegion() );
        itkMaskImage->SetRequestedRegion( dirImg->GetLargestPossibleRegion() );
        itkMaskImage->Allocate();
        itkMaskImage->FillBuffer(1);

        // extract directions from fiber bundle
        itk::TractsToVectorImageFilter<float>::Pointer fOdfFilter = itk::TractsToVectorImageFilter<float>::New();
        fOdfFilter->SetFiberBundle(inputTractogram);
        fOdfFilter->SetMaskImage(itkMaskImage);
        fOdfFilter->SetAngularThreshold(cos(angularThreshold*M_PI/180));
        fOdfFilter->SetNormalizeVectors(true);
        fOdfFilter->SetUseWorkingCopy(false);
        fOdfFilter->SetNumberOfThreads(1);
        fOdfFilter->Update();
        ItkDirectionImageContainerType::Pointer directionImageContainer = fOdfFilter->GetDirectionImageContainer();

        // Get directions and num directions image
        ItkUcharImgType::Pointer numDirImage = fOdfFilter->GetNumDirectionsImage();
        mitk::Image::Pointer mitkNumDirImage = mitk::Image::New();
        mitkNumDirImage->InitializeByItk( numDirImage.GetPointer() );
        mitkNumDirImage->SetVolume( numDirImage->GetBufferPointer() );
        mitk::FiberBundleX::Pointer testDirections = fOdfFilter->GetOutputFiberBundle();

        // evaluate directions with missing directions
        EvaluationFilterType::Pointer evaluationFilter = EvaluationFilterType::New();
        evaluationFilter->SetImageSet(directionImageContainer);
        evaluationFilter->SetReferenceImageSet(referenceImageContainer);
        evaluationFilter->SetMaskImage(itkMaskImage);
        evaluationFilter->SetIgnoreMissingDirections(false);
        evaluationFilter->Update();

        EvaluationFilterType::OutputImageType::Pointer angularErrorImage = evaluationFilter->GetOutput(0);
        mitk::Image::Pointer mitkAngularErrorImage = mitk::Image::New();
        mitkAngularErrorImage->InitializeByItk( angularErrorImage.GetPointer() );
        mitkAngularErrorImage->SetVolume( angularErrorImage->GetBufferPointer() );

        // evaluate directions without missing directions
        evaluationFilter->SetIgnoreMissingDirections(true);
        evaluationFilter->Update();

        EvaluationFilterType::OutputImageType::Pointer angularErrorImageIgnore = evaluationFilter->GetOutput(0);
        mitk::Image::Pointer mitkAngularErrorImageIgnore = mitk::Image::New();
        mitkAngularErrorImageIgnore->InitializeByItk( angularErrorImageIgnore.GetPointer() );
        mitkAngularErrorImageIgnore->SetVolume( angularErrorImageIgnore->GetBufferPointer() );

        mitk::Image::Pointer gtAngularErrorImageIgnore = dynamic_cast<mitk::Image*>(mitk::IOUtil::LoadDataNode(LDFP_ERROR_IMAGE_IGNORE)->GetData());
        mitk::Image::Pointer gtAngularErrorImage = dynamic_cast<mitk::Image*>(mitk::IOUtil::LoadDataNode(LDFP_ERROR_IMAGE)->GetData());
        mitk::Image::Pointer gtNumTestDirImage = dynamic_cast<mitk::Image*>(mitk::IOUtil::LoadDataNode(LDFP_NUM_DIRECTIONS)->GetData());
        mitk::FiberBundleX::Pointer gtTestDirections = dynamic_cast<mitk::FiberBundleX*>(mitk::IOUtil::LoadDataNode(LDFP_VECTOR_FIELD)->GetData());

        if (!testDirections->Equals(gtTestDirections))
        {
            MITK_INFO << "SAVING FILES TO " << mitk::IOUtil::GetTempPath();
            std::string out1 = mitk::IOUtil::GetTempPath().append("test.fib");
            std::string out2 = mitk::IOUtil::GetTempPath().append("reference.fib");

            mitk::FiberBundleXWriter::Pointer fibWriter = mitk::FiberBundleXWriter::New();
            fibWriter->SetFileName(out1.c_str());
            fibWriter->DoWrite(testDirections.GetPointer());

            fibWriter->SetFileName(out2.c_str());
            fibWriter->DoWrite(gtTestDirections.GetPointer());
        }

        MITK_TEST_CONDITION_REQUIRED(mitk::Equal(gtAngularErrorImageIgnore, mitkAngularErrorImageIgnore, 0.0001, true), "Check if error images are equal (ignored missing directions).");
        MITK_TEST_CONDITION_REQUIRED(mitk::Equal(gtAngularErrorImage, mitkAngularErrorImage, 0.0001, true), "Check if error images are equal.");
        MITK_TEST_CONDITION_REQUIRED(testDirections->Equals(gtTestDirections), "Check if vector fields are equal.");
        MITK_TEST_CONDITION_REQUIRED(mitk::Equal(gtNumTestDirImage, mitkNumDirImage, 0.0001, true), "Check if num direction images are equal.");
    }
    catch (itk::ExceptionObject e)
    {
        MITK_INFO << e;
        return EXIT_FAILURE;
    }
    catch (std::exception e)
    {
        MITK_INFO << e.what();
        return EXIT_FAILURE;
    }
    catch (...)
    {
        MITK_INFO << "ERROR!?!";
        return EXIT_FAILURE;
    }
    MITK_TEST_END();
}
<commit_msg>increased tolerance for 32 bit machines<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include <mitkBaseDataIOFactory.h>
#include <mitkBaseData.h>
#include <mitkImageCast.h>
#include <mitkImageToItk.h>
#include <itkEvaluateDirectionImagesFilter.h>
#include <itkTractsToVectorImageFilter.h>
#include <usAny.h>
#include <itkImageFileWriter.h>
#include <mitkIOUtil.h>
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <fstream>
#include <itksys/SystemTools.hxx>
#include <mitkTestingMacros.h>
#include <mitkCompareImageDataFilter.h>
#include <mitkFiberBundleXWriter.h>

#define _USE_MATH_DEFINES
#include <math.h>

using namespace std;

int mitkLocalFiberPlausibilityTest(int argc, char* argv[])
{
    MITK_TEST_BEGIN("mitkLocalFiberPlausibilityTest");
    MITK_TEST_CONDITION_REQUIRED(argc==8,"check for input data")

            string fibFile = argv[1];
    vector< string > referenceImages;
    referenceImages.push_back(argv[2]);
    referenceImages.push_back(argv[3]);
    string LDFP_ERROR_IMAGE = argv[4];
    string LDFP_NUM_DIRECTIONS = argv[5];
    string LDFP_VECTOR_FIELD = argv[6];
    string LDFP_ERROR_IMAGE_IGNORE = argv[7];

    float angularThreshold = 25;

    try
    {
        typedef itk::Image<unsigned char, 3>                                    ItkUcharImgType;
        typedef itk::Image< itk::Vector< float, 3>, 3 >                         ItkDirectionImage3DType;
        typedef itk::VectorContainer< unsigned int, ItkDirectionImage3DType::Pointer >   ItkDirectionImageContainerType;
        typedef itk::EvaluateDirectionImagesFilter< float >                     EvaluationFilterType;

        // load fiber bundle
        mitk::FiberBundleX::Pointer inputTractogram = dynamic_cast<mitk::FiberBundleX*>(mitk::IOUtil::LoadDataNode(fibFile)->GetData());

        // load reference directions
        ItkDirectionImageContainerType::Pointer referenceImageContainer = ItkDirectionImageContainerType::New();
        for (unsigned int i=0; i<referenceImages.size(); i++)
        {
            try
            {
                mitk::Image::Pointer img = dynamic_cast<mitk::Image*>(mitk::IOUtil::LoadDataNode(referenceImages.at(i))->GetData());
                typedef mitk::ImageToItk< ItkDirectionImage3DType > CasterType;
                CasterType::Pointer caster = CasterType::New();
                caster->SetInput(img);
                caster->Update();
                ItkDirectionImage3DType::Pointer itkImg = caster->GetOutput();
                referenceImageContainer->InsertElement(referenceImageContainer->Size(),itkImg);
            }
            catch(...){ MITK_INFO << "could not load: " << referenceImages.at(i); }
        }

        ItkUcharImgType::Pointer itkMaskImage = ItkUcharImgType::New();
        ItkDirectionImage3DType::Pointer dirImg = referenceImageContainer->GetElement(0);
        itkMaskImage->SetSpacing( dirImg->GetSpacing() );
        itkMaskImage->SetOrigin( dirImg->GetOrigin() );
        itkMaskImage->SetDirection( dirImg->GetDirection() );
        itkMaskImage->SetLargestPossibleRegion( dirImg->GetLargestPossibleRegion() );
        itkMaskImage->SetBufferedRegion( dirImg->GetLargestPossibleRegion() );
        itkMaskImage->SetRequestedRegion( dirImg->GetLargestPossibleRegion() );
        itkMaskImage->Allocate();
        itkMaskImage->FillBuffer(1);

        // extract directions from fiber bundle
        itk::TractsToVectorImageFilter<float>::Pointer fOdfFilter = itk::TractsToVectorImageFilter<float>::New();
        fOdfFilter->SetFiberBundle(inputTractogram);
        fOdfFilter->SetMaskImage(itkMaskImage);
        fOdfFilter->SetAngularThreshold(cos(angularThreshold*M_PI/180));
        fOdfFilter->SetNormalizeVectors(true);
        fOdfFilter->SetUseWorkingCopy(false);
        fOdfFilter->SetNumberOfThreads(1);
        fOdfFilter->Update();
        ItkDirectionImageContainerType::Pointer directionImageContainer = fOdfFilter->GetDirectionImageContainer();

        // Get directions and num directions image
        ItkUcharImgType::Pointer numDirImage = fOdfFilter->GetNumDirectionsImage();
        mitk::Image::Pointer mitkNumDirImage = mitk::Image::New();
        mitkNumDirImage->InitializeByItk( numDirImage.GetPointer() );
        mitkNumDirImage->SetVolume( numDirImage->GetBufferPointer() );
        mitk::FiberBundleX::Pointer testDirections = fOdfFilter->GetOutputFiberBundle();

        // evaluate directions with missing directions
        EvaluationFilterType::Pointer evaluationFilter = EvaluationFilterType::New();
        evaluationFilter->SetImageSet(directionImageContainer);
        evaluationFilter->SetReferenceImageSet(referenceImageContainer);
        evaluationFilter->SetMaskImage(itkMaskImage);
        evaluationFilter->SetIgnoreMissingDirections(false);
        evaluationFilter->Update();

        EvaluationFilterType::OutputImageType::Pointer angularErrorImage = evaluationFilter->GetOutput(0);
        mitk::Image::Pointer mitkAngularErrorImage = mitk::Image::New();
        mitkAngularErrorImage->InitializeByItk( angularErrorImage.GetPointer() );
        mitkAngularErrorImage->SetVolume( angularErrorImage->GetBufferPointer() );

        // evaluate directions without missing directions
        evaluationFilter->SetIgnoreMissingDirections(true);
        evaluationFilter->Update();

        EvaluationFilterType::OutputImageType::Pointer angularErrorImageIgnore = evaluationFilter->GetOutput(0);
        mitk::Image::Pointer mitkAngularErrorImageIgnore = mitk::Image::New();
        mitkAngularErrorImageIgnore->InitializeByItk( angularErrorImageIgnore.GetPointer() );
        mitkAngularErrorImageIgnore->SetVolume( angularErrorImageIgnore->GetBufferPointer() );

        mitk::Image::Pointer gtAngularErrorImageIgnore = dynamic_cast<mitk::Image*>(mitk::IOUtil::LoadDataNode(LDFP_ERROR_IMAGE_IGNORE)->GetData());
        mitk::Image::Pointer gtAngularErrorImage = dynamic_cast<mitk::Image*>(mitk::IOUtil::LoadDataNode(LDFP_ERROR_IMAGE)->GetData());
        mitk::Image::Pointer gtNumTestDirImage = dynamic_cast<mitk::Image*>(mitk::IOUtil::LoadDataNode(LDFP_NUM_DIRECTIONS)->GetData());
        mitk::FiberBundleX::Pointer gtTestDirections = dynamic_cast<mitk::FiberBundleX*>(mitk::IOUtil::LoadDataNode(LDFP_VECTOR_FIELD)->GetData());

        if (!testDirections->Equals(gtTestDirections))
        {
            MITK_INFO << "SAVING FILES TO " << mitk::IOUtil::GetTempPath();
            std::string out1 = mitk::IOUtil::GetTempPath().append("test.fib");
            std::string out2 = mitk::IOUtil::GetTempPath().append("reference.fib");

            mitk::FiberBundleXWriter::Pointer fibWriter = mitk::FiberBundleXWriter::New();
            fibWriter->SetFileName(out1.c_str());
            fibWriter->DoWrite(testDirections.GetPointer());

            fibWriter->SetFileName(out2.c_str());
            fibWriter->DoWrite(gtTestDirections.GetPointer());
        }

        MITK_TEST_CONDITION_REQUIRED(mitk::Equal(gtAngularErrorImageIgnore, mitkAngularErrorImageIgnore, 0.01, true), "Check if error images are equal (ignored missing directions).");
        MITK_TEST_CONDITION_REQUIRED(mitk::Equal(gtAngularErrorImage, mitkAngularErrorImage, 0.01, true), "Check if error images are equal.");
        MITK_TEST_CONDITION_REQUIRED(testDirections->Equals(gtTestDirections), "Check if vector fields are equal.");
        MITK_TEST_CONDITION_REQUIRED(mitk::Equal(gtNumTestDirImage, mitkNumDirImage, 0.0001, true), "Check if num direction images are equal.");
    }
    catch (itk::ExceptionObject e)
    {
        MITK_INFO << e;
        return EXIT_FAILURE;
    }
    catch (std::exception e)
    {
        MITK_INFO << e.what();
        return EXIT_FAILURE;
    }
    catch (...)
    {
        MITK_INFO << "ERROR!?!";
        return EXIT_FAILURE;
    }
    MITK_TEST_END();
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef otbLabelImageSmallRegionMergingFilter_hxx
#define otbLabelImageSmallRegionMergingFilter_hxx

#include "otbLabelImageSmallRegionMergingFilter.h"
#include "itkImageConstIterator.h"
#include "itkConstShapedNeighborhoodIterator.h"
#include "itkProgressReporter.h"

#include <time.h>
namespace otb
{
template <class TInputLabelImage >
PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage >
::PersistentLabelImageSmallRegionMergingFilter() : m_Size(1)
{
}

template <class TInputLabelImage >
void
PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage >
::Reset()
{
  m_NeighboursMapsTmp.clear();
  m_NeighboursMapsTmp.resize( this->GetNumberOfThreads() );
}

template <class TInputLabelImage >
void
PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage >
::Synthetize()
{
  NeigboursMapType neighboursMap;
  // Merge the neighbours maps from all threads
  for( unsigned int threadId = 0; threadId < this->GetNumberOfThreads(); threadId++)
    {
    for (auto it = m_NeighboursMapsTmp[threadId].begin(); it != m_NeighboursMapsTmp[threadId].end(); it++)
      {
      neighboursMap[ it->first ].insert( it->second.begin(), it->second.end() );
      }
    }

  // For each label of the label map, find the "closest" connected label, according
  // to the euclidian distance between the corresponding m_labelStatistic elements.
  for (auto neighbours : neighboursMap)
    {
    double proximity = std::numeric_limits<double>::max();
    InputLabelType label = neighbours.first;
    InputLabelType closestNeighbour = label;
    for (auto neighbour : neighbours.second)
      {
      auto statsLabel = m_LabelStatistic[ label ];
      auto statsNeighbour = m_LabelStatistic[ neighbour ];
      assert( statsLabel.Size() == statsNeighbour.Size() );
      double distance = 0;
      for (unsigned int i = 0 ; i < statsLabel.Size(); i++)
        {
        distance += pow( statsLabel[i] - statsNeighbour[i] , 2);
        }
      if (distance < proximity)
        {
        proximity = distance;
        closestNeighbour = neighbour;
        }
      }

    auto curLabelLUT = FindCorrespondingLabel(label);
    auto adjLabelLUT = FindCorrespondingLabel(closestNeighbour);

    if(curLabelLUT < adjLabelLUT)
      {
      m_LUT[adjLabelLUT] = curLabelLUT;
      }
    else
      {
      m_LUT[m_LUT[curLabelLUT]] = adjLabelLUT;
      m_LUT[curLabelLUT] = adjLabelLUT;
      }
    }

  // Update the LUT
  for(InputLabelType label = 0; label < m_LUT.size(); ++label)
    {
    InputLabelType can = label;
    while(m_LUT[can] != can)
      {
      can = m_LUT[can];
      }
    m_LUT[label] = can;
    }

  // Update Statistics
  for(InputLabelType label = 0; label < m_LUT.size(); ++label)
    {
    InputLabelType correspondingLabel = m_LUT[label];

    if((m_LabelPopulation[label]!=0) && (correspondingLabel != label))
      {
      m_LabelStatistic[ correspondingLabel ] = (m_LabelStatistic[correspondingLabel]*m_LabelPopulation[correspondingLabel] +
                        m_LabelStatistic[label]*m_LabelPopulation[label] ) / (m_LabelPopulation[label]+m_LabelPopulation[correspondingLabel]);
      m_LabelPopulation[ correspondingLabel ] += m_LabelPopulation[ label ] ;
      m_LabelPopulation[ label ] = 0;
      }
    }
}

template <class TInputLabelImage >
typename PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage >::InputLabelType
PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage >
::FindCorrespondingLabel( typename PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage >
                            ::InputLabelType label)
{
  auto correspondingLabel = m_LUT[label];
  while (label != correspondingLabel)
    {
    label = correspondingLabel;
    correspondingLabel = m_LUT[correspondingLabel];
    }
  return correspondingLabel;
}

template <class TInputLabelImage >
void
PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage >
::GenerateInputRequestedRegion()
{
  // call the superclass' implementation of this method
  Superclass::GenerateInputRequestedRegion();

  // get pointers to the input
  auto inputPtr = const_cast<TInputLabelImage *>(this->GetInput());

  // get a copy of the input requested region
  auto inputRequestedRegion = inputPtr->GetRequestedRegion();

  // pad the input requested region by the operator radius
  inputRequestedRegion.PadByRadius(1);
  // crop the input requested region at the input's largest possible region
  if (inputRequestedRegion.Crop(inputPtr->GetLargestPossibleRegion()))
    {
    inputPtr->SetRequestedRegion(inputRequestedRegion);
    return;
    }
  else
    {
    // Couldn't crop the region (requested region is outside the largest
    // possible region).  Throw an exception.

    // store what we tried to request (prior to trying to crop)
    inputPtr->SetRequestedRegion(inputRequestedRegion);

    // build an exception
    itk::InvalidRequestedRegionError e(__FILE__, __LINE__);
    e.SetLocation(ITK_LOCATION);
    e.SetDescription("Requested region is (at least partially) outside the largest possible region.");
    e.SetDataObject(inputPtr);
    throw e;
    }

}

template <class TInputLabelImage >
void
PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage >
::ThreadedGenerateData(const RegionType& outputRegionForThread, itk::ThreadIdType threadId )
{
  using IteratorType = itk::ImageRegionConstIterator< TInputLabelImage >;
  using NeighborhoodIteratorType = itk::ConstShapedNeighborhoodIterator< TInputLabelImage >;

  typename NeighborhoodIteratorType::RadiusType radius;
  radius.Fill(1);

  auto labelImage = this->GetInput();

  IteratorType it(labelImage, outputRegionForThread);
  NeighborhoodIteratorType itN(radius, labelImage, outputRegionForThread);

  // 4 connected Neighborhood (top, bottom, left and right)
  typename IteratorType::OffsetType top = {{0,-1}};
  itN.ActivateOffset(top);
  typename IteratorType::OffsetType bottom = {{0,1}};
  itN.ActivateOffset(bottom);
  typename IteratorType::OffsetType right = {{1,0}};
  itN.ActivateOffset(right);
  typename IteratorType::OffsetType left = {{-1,0}};
  itN.ActivateOffset(left);

  for (it.GoToBegin(); ! it.IsAtEnd(); ++it, ++itN)
    {
    assert( !itN.IsAtEnd() );
    int currentLabel = FindCorrespondingLabel(it.Get());

    if ( m_LabelPopulation[currentLabel] == m_Size )
      {
      for (auto ci = itN.Begin() ; !ci.IsAtEnd(); ci++)
        {
        int neighbourLabel = FindCorrespondingLabel(ci.Get() );
        if (neighbourLabel != currentLabel)
          m_NeighboursMapsTmp[threadId][ currentLabel ].insert( neighbourLabel );
        }
      }
    }
}

template <class TInputLabelImage >
void
PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage >
::PrintSelf(std::ostream& os, itk::Indent indent) const
{
  Superclass::PrintSelf(os, indent);
}

template <class TInputLabelImage >
LabelImageSmallRegionMergingFilter< TInputLabelImage >
::LabelImageSmallRegionMergingFilter() : m_MinSize(1)
{
  m_SmallRegionMergingFilter = LabelImageSmallRegionMergingFilterType::New();
}

template <class TInputLabelImage >
void
LabelImageSmallRegionMergingFilter< TInputLabelImage >
::GenerateData()
{
  this->SetProgress(0.0);
  auto labelImage = this->GetInput();
  m_SmallRegionMergingFilter->GetFilter()->SetInput( labelImage );

  // Update the filter for all sizes.
  for (unsigned int size = 1; size < m_MinSize; size++)
    {
    m_SmallRegionMergingFilter->GetFilter()->SetSize( size) ;
    m_SmallRegionMergingFilter->Update();
    this->UpdateProgress(static_cast<double>(size+1)/m_MinSize);
    }
}

} // end namespace otb

#endif
<commit_msg>ENH : Code review 1<commit_after>/*
 * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef otbLabelImageSmallRegionMergingFilter_hxx
#define otbLabelImageSmallRegionMergingFilter_hxx

#include "otbLabelImageSmallRegionMergingFilter.h"
#include "itkImageConstIterator.h"
#include "itkConstShapedNeighborhoodIterator.h"
#include "itkProgressReporter.h"

#include <time.h>
namespace otb
{
template <class TInputLabelImage >
PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage >
::PersistentLabelImageSmallRegionMergingFilter() : m_Size(1)
{
}

template <class TInputLabelImage >
void
PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage >
::Reset()
{
  m_NeighboursMapsTmp.clear();
  m_NeighboursMapsTmp.resize( this->GetNumberOfThreads() );
}

template <class TInputLabelImage >
void
PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage >
::Synthetize()
{
  NeigboursMapType neighboursMap;
  // Merge the neighbours maps from all threads
  for( unsigned int threadId = 0; threadId < this->GetNumberOfThreads(); threadId++)
    {
    for (auto it = m_NeighboursMapsTmp[threadId].begin(); it != m_NeighboursMapsTmp[threadId].end(); it++)
      {
      neighboursMap[ it->first ].insert( it->second.begin(), it->second.end() );
      }
    }

  // For each label of the label map, find the "closest" connected label, according
  // to the euclidian distance between the corresponding m_labelStatistic elements.
  for (auto const & neighbours : neighboursMap)
    {
    double proximity = std::numeric_limits<double>::max();
    InputLabelType label = neighbours.first;
    InputLabelType closestNeighbour = label;
    for (auto const & neighbour : neighbours.second)
      {
      auto statsLabel = m_LabelStatistic[ label ];
      auto statsNeighbour = m_LabelStatistic[ neighbour ];
      assert( statsLabel.Size() == statsNeighbour.Size() );
      double distance = 0;
      for (unsigned int i = 0 ; i < statsLabel.Size(); i++)
        {
        distance += (statsLabel[i] - statsNeighbour[i]) * (statsLabel[i] - statsNeighbour[i]);
        }
      if (distance < proximity)
        {
        proximity = distance;
        closestNeighbour = neighbour;
        }
      }

    auto curLabelLUT = FindCorrespondingLabel(label);
    auto adjLabelLUT = FindCorrespondingLabel(closestNeighbour);

    if(curLabelLUT < adjLabelLUT)
      {
      m_LUT[adjLabelLUT] = curLabelLUT;
      }
    else
      {
      m_LUT[m_LUT[curLabelLUT]] = adjLabelLUT;
      m_LUT[curLabelLUT] = adjLabelLUT;
      }
    }

  // Update the LUT
  for(InputLabelType label = 0; label < m_LUT.size(); ++label)
    {
    InputLabelType can = label;
    while(m_LUT[can] != can)
      {
      can = m_LUT[can];
      }
    m_LUT[label] = can;
    }

  // Update Statistics
  for(InputLabelType label = 0; label < m_LUT.size(); ++label)
    {
    InputLabelType correspondingLabel = m_LUT[label];

    if((m_LabelPopulation[label]!=0) && (correspondingLabel != label))
      {
      m_LabelStatistic[ correspondingLabel ] = (m_LabelStatistic[correspondingLabel]*m_LabelPopulation[correspondingLabel] +
                        m_LabelStatistic[label]*m_LabelPopulation[label] ) / (m_LabelPopulation[label]+m_LabelPopulation[correspondingLabel]);
      m_LabelPopulation[ correspondingLabel ] += m_LabelPopulation[ label ] ;
      m_LabelPopulation[ label ] = 0;
      }
    }
}

template <class TInputLabelImage >
typename PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage >::InputLabelType
PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage >
::FindCorrespondingLabel( typename PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage >
                            ::InputLabelType label)
{
  auto correspondingLabel = m_LUT[label];
  while (label != correspondingLabel)
    {
    label = correspondingLabel;
    correspondingLabel = m_LUT[correspondingLabel];
    }
  return correspondingLabel;
}

template <class TInputLabelImage >
void
PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage >
::GenerateInputRequestedRegion()
{
  // call the superclass' implementation of this method
  Superclass::GenerateInputRequestedRegion();

  // get pointers to the input
  auto inputPtr = const_cast<TInputLabelImage *>(this->GetInput());

  // get a copy of the input requested region
  auto inputRequestedRegion = inputPtr->GetRequestedRegion();

  // pad the input requested region by the operator radius
  inputRequestedRegion.PadByRadius(1);
  // crop the input requested region at the input's largest possible region
  if (inputRequestedRegion.Crop(inputPtr->GetLargestPossibleRegion()))
    {
    inputPtr->SetRequestedRegion(inputRequestedRegion);
    return;
    }
  else
    {
    // Couldn't crop the region (requested region is outside the largest
    // possible region).  Throw an exception.

    // store what we tried to request (prior to trying to crop)
    inputPtr->SetRequestedRegion(inputRequestedRegion);

    // build an exception
    itk::InvalidRequestedRegionError e(__FILE__, __LINE__);
    e.SetLocation(ITK_LOCATION);
    e.SetDescription("Requested region is (at least partially) outside the largest possible region.");
    e.SetDataObject(inputPtr);
    throw e;
    }

}

template <class TInputLabelImage >
void
PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage >
::ThreadedGenerateData(const RegionType& outputRegionForThread, itk::ThreadIdType threadId )
{
  using IteratorType = itk::ImageRegionConstIterator< TInputLabelImage >;
  using NeighborhoodIteratorType = itk::ConstShapedNeighborhoodIterator< TInputLabelImage >;

  typename NeighborhoodIteratorType::RadiusType radius;
  radius.Fill(1);

  auto labelImage = this->GetInput();

  IteratorType it(labelImage, outputRegionForThread);
  NeighborhoodIteratorType itN(radius, labelImage, outputRegionForThread);

  // 4 connected Neighborhood (top, bottom, left and right)
  typename IteratorType::OffsetType top = {{0,-1}};
  itN.ActivateOffset(top);
  typename IteratorType::OffsetType bottom = {{0,1}};
  itN.ActivateOffset(bottom);
  typename IteratorType::OffsetType right = {{1,0}};
  itN.ActivateOffset(right);
  typename IteratorType::OffsetType left = {{-1,0}};
  itN.ActivateOffset(left);

  for (it.GoToBegin(); ! it.IsAtEnd(); ++it, ++itN)
    {
    assert( !itN.IsAtEnd() );
    int currentLabel = FindCorrespondingLabel(it.Get());

    if ( m_LabelPopulation[currentLabel] == m_Size )
      {
      for (auto ci = itN.Begin() ; !ci.IsAtEnd(); ci++)
        {
        int neighbourLabel = FindCorrespondingLabel(ci.Get() );
        if (neighbourLabel != currentLabel)
          m_NeighboursMapsTmp[threadId][ currentLabel ].insert( neighbourLabel );
        }
      }
    }
}

template <class TInputLabelImage >
void
PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage >
::PrintSelf(std::ostream& os, itk::Indent indent) const
{
  Superclass::PrintSelf(os, indent);
}

template <class TInputLabelImage >
LabelImageSmallRegionMergingFilter< TInputLabelImage >
::LabelImageSmallRegionMergingFilter() : m_MinSize(1)
{
  m_SmallRegionMergingFilter = LabelImageSmallRegionMergingFilterType::New();
}

template <class TInputLabelImage >
void
LabelImageSmallRegionMergingFilter< TInputLabelImage >
::GenerateData()
{
  this->SetProgress(0.0);
  auto labelImage = this->GetInput();
  m_SmallRegionMergingFilter->GetFilter()->SetInput( labelImage );

  // Update the filter for all sizes.
  for (unsigned int size = 1; size < m_MinSize; size++)
    {
    m_SmallRegionMergingFilter->GetFilter()->SetSize( size) ;
    m_SmallRegionMergingFilter->Update();
    this->UpdateProgress(static_cast<double>(size+1)/m_MinSize);
    }
}

} // end namespace otb

#endif
<|endoftext|>


<commit_before>/**
* @file IKParameters.cpp
*
* @author Xu, Yuan
* Implement of parameters for IK motion
*/

#include "IKParameters.h"

IKParameters::IKParameters()
:ParameterList("IKParameters")
{
  PARAMETER_REGISTER(footOffsetY) = 0;

  // stand parameter
  PARAMETER_REGISTER(stand.speed) = 0.01;
  PARAMETER_REGISTER(stand.enableStabilization) = false;
  PARAMETER_REGISTER(stand.stiffness) = 0.7;

  PARAMETER_ANGLE_REGISTER(stand.bodyPitchOffset) = 0.2;
  PARAMETER_REGISTER(stand.hipOffsetX) = 15;

  // relax
  PARAMETER_REGISTER(stand.relax.enable) = true;
  PARAMETER_REGISTER(stand.relax.allowedDeviation) = 5;   // [mm]
  PARAMETER_REGISTER(stand.relax.allowedRotationDeviation) = Math::fromDegrees(5);// [rad] todo: PARAMETER_ANGLE_REGISTER
  PARAMETER_REGISTER(stand.relax.timeBonusForCorrection)   = 1000; // [ms]

  PARAMETER_REGISTER(stand.relax.jointOffsetTuning.enable) = true;
  PARAMETER_REGISTER(stand.relax.jointOffsetTuning.deadTime)         = 1000;         // [ms]
  PARAMETER_REGISTER(stand.relax.jointOffsetTuning.currentThreshold) = 0.3;          // [A]
  PARAMETER_REGISTER(stand.relax.jointOffsetTuning.minimalJointStep) = 0.0013962634; // [rad]

  PARAMETER_REGISTER(stand.relax.stiffnessControl.enable) = true;
  PARAMETER_REGISTER(stand.relax.stiffnessControl.deadTime)     = 100;  // [ms]
  PARAMETER_REGISTER(stand.relax.stiffnessControl.minAngle)     = 0.08; // [°]
  PARAMETER_REGISTER(stand.relax.stiffnessControl.maxAngle)     = 2;    // [°]
  PARAMETER_REGISTER(stand.relax.stiffnessControl.minStiffness) = 0.3;
  PARAMETER_REGISTER(stand.relax.stiffnessControl.maxStiffness) = 1.0;

  // walk parameter:
  // General
  PARAMETER_ANGLE_REGISTER(walk.general.bodyPitchOffset) = 0.2;
  PARAMETER_REGISTER(walk.general.hipOffsetX) = 15;
  PARAMETER_REGISTER(walk.general.stiffness) = 0.7;
  PARAMETER_REGISTER(walk.general.useArm) = false;
  PARAMETER_REGISTER(walk.general.hipRollSingleSupFactorLeft) = 0.4;
  PARAMETER_REGISTER(walk.general.hipRollSingleSupFactorRight) = 0.4;

  // hip trajectory geometry
  PARAMETER_REGISTER(walk.hip.comHeight) = 260;
  PARAMETER_REGISTER(walk.hip.comHeightOffset) = 0.18;
  PARAMETER_REGISTER(walk.hip.comRotationOffsetX) = 0;
  PARAMETER_REGISTER(walk.hip.ZMPOffsetY) = 5;
  PARAMETER_REGISTER(walk.hip.ZMPOffsetYByCharacter) = 0;

  // step geometry
  PARAMETER_REGISTER(walk.step.duration) = 300;
  PARAMETER_REGISTER(walk.step.doubleSupportTime) = 40;

  PARAMETER_REGISTER(walk.step.stepHeight) = 10;

  // step limits
  PARAMETER_REGISTER(walk.limits.maxTurnInner) = 10;
  PARAMETER_REGISTER(walk.limits.maxStepTurn) = 30;
  PARAMETER_REGISTER(walk.limits.maxStepLength) = 50;
  PARAMETER_REGISTER(walk.limits.maxStepLengthBack) = 50;
  PARAMETER_REGISTER(walk.limits.maxStepWidth) = 50;
  PARAMETER_REGISTER(walk.limits.maxStepChange) = 0.5;

  // step control
  PARAMETER_REGISTER(walk.limits.maxCtrlTurn) = 30;
  PARAMETER_REGISTER(walk.limits.maxCtrlLength) = 80;
  PARAMETER_REGISTER(walk.limits.maxCtrlWidth) = 50;

  // Stabilization
  //PARAMETER_REGISTER(walk.stabilization.enableFSRProtection) = true;
  //PARAMETER_REGISTER(walk.stabilization.enableWaitLanding) = false;
  //PARAMETER_REGISTER(walk.stabilization.minFSRProtectionCount) = 0;
  //PARAMETER_REGISTER(walk.stabilization.maxUnsupportedCount) = 0;
  //PARAMETER_REGISTER(walk.stabilization.maxWaitLandingCount) = 20;

  PARAMETER_REGISTER(walk.stabilization.emergencyStopError) = 500;

  PARAMETER_REGISTER(walk.stabilization.rotationStabilize) = true;
  PARAMETER_REGISTER(walk.stabilization.rotationP.x) = 0;
  PARAMETER_REGISTER(walk.stabilization.rotationP.y) = 0;
  PARAMETER_REGISTER(walk.stabilization.rotationVelocityP.x) = 0;
  PARAMETER_REGISTER(walk.stabilization.rotationVelocityP.y) = 0;
  PARAMETER_REGISTER(walk.stabilization.rotationD.x) = 0;
  PARAMETER_REGISTER(walk.stabilization.rotationD.y) = 0;

  PARAMETER_REGISTER(walk.stabilization.stabilizeFeet) = true;
  PARAMETER_REGISTER(walk.stabilization.stabilizeFeetP.x) = 0.04;
  PARAMETER_REGISTER(walk.stabilization.stabilizeFeetP.y) = 0.035;
  PARAMETER_REGISTER(walk.stabilization.stabilizeFeetD.x) = -0.4;
  PARAMETER_REGISTER(walk.stabilization.stabilizeFeetD.y) = -0.3;

  PARAMETER_REGISTER(walk.stabilization.dynamicStepsize) = true;
  PARAMETER_REGISTER(walk.stabilization.dynamicStepsizeP) = -1;
  PARAMETER_REGISTER(walk.stabilization.dynamicStepsizeD) = 0.5;

  // rotation stabilize parameter
  PARAMETER_REGISTER(rotationStabilize.k.x) = -0.5;
  PARAMETER_REGISTER(rotationStabilize.k.y) = -0.2;
  PARAMETER_REGISTER(rotationStabilize.threshold.x) = 2;
  PARAMETER_REGISTER(rotationStabilize.threshold.y) = 3;

  // arm parameter
  PARAMETER_REGISTER(arm.shoulderPitchInterialSensorRate) = -10;
  PARAMETER_REGISTER(arm.shoulderRollInterialSensorRate) = -10;
  PARAMETER_REGISTER(arm.maxSpeed) = 60;
  PARAMETER_REGISTER(arm.alwaysEnabled)  = false;
  PARAMETER_REGISTER(arm.kickEnabled) = true;
  PARAMETER_REGISTER(arm.walkEnabled) = true;
  PARAMETER_REGISTER(arm.takeBack) = false;

  PARAMETER_REGISTER(balanceCoM.kP) = 0;
  PARAMETER_REGISTER(balanceCoM.kI) = 0;
  PARAMETER_REGISTER(balanceCoM.kD) = 0;
  PARAMETER_REGISTER(balanceCoM.threshold) = 10;

  syncWithConfig();

}

IKParameters::~IKParameters()
{
}
<commit_msg>redo initial parameters<commit_after>/**
* @file IKParameters.cpp
*
* @author Xu, Yuan
* Implement of parameters for IK motion
*/

#include "IKParameters.h"

IKParameters::IKParameters()
:ParameterList("IKParameters")
{
  PARAMETER_REGISTER(footOffsetY) = 0;

  // stand parameter
  PARAMETER_REGISTER(stand.speed) = 0.04;
  PARAMETER_REGISTER(stand.enableStabilization) = true;
  PARAMETER_REGISTER(stand.stiffness) = 0.7;

  PARAMETER_ANGLE_REGISTER(stand.bodyPitchOffset) = 0.2;
  PARAMETER_REGISTER(stand.hipOffsetX) = 15;

  // relax
  PARAMETER_REGISTER(stand.relax.enable) = true;
  PARAMETER_REGISTER(stand.relax.allowedDeviation) = 5;   // [mm]
  PARAMETER_REGISTER(stand.relax.allowedRotationDeviation) = Math::fromDegrees(5);// [rad] todo: PARAMETER_ANGLE_REGISTER
  PARAMETER_REGISTER(stand.relax.timeBonusForCorrection)   = 1000; // [ms]

  PARAMETER_REGISTER(stand.relax.jointOffsetTuning.enable) = true;
  PARAMETER_REGISTER(stand.relax.jointOffsetTuning.deadTime)         = 1000;         // [ms]
  PARAMETER_REGISTER(stand.relax.jointOffsetTuning.currentThreshold) = 0.3;          // [A]
  PARAMETER_REGISTER(stand.relax.jointOffsetTuning.minimalJointStep) = 0.0013962634; // [rad]

  PARAMETER_REGISTER(stand.relax.stiffnessControl.enable) = true;
  PARAMETER_REGISTER(stand.relax.stiffnessControl.deadTime)     = 100;  // [ms]
  PARAMETER_REGISTER(stand.relax.stiffnessControl.minAngle)     = 0.08; // [°]
  PARAMETER_REGISTER(stand.relax.stiffnessControl.maxAngle)     = 2;    // [°]
  PARAMETER_REGISTER(stand.relax.stiffnessControl.minStiffness) = 0.3;
  PARAMETER_REGISTER(stand.relax.stiffnessControl.maxStiffness) = 1.0;

  // walk parameter:
  // General
  PARAMETER_ANGLE_REGISTER(walk.general.bodyPitchOffset) = 0.2;
  PARAMETER_REGISTER(walk.general.hipOffsetX) = 15;
  PARAMETER_REGISTER(walk.general.stiffness) = 0.7;
  PARAMETER_REGISTER(walk.general.useArm) = false;
  PARAMETER_REGISTER(walk.general.hipRollSingleSupFactorLeft) = 0.4;
  PARAMETER_REGISTER(walk.general.hipRollSingleSupFactorRight) = 0.4;

  // hip trajectory geometry
  PARAMETER_REGISTER(walk.hip.comHeight) = 260;
  PARAMETER_REGISTER(walk.hip.comHeightOffset) = 0.18;
  PARAMETER_REGISTER(walk.hip.comRotationOffsetX) = 0;
  PARAMETER_REGISTER(walk.hip.ZMPOffsetY) = 5;
  PARAMETER_REGISTER(walk.hip.ZMPOffsetYByCharacter) = 0;

  // step geometry
  PARAMETER_REGISTER(walk.step.duration) = 300;
  PARAMETER_REGISTER(walk.step.doubleSupportTime) = 40;

  PARAMETER_REGISTER(walk.step.stepHeight) = 10;

  // step limits
  PARAMETER_REGISTER(walk.limits.maxTurnInner) = 10;
  PARAMETER_REGISTER(walk.limits.maxStepTurn) = 30;
  PARAMETER_REGISTER(walk.limits.maxStepLength) = 50;
  PARAMETER_REGISTER(walk.limits.maxStepLengthBack) = 50;
  PARAMETER_REGISTER(walk.limits.maxStepWidth) = 50;
  PARAMETER_REGISTER(walk.limits.maxStepChange) = 0.5;

  // step control
  PARAMETER_REGISTER(walk.limits.maxCtrlTurn) = 30;
  PARAMETER_REGISTER(walk.limits.maxCtrlLength) = 80;
  PARAMETER_REGISTER(walk.limits.maxCtrlWidth) = 50;

  // Stabilization
  //PARAMETER_REGISTER(walk.stabilization.enableFSRProtection) = true;
  //PARAMETER_REGISTER(walk.stabilization.enableWaitLanding) = false;
  //PARAMETER_REGISTER(walk.stabilization.minFSRProtectionCount) = 0;
  //PARAMETER_REGISTER(walk.stabilization.maxUnsupportedCount) = 0;
  //PARAMETER_REGISTER(walk.stabilization.maxWaitLandingCount) = 20;

  PARAMETER_REGISTER(walk.stabilization.emergencyStopError) = 500;

  PARAMETER_REGISTER(walk.stabilization.rotationStabilize) = true;
  PARAMETER_REGISTER(walk.stabilization.rotationP.x) = 0;
  PARAMETER_REGISTER(walk.stabilization.rotationP.y) = 0;
  PARAMETER_REGISTER(walk.stabilization.rotationVelocityP.x) = 0;
  PARAMETER_REGISTER(walk.stabilization.rotationVelocityP.y) = 0;
  PARAMETER_REGISTER(walk.stabilization.rotationD.x) = 0;
  PARAMETER_REGISTER(walk.stabilization.rotationD.y) = 0;

  PARAMETER_REGISTER(walk.stabilization.stabilizeFeet) = true;
  PARAMETER_REGISTER(walk.stabilization.stabilizeFeetP.x) = 0.04;
  PARAMETER_REGISTER(walk.stabilization.stabilizeFeetP.y) = 0.035;
  PARAMETER_REGISTER(walk.stabilization.stabilizeFeetD.x) = -0.4;
  PARAMETER_REGISTER(walk.stabilization.stabilizeFeetD.y) = -0.3;

  PARAMETER_REGISTER(walk.stabilization.dynamicStepsize) = true;
  PARAMETER_REGISTER(walk.stabilization.dynamicStepsizeP) = -1;
  PARAMETER_REGISTER(walk.stabilization.dynamicStepsizeD) = 0.5;

  // rotation stabilize parameter
  PARAMETER_REGISTER(rotationStabilize.k.x) = -0.5;
  PARAMETER_REGISTER(rotationStabilize.k.y) = -0.2;
  PARAMETER_REGISTER(rotationStabilize.threshold.x) = 2;
  PARAMETER_REGISTER(rotationStabilize.threshold.y) = 3;

  // arm parameter
  PARAMETER_REGISTER(arm.shoulderPitchInterialSensorRate) = -10;
  PARAMETER_REGISTER(arm.shoulderRollInterialSensorRate) = -10;
  PARAMETER_REGISTER(arm.maxSpeed) = 60;
  PARAMETER_REGISTER(arm.alwaysEnabled)  = false;
  PARAMETER_REGISTER(arm.kickEnabled) = true;
  PARAMETER_REGISTER(arm.walkEnabled) = true;
  PARAMETER_REGISTER(arm.takeBack) = false;

  PARAMETER_REGISTER(balanceCoM.kP) = 0;
  PARAMETER_REGISTER(balanceCoM.kI) = 0;
  PARAMETER_REGISTER(balanceCoM.kD) = 0;
  PARAMETER_REGISTER(balanceCoM.threshold) = 10;

  syncWithConfig();

}

IKParameters::~IKParameters()
{
}
<|endoftext|>


<commit_before><commit_msg>Add the initial template of answer to question 5.1<commit_after><|endoftext|>