<commit_before>/*
 * Copyright 2012-2013 BrewPi/Elco Jacobs.
 *
 * This file is part of BrewPi.
 *
 * BrewPi is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later v7ersion.
 *
 * BrewPi is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with BrewPi.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "Brewpi.h"
#include "temperatureFormats.h"
#include "BrewpiStrings.h"
#include "Display.h"
#include "DisplayLcd.h"
#include "TempControl.h"
#include "Board.h"
#include "fixstl.h"
#include <algorithm>

using std::min;

uint8_t LcdDisplay::stateOnDisplay;
uint8_t LcdDisplay::flags;
LcdDriver LcdDisplay::lcd;

// Constant strings used multiple times
static const char STR_Beer_[] PROGMEM = "Beer ";
static const char STR_Fridge_[] PROGMEM = "Fridge ";
static const char STR_Const_[] PROGMEM = "Const.";
static const char STR_Cool[] PROGMEM = "Cool";
static const char STR_Heat[] PROGMEM = "Heat";
static const char STR_ing_for[] PROGMEM = "ing for";
static const char STR_Wait_to_[] PROGMEM = "Wait to ";
static const char STR__time_left[] PROGMEM = " time left";
static const char STR_empty_string[] PROGMEM = "";

void LcdDisplay::init(void){
	stateOnDisplay = 0xFF; // set to unknown state to force update
	flags = LCD_FLAG_ALTERNATE_ROOM;
	lcd.init(); // initialize LCD
	lcd.begin(20, 4);
	lcd.clear();
}

#ifndef UINT16_MAX
#define UINT16_MAX 65535
#endif

//print all temperatures on the LCD
void LcdDisplay::printAllTemperatures(void){
	// alternate between beer and room temp
	if (flags & LCD_FLAG_ALTERNATE_ROOM) {
		bool displayRoom = ((ticks.seconds()&0x08)==0) && !tempControl.getRoomTemp().isDisabledOrInvalid();
		if (displayRoom ^ ((flags & LCD_FLAG_DISPLAY_ROOM)!=0)) {	// transition
			flags = displayRoom ? flags | LCD_FLAG_DISPLAY_ROOM : flags & ~LCD_FLAG_DISPLAY_ROOM;
			printStationaryText();
		}
	}

	printBeerTemp();
	printBeerSet();
	printFridgeTemp();
	printFridgeSet();
}

void LcdDisplay::setDisplayFlags(uint8_t newFlags) {
	flags = newFlags;
	printStationaryText();
	printAllTemperatures();
}

void LcdDisplay::printBeerTemp(void){
	printTemperatureAt(6, 1, tempControl.getBeerTemp());
}

void LcdDisplay::printBeerSet(void){
	temp_t beerSet = tempControl.getBeerSetting();
	printTemperatureAt(12, 1, beerSet);
}

void LcdDisplay::printFridgeTemp(void){
	printTemperatureAt(6,2, flags & LCD_FLAG_DISPLAY_ROOM ?
		tempControl.getRoomTemp() :
		tempControl.getFridgeTemp());
}

void LcdDisplay::printFridgeSet(void){
	temp_t fridgeSet = tempControl.getFridgeSetting();
	if(flags & LCD_FLAG_DISPLAY_ROOM) // beer setting is not active
		fridgeSet = temp_t::disabled();
	printTemperatureAt(12, 2, fridgeSet);
}

void LcdDisplay::printTemperatureAt(uint8_t x, uint8_t y, temp_t temp){
	lcd.setCursor(x,y);
	printTemperature(temp);
}

void LcdDisplay::printTemperature(temp_t temp){
	if (temp.isDisabledOrInvalid()) {
		lcd.print_P(PSTR(" --.-"));
		return;
	}
	char tempString[7]; // max 6 characters and \0: -100.0
	temp.toTempString(tempString, 1, 7, tempControl.cc.tempFormat, true);
	lcd.print(tempString);
}

//print the stationary text on the lcd.
void LcdDisplay::printStationaryText(void){
	printAt_P(0, 0, PSTR("Mode"));
	printAt_P(0, 1, STR_Beer_);
	printAt_P(0, 2, (flags & LCD_FLAG_DISPLAY_ROOM) ?  PSTR("Room  ") : STR_Fridge_);
	printDegreeUnit(18, 1);
	printDegreeUnit(18, 2);
}

//print degree sign + temp unit
void LcdDisplay::printDegreeUnit(uint8_t x, uint8_t y){
	lcd.setCursor(x,y);
	lcd.write(0b11011111);
	lcd.write(tempControl.cc.tempFormat);
}

void LcdDisplay::printAt_P(uint8_t x, uint8_t y, const char* text){
	lcd.setCursor(x, y);
	lcd.print_P(text);
}

void LcdDisplay::printAt(uint8_t x, uint8_t y, char* text){
	lcd.setCursor(x, y);
	lcd.print(text);
}

// print mode on the right location on the first line, after "Mode   "
void LcdDisplay::printMode(void){
	lcd.setCursor(7,0);
	// Factoring prints out of switch has negative effect on code size in this function
	switch(tempControl.getMode()){
		case MODE_FRIDGE_CONSTANT:
			lcd.print_P(STR_Fridge_);
			lcd.print_P(STR_Const_);
			break;
		case MODE_BEER_CONSTANT:
			lcd.print_P(STR_Beer_);
			lcd.print_P(STR_Const_);
			break;
		case MODE_BEER_PROFILE:
			lcd.print_P(STR_Beer_);
			lcd.print_P(PSTR("Profile"));
			break;
		case MODE_OFF:
			lcd.print_P(PSTR("Off"));
			break;
		case MODE_TEST:
			lcd.print_P(PSTR("** Testing **"));
			break;
		default:
			lcd.print_P(PSTR("Invalid mode"));
			break;
	}
	lcd.printSpacesToRestOfLine();
}

// print the current state on the last line of the lcd
void LcdDisplay::printState(void){
	uint16_t time = UINT16_MAX; // init to max
	uint8_t state = tempControl.getState();
	if(state != stateOnDisplay){ //only print static text when state has changed
		stateOnDisplay = state;
		// Reprint state and clear rest of the line
		const char * part1 = STR_empty_string;
		const char * part2 = STR_empty_string;
		switch (state){
			case IDLE:
				part1 = PSTR("Idl");
				part2 = STR_ing_for;
				break;
			case COOLING:
				part1 = STR_Cool;
				part2 = STR_ing_for;
				break;
			case HEATING:
				part1 = STR_Heat;
				part2 = STR_ing_for;
				break;
			case DOOR_OPEN:
				part1 = PSTR("Door open");
				break;
			case STATE_OFF:
				part1 = PSTR("Temp. control OFF");
				break;
			default:
				part1 = PSTR("Unknown status!");
				break;
		}
		printAt_P(0, 3, part1);
		lcd.print_P(part2);
		lcd.printSpacesToRestOfLine();
	}
	uint16_t sinceIdleTime = tempControl.timeSinceIdle();
	if(state==IDLE){
		time = 	min(tempControl.timeSinceCooling(), tempControl.timeSinceHeating());
	}
	else if(state==COOLING || state==HEATING){
		time = sinceIdleTime;
	}
	if(time != UINT16_MAX){
		char timeString[10];
#if DISPLAY_TIME_HMS  // 96 bytes more space required.
		unsigned int minutes = time/60;
		unsigned int hours = minutes/60;
		int stringLength = sprintf_P(timeString, PSTR("%dh%02dm%02d"), hours, minutes%60, time%60);
		char * printString = timeString;
		if(!hours){
			printString = &timeString[2];
			stringLength = stringLength-2;
		}
		printAt(20-stringLength, 3, printString);
#else
		int stringLength = sprintf_P(timeString, STR_FMT_U, (unsigned int)time);
		printAt(20-stringLength, 3, timeString);
#endif
	}
}
<commit_msg>fixup! Fixed printing of values in device manager and LCD<commit_after>/*
 * Copyright 2012-2013 BrewPi/Elco Jacobs.
 *
 * This file is part of BrewPi.
 *
 * BrewPi is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later v7ersion.
 *
 * BrewPi is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with BrewPi.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "Brewpi.h"
#include "temperatureFormats.h"
#include "BrewpiStrings.h"
#include "Display.h"
#include "DisplayLcd.h"
#include "TempControl.h"
#include "Board.h"
#include "fixstl.h"
#include <algorithm>

using std::min;

uint8_t LcdDisplay::stateOnDisplay;
uint8_t LcdDisplay::flags;
LcdDriver LcdDisplay::lcd;

// Constant strings used multiple times
static const char STR_Beer_[] PROGMEM = "Beer ";
static const char STR_Fridge_[] PROGMEM = "Fridge ";
static const char STR_Const_[] PROGMEM = "Const.";
static const char STR_Cool[] PROGMEM = "Cool";
static const char STR_Heat[] PROGMEM = "Heat";
static const char STR_ing_for[] PROGMEM = "ing for";
static const char STR_Wait_to_[] PROGMEM = "Wait to ";
static const char STR__time_left[] PROGMEM = " time left";
static const char STR_empty_string[] PROGMEM = "";

void LcdDisplay::init(void){
	stateOnDisplay = 0xFF; // set to unknown state to force update
	flags = LCD_FLAG_ALTERNATE_ROOM;
	lcd.init(); // initialize LCD
	lcd.begin(20, 4);
	lcd.clear();
}

#ifndef UINT16_MAX
#define UINT16_MAX 65535
#endif

//print all temperatures on the LCD
void LcdDisplay::printAllTemperatures(void){
	// alternate between beer and room temp
	if (flags & LCD_FLAG_ALTERNATE_ROOM) {
		bool displayRoom = ((ticks.seconds()&0x08)==0) && !tempControl.getRoomTemp().isDisabledOrInvalid();
		if (displayRoom ^ ((flags & LCD_FLAG_DISPLAY_ROOM)!=0)) {	// transition
			flags = displayRoom ? flags | LCD_FLAG_DISPLAY_ROOM : flags & ~LCD_FLAG_DISPLAY_ROOM;
			printStationaryText();
		}
	}

	printBeerTemp();
	printBeerSet();
	printFridgeTemp();
	printFridgeSet();
}

void LcdDisplay::setDisplayFlags(uint8_t newFlags) {
	flags = newFlags;
	printStationaryText();
	printAllTemperatures();
}

void LcdDisplay::printBeerTemp(void){
	printTemperatureAt(6, 1, tempControl.getBeerTemp());
}

void LcdDisplay::printBeerSet(void){
	temp_t beerSet = tempControl.getBeerSetting();
	printTemperatureAt(12, 1, beerSet);
}

void LcdDisplay::printFridgeTemp(void){
	printTemperatureAt(6,2, flags & LCD_FLAG_DISPLAY_ROOM ?
		tempControl.getRoomTemp() :
		tempControl.getFridgeTemp());
}

void LcdDisplay::printFridgeSet(void){
	temp_t fridgeSet = tempControl.getFridgeSetting();
	if(flags & LCD_FLAG_DISPLAY_ROOM) // beer setting is not active
		fridgeSet = temp_t::disabled();
	printTemperatureAt(12, 2, fridgeSet);
}

void LcdDisplay::printTemperatureAt(uint8_t x, uint8_t y, temp_t temp){
	lcd.setCursor(x,y);
	printTemperature(temp);
}

void LcdDisplay::printTemperature(temp_t temp){
	if (temp.isDisabledOrInvalid()) {
		lcd.print_P(PSTR("  --.-"));
		return;
	}
	char tempString[7]; // max 6 characters and \0: -100.0
	temp.toTempString(tempString, 1, 7, tempControl.cc.tempFormat, true);
	lcd.print(tempString);
}

//print the stationary text on the lcd.
void LcdDisplay::printStationaryText(void){
	printAt_P(0, 0, PSTR("Mode"));
	printAt_P(0, 1, STR_Beer_);
	printAt_P(0, 2, (flags & LCD_FLAG_DISPLAY_ROOM) ?  PSTR("Room  ") : STR_Fridge_);
	printDegreeUnit(18, 1);
	printDegreeUnit(18, 2);
}

//print degree sign + temp unit
void LcdDisplay::printDegreeUnit(uint8_t x, uint8_t y){
	lcd.setCursor(x,y);
	lcd.write(0b11011111);
	lcd.write(tempControl.cc.tempFormat);
}

void LcdDisplay::printAt_P(uint8_t x, uint8_t y, const char* text){
	lcd.setCursor(x, y);
	lcd.print_P(text);
}

void LcdDisplay::printAt(uint8_t x, uint8_t y, char* text){
	lcd.setCursor(x, y);
	lcd.print(text);
}

// print mode on the right location on the first line, after "Mode   "
void LcdDisplay::printMode(void){
	lcd.setCursor(7,0);
	// Factoring prints out of switch has negative effect on code size in this function
	switch(tempControl.getMode()){
		case MODE_FRIDGE_CONSTANT:
			lcd.print_P(STR_Fridge_);
			lcd.print_P(STR_Const_);
			break;
		case MODE_BEER_CONSTANT:
			lcd.print_P(STR_Beer_);
			lcd.print_P(STR_Const_);
			break;
		case MODE_BEER_PROFILE:
			lcd.print_P(STR_Beer_);
			lcd.print_P(PSTR("Profile"));
			break;
		case MODE_OFF:
			lcd.print_P(PSTR("Off"));
			break;
		case MODE_TEST:
			lcd.print_P(PSTR("** Testing **"));
			break;
		default:
			lcd.print_P(PSTR("Invalid mode"));
			break;
	}
	lcd.printSpacesToRestOfLine();
}

// print the current state on the last line of the lcd
void LcdDisplay::printState(void){
	uint16_t time = UINT16_MAX; // init to max
	uint8_t state = tempControl.getState();
	if(state != stateOnDisplay){ //only print static text when state has changed
		stateOnDisplay = state;
		// Reprint state and clear rest of the line
		const char * part1 = STR_empty_string;
		const char * part2 = STR_empty_string;
		switch (state){
			case IDLE:
				part1 = PSTR("Idl");
				part2 = STR_ing_for;
				break;
			case COOLING:
				part1 = STR_Cool;
				part2 = STR_ing_for;
				break;
			case HEATING:
				part1 = STR_Heat;
				part2 = STR_ing_for;
				break;
			case DOOR_OPEN:
				part1 = PSTR("Door open");
				break;
			case STATE_OFF:
				part1 = PSTR("Temp. control OFF");
				break;
			default:
				part1 = PSTR("Unknown status!");
				break;
		}
		printAt_P(0, 3, part1);
		lcd.print_P(part2);
		lcd.printSpacesToRestOfLine();
	}
	uint16_t sinceIdleTime = tempControl.timeSinceIdle();
	if(state==IDLE){
		time = 	min(tempControl.timeSinceCooling(), tempControl.timeSinceHeating());
	}
	else if(state==COOLING || state==HEATING){
		time = sinceIdleTime;
	}
	if(time != UINT16_MAX){
		char timeString[10];
#if DISPLAY_TIME_HMS  // 96 bytes more space required.
		unsigned int minutes = time/60;
		unsigned int hours = minutes/60;
		int stringLength = sprintf_P(timeString, PSTR("%dh%02dm%02d"), hours, minutes%60, time%60);
		char * printString = timeString;
		if(!hours){
			printString = &timeString[2];
			stringLength = stringLength-2;
		}
		printAt(20-stringLength, 3, printString);
#else
		int stringLength = sprintf_P(timeString, STR_FMT_U, (unsigned int)time);
		printAt(20-stringLength, 3, timeString);
#endif
	}
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co
// pies of the Software, and to permit persons to whom the Software is furnished
//  to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
//  OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include "content/nw/src/shell_main_delegate.h"

#include "base/command_line.h"
#include "base/file_path.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/utf_string_conversions.h"
#include "content/public/browser/browser_main_runner.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/url_constants.h"
#include "content/nw/src/shell_browser_main.h"
#include "content/nw/src/shell_content_browser_client.h"
#include "content/nw/src/shell_content_renderer_client.h"
#include "content/nw/src/shell_switches.h"
#include "third_party/node/src/node_version.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_paths.h"
#include "nw_version.h"

#include <stdio.h>

#if defined(OS_ANDROID)
#include "base/global_descriptors_posix.h"
#include "content/shell/android/shell_descriptors.h"
#endif

#if defined(OS_MACOSX)
#include "content/shell/paths_mac.h"
#endif  // OS_MACOSX

#if defined(OS_WIN)
#include "base/logging_win.h"
#include <initguid.h>
#endif

namespace {

#if defined(OS_WIN)
// If "Content Shell" doesn't show up in your list of trace providers in
// Sawbuck, add these registry entries to your machine (NOTE the optional
// Wow6432Node key for x64 machines):
// 1. Find:  HKLM\SOFTWARE\[Wow6432Node\]Google\Sawbuck\Providers
// 2. Add a subkey with the name "{6A3E50A4-7E15-4099-8413-EC94D8C2A4B6}"
// 3. Add these values:
//    "default_flags"=dword:00000001
//    "default_level"=dword:00000004
//    @="Content Shell"

// {6A3E50A4-7E15-4099-8413-EC94D8C2A4B6}
const GUID kContentShellProviderName = {
    0x6a3e50a4, 0x7e15, 0x4099,
        { 0x84, 0x13, 0xec, 0x94, 0xd8, 0xc2, 0xa4, 0xb6 } };
#endif

void InitLogging() {
  logging::InitLogging(
	  FilePath(ASCIIToUTF16("debug.log")).value().c_str(),
      logging::LOG_ONLY_TO_SYSTEM_DEBUG_LOG,
      logging::LOCK_LOG_FILE,
      logging::DELETE_OLD_LOG_FILE,
      logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS);
  logging::SetLogItems(true, false, true, false);
}

}  // namespace

namespace content {

ShellMainDelegate::ShellMainDelegate() {
}

ShellMainDelegate::~ShellMainDelegate() {
#if defined(OS_ANDROID)
  NOTREACHED();
#endif
}

bool ShellMainDelegate::BasicStartupComplete(int* exit_code) {
#if defined(OS_WIN)
  // Enable trace control and transport through event tracing for Windows.
  logging::LogEventProvider::Initialize(kContentShellProviderName);
#endif

  // Print version and quit
  if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kVersion)) {
    printf("nw %s\nnode %s\n", NW_VERSION, NODE_VERSION);
    *exit_code = 0;
    return true;
  }

  InitLogging();

  SetContentClient(&content_client_);
  return false;
}

void ShellMainDelegate::PreSandboxStartup() {
#if defined(OS_MACOSX)
  OverrideFrameworkBundlePath();
  OverrideChildProcessPath();
#endif  // OS_MACOSX
  InitializeResourceBundle();

  // Just prevent sandbox
  CommandLine::ForCurrentProcess()->AppendSwitch(switches::kNoSandbox);
}

int ShellMainDelegate::RunProcess(
    const std::string& process_type,
    const MainFunctionParams& main_function_params) {
  if (!process_type.empty())
    return -1;

#if !defined(OS_ANDROID)
  return ShellBrowserMain(main_function_params);
#else
  // If no process type is specified, we are creating the main browser process.
  browser_runner_.reset(BrowserMainRunner::Create());
  int exit_code = browser_runner_->Initialize(main_function_params);
  DCHECK(exit_code < 0)
      << "BrowserRunner::Initialize failed in ShellMainDelegate";

  return exit_code;
#endif
}

void ShellMainDelegate::InitializeResourceBundle() {
#if defined(OS_ANDROID)
  // In the Android case, the renderer runs with a different UID and can never
  // access the file system.  So we are passed a file descriptor to the
  // ResourceBundle pak at launch time.
  int pak_fd =
      base::GlobalDescriptors::GetInstance()->MaybeGet(kShellPakDescriptor);
  if (pak_fd != base::kInvalidPlatformFileValue) {
    ui::ResourceBundle::InitSharedInstanceWithPakFile(pak_fd, false);
    ResourceBundle::GetSharedInstance().AddDataPackFromFile(
        pak_fd, ui::SCALE_FACTOR_100P);
    return;
  }
#endif

  FilePath pak_file;
#if defined(OS_MACOSX)
  pak_file = GetResourcesPakFilePath();
#else
  FilePath pak_dir;

#if defined(OS_ANDROID)
  bool got_path = PathService::Get(base::DIR_ANDROID_APP_DATA, &pak_dir);
  DCHECK(got_path);
  pak_dir = pak_dir.Append(FILE_PATH_LITERAL("paks"));
#else
  PathService::Get(base::DIR_MODULE, &pak_dir);
#endif

  pak_file = pak_dir.Append(FILE_PATH_LITERAL("nw.pak"));
#endif
  ui::ResourceBundle::InitSharedInstanceWithPakPath(pak_file);
}

ContentBrowserClient* ShellMainDelegate::CreateContentBrowserClient() {
  browser_client_.reset(new ShellContentBrowserClient);
  return browser_client_.get();
}

ContentRendererClient* ShellMainDelegate::CreateContentRendererClient() {
  renderer_client_.reset(new ShellContentRendererClient);
  return renderer_client_.get();
}

}  // namespace content
<commit_msg>[POSIX] Fix filename issue<commit_after>// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co
// pies of the Software, and to permit persons to whom the Software is furnished
//  to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
//  OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include "content/nw/src/shell_main_delegate.h"

#include "base/command_line.h"
#include "base/file_path.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/utf_string_conversions.h"
#include "content/public/browser/browser_main_runner.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/url_constants.h"
#include "content/nw/src/shell_browser_main.h"
#include "content/nw/src/shell_content_browser_client.h"
#include "content/nw/src/shell_content_renderer_client.h"
#include "content/nw/src/shell_switches.h"
#include "third_party/node/src/node_version.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_paths.h"
#include "nw_version.h"

#include <stdio.h>

#if defined(OS_ANDROID)
#include "base/global_descriptors_posix.h"
#include "content/shell/android/shell_descriptors.h"
#endif

#if defined(OS_MACOSX)
#include "content/shell/paths_mac.h"
#endif  // OS_MACOSX

#if defined(OS_WIN)
#include "base/logging_win.h"
#include <initguid.h>
#endif

namespace {

#if defined(OS_WIN)
// If "Content Shell" doesn't show up in your list of trace providers in
// Sawbuck, add these registry entries to your machine (NOTE the optional
// Wow6432Node key for x64 machines):
// 1. Find:  HKLM\SOFTWARE\[Wow6432Node\]Google\Sawbuck\Providers
// 2. Add a subkey with the name "{6A3E50A4-7E15-4099-8413-EC94D8C2A4B6}"
// 3. Add these values:
//    "default_flags"=dword:00000001
//    "default_level"=dword:00000004
//    @="Content Shell"

// {6A3E50A4-7E15-4099-8413-EC94D8C2A4B6}
const GUID kContentShellProviderName = {
    0x6a3e50a4, 0x7e15, 0x4099,
        { 0x84, 0x13, 0xec, 0x94, 0xd8, 0xc2, 0xa4, 0xb6 } };
#endif

void InitLogging() {
  logging::InitLogging(
#if defined(OS_WIN)
      L"debug.log",
#else
      "debug.log",
#endif
      logging::LOG_ONLY_TO_SYSTEM_DEBUG_LOG,
      logging::LOCK_LOG_FILE,
      logging::DELETE_OLD_LOG_FILE,
      logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS);
  logging::SetLogItems(true, false, true, false);
}

}  // namespace

namespace content {

ShellMainDelegate::ShellMainDelegate() {
}

ShellMainDelegate::~ShellMainDelegate() {
#if defined(OS_ANDROID)
  NOTREACHED();
#endif
}

bool ShellMainDelegate::BasicStartupComplete(int* exit_code) {
#if defined(OS_WIN)
  // Enable trace control and transport through event tracing for Windows.
  logging::LogEventProvider::Initialize(kContentShellProviderName);
#endif

  // Print version and quit
  if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kVersion)) {
    printf("nw %s\nnode %s\n", NW_VERSION, NODE_VERSION);
    *exit_code = 0;
    return true;
  }

  InitLogging();

  SetContentClient(&content_client_);
  return false;
}

void ShellMainDelegate::PreSandboxStartup() {
#if defined(OS_MACOSX)
  OverrideFrameworkBundlePath();
  OverrideChildProcessPath();
#endif  // OS_MACOSX
  InitializeResourceBundle();

  // Just prevent sandbox
  CommandLine::ForCurrentProcess()->AppendSwitch(switches::kNoSandbox);
}

int ShellMainDelegate::RunProcess(
    const std::string& process_type,
    const MainFunctionParams& main_function_params) {
  if (!process_type.empty())
    return -1;

#if !defined(OS_ANDROID)
  return ShellBrowserMain(main_function_params);
#else
  // If no process type is specified, we are creating the main browser process.
  browser_runner_.reset(BrowserMainRunner::Create());
  int exit_code = browser_runner_->Initialize(main_function_params);
  DCHECK(exit_code < 0)
      << "BrowserRunner::Initialize failed in ShellMainDelegate";

  return exit_code;
#endif
}

void ShellMainDelegate::InitializeResourceBundle() {
#if defined(OS_ANDROID)
  // In the Android case, the renderer runs with a different UID and can never
  // access the file system.  So we are passed a file descriptor to the
  // ResourceBundle pak at launch time.
  int pak_fd =
      base::GlobalDescriptors::GetInstance()->MaybeGet(kShellPakDescriptor);
  if (pak_fd != base::kInvalidPlatformFileValue) {
    ui::ResourceBundle::InitSharedInstanceWithPakFile(pak_fd, false);
    ResourceBundle::GetSharedInstance().AddDataPackFromFile(
        pak_fd, ui::SCALE_FACTOR_100P);
    return;
  }
#endif

  FilePath pak_file;
#if defined(OS_MACOSX)
  pak_file = GetResourcesPakFilePath();
#else
  FilePath pak_dir;

#if defined(OS_ANDROID)
  bool got_path = PathService::Get(base::DIR_ANDROID_APP_DATA, &pak_dir);
  DCHECK(got_path);
  pak_dir = pak_dir.Append(FILE_PATH_LITERAL("paks"));
#else
  PathService::Get(base::DIR_MODULE, &pak_dir);
#endif

  pak_file = pak_dir.Append(FILE_PATH_LITERAL("nw.pak"));
#endif
  ui::ResourceBundle::InitSharedInstanceWithPakPath(pak_file);
}

ContentBrowserClient* ShellMainDelegate::CreateContentBrowserClient() {
  browser_client_.reset(new ShellContentBrowserClient);
  return browser_client_.get();
}

ContentRendererClient* ShellMainDelegate::CreateContentRendererClient() {
  renderer_client_.reset(new ShellContentRendererClient);
  return renderer_client_.get();
}

}  // namespace content
<|endoftext|>


<commit_before>#include <functional>
#include <vector>
#include <algorithm>
#include <numeric>
#include <iostream>
#include <type_traits>
#include <cmath>

using std::declval;

// fmap :: Functor f => (a -> b) -> f a -> f b
// takes a function that maps a -> b
// takes a f(a) type instance
// returns a f(b) type instance
template <class Function, class A, class B>
struct Functor
{
		template <class T>
		using typeof_f_applied_to = decltype((declval<Function>())(declval<T>()));

		template <class Mapper>
		Functor(const Mapper& identity, const typeof_f_applied_to<A>& _f_a)
		: mapper(identity), f_a(_f_a)
		{
		}

		template <class Mapper>
		Functor<Function,A,decltype((declval<Mapper>())(declval<B>()))> fmap(const Mapper& map) const
		{
				using B_i = decltype((declval<Mapper>())(declval<B>()));
				auto composite_mapper = [this, &map](const A& a)
					{
						return std::forward<B_i>(map(std::forward<B>(mapper(a))));
					};
				return Functor<Function,A,B_i>(composite_mapper, f_a);
		}

		template <class B_i>
		Functor<Function,A,B_i> fmap(B_i(* const map)(const B&)) const
		{
				auto composite_mapper = [this, &map](const A& a)
					{
						return std::forward<B_i>(map(std::forward<B>(mapper(a))));
					};
				return Functor<Function,A,B_i>(composite_mapper, f_a);
		}

		typeof_f_applied_to<B> get() const
		{
				return Function::apply(mapper, f_a);
		}

		const std::function<B(A)> mapper;
		const typeof_f_applied_to<A>& f_a;
};

// Monad
template <class Function, class A, class B>
struct Monad : Functor<Function, A, Functor<Function, A, B>>
{
		Functor<Function, A, B> mjoin()
		{
				// TODO
		}
};

struct Vector
{
		template <class B> std::vector<B> operator()(B...) const;
		template <class B, class A>
		static std::vector<B> apply(const std::function<B(A)>& mapper, const std::vector<A>& source)
		{
				std::vector<B> target(source.size());
				std::transform(source.begin(), source.end(), target.begin(), mapper);
				return target;
		}
};

template <class A>
Functor<Vector,A,A> make_functor(const std::vector<A>& f_a)
{
		return Functor<Vector,A,A>([](A&& a) { return std::forward<A>(a); }, f_a);
}

double sqrt(const int& a)
{
		return std::sqrt(a);
}

void test(std::vector<int>& l)
{
		auto r = make_functor(l)
//			.fmap([](int x)
//			{
//				std::vector<int> v(x);
//				std::iota(v.begin(), v.end(), 1);
//				return make_functor(v);
//			})
//			.mjoin()
			.fmap(&sqrt)
			.fmap([](const double& x)
			{
				return std::forward<std::string>(std::to_string(x));
			})
			.fmap([](const std::string& x)
			{
				return std::forward<float>(std::stof(x)/2);
			})
			.get();

		std::for_each(r.begin(), r.end(), [](float s)
		{
			std::cout << s << std::endl;
		});
}

int main()
{
		std::vector<int> l(5);
		std::iota(l.begin(), l.end(), 1);
		test(l);
		return 0;
}
<commit_msg>redefined names<commit_after>#include <functional>
#include <vector>
#include <algorithm>
#include <numeric>
#include <iostream>
#include <type_traits>
#include <cmath>

using std::declval;

// fmap :: Functor f => (a -> b) -> f a -> f b
// takes a function that maps a -> b
// takes a f(a) type instance
// returns a f(b) type instance
template <class Functor, class A, class B>
struct fmap
{
		template <class T>
		using typeof_f_of = decltype((declval<Functor>())(declval<T>()));

		fmap(std::function<B(A)>&& map, const typeof_f_of<A>& _f_a) : mapper(map), f_a(_f_a)
		{
		}

		template <class Map>
		fmap<Functor,A,decltype((declval<Map>())(declval<B>()))> composite(const Map& map) const
		{
				using C = decltype((declval<Map>())(declval<B>()));
				auto composite_mapper = [this, &map](const A& a)
					{
						return std::forward<C>(map(std::forward<B>(mapper(a))));
					};
				return fmap<Functor,A,C>(composite_mapper, f_a);
		}

		template <class C>
		fmap<Functor,A,C> composite(C(* const map)(const B&)) const
		{
				auto composite_mapper = [this, &map](const A& a)
					{
						return std::forward<C>(map(std::forward<B>(mapper(a))));
					};
				return fmap<Functor,A,C>(composite_mapper, f_a);
		}

		typeof_f_of<B> yield() const
		{
				return Functor::apply(mapper, f_a);
		}

		const std::function<B(A)> mapper;
		const typeof_f_of<A>& f_a;
};

// Monad
template <class Functor, class A, class B>
struct fmap<Functor, A, fmap<Functor, A, B>>
{
		template <class T>
		using typeof_f_of = decltype((declval<Functor>())(declval<T>()));

		fmap(std::function<B(A)>&& map, const typeof_f_of<A>& _f_a) : mapper(map), f_a(_f_a)
		{
				std::cout << "Monad constructed" << std::endl;
		}

		fmap<Functor, A, B> mjoin()
		{
				// TODO
				typeof_f_of<fmap<Functor, A, B>> f_f_a;
		}

		const std::function<fmap<Functor, A, B>(A)> mapper;
		const typeof_f_of<A>& f_a;
};

struct Vector
{
		template <class B> std::vector<B> operator()(B...) const;
		template <class B, class A>
		static std::vector<B> apply(const std::function<B(A)>& mapper, const std::vector<A>& source)
		{
				std::vector<B> target(source.size());
				std::transform(source.begin(), source.end(), target.begin(), mapper);
				return target;
		}
		template <class A>
		static fmap<Vector,A,A> as_functor(const std::vector<A>& f_a)
		{
				auto identity_map = [](A&& a) { return std::forward<A>(a); };
				return fmap<Vector,A,A>(identity_map, f_a);
		}
};

double sqrt(const int& a)
{
		return std::sqrt(a);
}

void test(const std::vector<int>& l)
{
		auto r = Vector::as_functor(l)
//			.composite([](int x)
//			{
//				std::vector<int> v(x);
//				std::iota(v.begin(), v.end(), 1);
//				return v;
//				return Vector::as_functor(v);
//			})
//			.mjoin()
			.composite(&sqrt)
			.composite([](double x)
			{
				return std::to_string(x);
			})
			.composite([](const std::string& x)
			{
				return std::stof(x)/2;
			})
			.yield();

		std::for_each(r.begin(), r.end(), [](float s)
			{
				std::cout << s << std::endl;
			});

//		std::for_each(r.begin(), r.end(), [](std::vector<int>& v)
//		{
//			std::for_each(v.begin(), v.end(), [](int s)
//			{
//				std::cout << s << " ";
//			});
//			std::cout << std::endl;
//		});
}

int main()
{
		std::vector<int> l(10);
		std::iota(l.begin(), l.end(), 1);
		test(l);
		return 0;
}
<|endoftext|>


<commit_before>//
// Created by salmon on 17-7-18.
//

#include "EBMesh.h"
#include <simpla/geometry/GeoObjectOCC.h>
#include "simpla/engine/Mesh.h"
#include "simpla/geometry/BoxUtilities.h"
#include "simpla/geometry/GeoObject.h"
namespace simpla {
namespace mesh {
namespace detail {
struct EntityIdHasher {
    size_t operator()(const EntityId &key) const { return static_cast<size_t>(key.v); }
};

std::shared_ptr<UnorderedRange<EntityId>> make_range(tbb::concurrent_unordered_set<EntityId, EntityIdHasher> const &t) {
    auto res = std::make_shared<UnorderedRange<EntityId>>();
    res->reset(t.size(), nullptr);
    std::copy(t.begin(), t.end(), res->get());
    return res;
}
void UpdateRanges(engine::MeshBase *m_host_, std::string const &prefix, Array<int, ZSFC<3>> const &vertex_tags) {
    /**
    *\verbatim
    *                ^s (dl)
    *               /
    *   (dz) t     /
    *        ^    /
    *        |  110-------------111
    *        |  /|              /|
    *        | / |             / |
    *        |/  |            /  |
    *       100--|----------101  |
    *        | m |           |   |
    *        |  010----------|--011
    *        |  /            |  /
    *        | /             | /
    *        |/              |/
    *       000-------------001---> r (dr)
    *
    *\endverbatim
    */

    //    Array<int, ZSFC<3>> volume_tags{nullptr, m_host_->IndexBox(0b111)};
    //
    //    volume_tags = ((vertex_tags(IdxShift{0, 0, 0})) << 0) |  //
    //                  ((vertex_tags(IdxShift{1, 0, 0})) << 1) |  //
    //                  ((vertex_tags(IdxShift{0, 1, 0})) << 2) |  //
    //                  ((vertex_tags(IdxShift{1, 1, 0})) << 3) |  //
    //                  ((vertex_tags(IdxShift{0, 0, 1})) << 4) |  //
    //                  ((vertex_tags(IdxShift{1, 0, 1})) << 5) |  //
    //                  ((vertex_tags(IdxShift{0, 1, 1})) << 6) |  //
    //                  ((vertex_tags(IdxShift{1, 1, 1})) << 7);

    tbb::concurrent_unordered_set<EntityId, detail::EntityIdHasher> VERTEX_body;
    tbb::concurrent_unordered_set<EntityId, detail::EntityIdHasher> EDGE_body;
    tbb::concurrent_unordered_set<EntityId, detail::EntityIdHasher> FACE_body;
    tbb::concurrent_unordered_set<EntityId, detail::EntityIdHasher> VOLUME_body;

    tbb::concurrent_unordered_set<EntityId, detail::EntityIdHasher> VERTEX_boundary;
    tbb::concurrent_unordered_set<EntityId, detail::EntityIdHasher> EDGE_boundary;
    tbb::concurrent_unordered_set<EntityId, detail::EntityIdHasher> FACE_boundary;
    tbb::concurrent_unordered_set<EntityId, detail::EntityIdHasher> EDGE_CUT_boundary;
    tbb::concurrent_unordered_set<EntityId, detail::EntityIdHasher> FACE_CUT_boundary;
    tbb::concurrent_unordered_set<EntityId, detail::EntityIdHasher> VOLUME_boundary;

    static const int b0 = 0b000;
    static const int b1 = 0b001;
    static const int b2 = 0b010;
    static const int b3 = 0b011;
    static const int b4 = 0b100;
    static const int b5 = 0b101;
    static const int b6 = 0b110;
    static const int b7 = 0b111;
    static const EntityId t0 = {0, 0, 0, 0b000};
    static const EntityId t1 = {0, 0, 0, 0b001};
    static const EntityId t2 = {0, 0, 0, 0b010};
    static const EntityId t3 = {0, 0, 0, 0b011};
    static const EntityId t4 = {0, 0, 0, 0b100};
    static const EntityId t5 = {0, 0, 0, 0b101};
    static const EntityId t6 = {0, 0, 0, 0b110};
    static const EntityId t7 = {0, 0, 0, 0b111};

    static const EntityId s0 = {0, 0, 0, 0};
    static const EntityId s1 = {1, 0, 0, 0};
    static const EntityId s2 = {0, 1, 0, 0};
    static const EntityId s3 = {1, 1, 0, 0};
    static const EntityId s4 = {0, 0, 1, 0};
    static const EntityId s5 = {1, 0, 1, 0};
    static const EntityId s6 = {0, 1, 1, 0};
    static const EntityId s7 = {1, 1, 1, 0};

    ZSFC<3>(geometry::Expand(m_host_->IndexBox(0b111), index_tuple{1, 1, 1}))
        .Foreach(  //
            [&](auto I, auto J, auto K) {

                EntityId s = {static_cast<int16_t>(I), static_cast<int16_t>(J), static_cast<int16_t>(K), 0};

                int tag = ((vertex_tags(I + 0, J + 0, K + 0)) << 0) |  //
                          ((vertex_tags(I + 1, J + 0, K + 0)) << 1) |  //
                          ((vertex_tags(I + 0, J + 1, K + 0)) << 2) |  //
                          ((vertex_tags(I + 1, J + 1, K + 0)) << 3) |  //
                          ((vertex_tags(I + 0, J + 0, K + 1)) << 4) |  //
                          ((vertex_tags(I + 1, J + 0, K + 1)) << 5) |  //
                          ((vertex_tags(I + 0, J + 1, K + 1)) << 6) |  //
                          ((vertex_tags(I + 1, J + 1, K + 1)) << 7);

                //
                if (tag == 0b11111111) {
                    /**
                     *\verbatim
                     *                ^s (dl)
                     *               /
                     *   (dz) t     /
                     *        ^    /
                     *        |   6 --------------7
                     *        |  /|              /|
                     *        | / |             / |
                     *        |/  |            /  |
                     *        4 --|---------- 5   |
                     *        | m |           |   |
                     *        |   2 ----------|-- 3
                     *        |  /            |  /
                     *        | /             | /
                     *        |/              |/
                     *        0 ------------- 1---> r (dr)
                     *
                     *\endverbatim
                     */

                    VERTEX_body.insert(s0 + s);
                    VERTEX_body.insert(s1 + s);
                    VERTEX_body.insert(s2 + s);
                    VERTEX_body.insert(s3 + s);
                    VERTEX_body.insert(s4 + s);
                    VERTEX_body.insert(s5 + s);
                    VERTEX_body.insert(s6 + s);
                    VERTEX_body.insert(s7 + s);

                    EDGE_body.insert((t1 | s0) + s);
                    EDGE_body.insert((t1 | s2) + s);
                    EDGE_body.insert((t1 | s4) + s);
                    EDGE_body.insert((t1 | s6) + s);

                    EDGE_body.insert((t2 | s0) + s);
                    EDGE_body.insert((t2 | s1) + s);
                    EDGE_body.insert((t2 | s4) + s);
                    EDGE_body.insert((t2 | s5) + s);

                    EDGE_body.insert((t4 | s0) + s);
                    EDGE_body.insert((t4 | s1) + s);
                    EDGE_body.insert((t4 | s2) + s);
                    EDGE_body.insert((t4 | s3) + s);

                    FACE_body.insert((t3 | s0) + s);
                    FACE_body.insert((t5 | s0) + s);
                    FACE_body.insert((t6 | s0) + s);

                    FACE_body.insert((t6 | s1) + s);
                    FACE_body.insert((t5 | s2) + s);
                    FACE_body.insert((t3 | s4) + s);

                    VOLUME_body.insert(t7 + s);

                } else if (tag > 0 && tag < 0b11111111) {
                    if ((tag & b0) != 0) { VERTEX_boundary.insert(s0 + s); }
                    if ((tag & b1) != 0) { VERTEX_boundary.insert(s1 + s); }
                    if ((tag & b2) != 0) { VERTEX_boundary.insert(s2 + s); }
                    if ((tag & b3) != 0) { VERTEX_boundary.insert(s3 + s); }
                    if ((tag & b4) != 0) { VERTEX_boundary.insert(s4 + s); }
                    if ((tag & b5) != 0) { VERTEX_boundary.insert(s5 + s); }
                    if ((tag & b6) != 0) { VERTEX_boundary.insert(s6 + s); }
                    if ((tag & b7) != 0) { VERTEX_boundary.insert(s7 + s); }

#define CHECK_TAG(_TAG_) if ((tag & _TAG_) == _TAG_)
                    CHECK_TAG(0b00000011) { EDGE_boundary.insert(t1 | s0 + s); }
                    CHECK_TAG(0b00001100) { EDGE_boundary.insert(t1 | s2 + s); }
                    CHECK_TAG(0b00110000) { EDGE_boundary.insert(t1 | s4 + s); }
                    CHECK_TAG(0b11000000) { EDGE_boundary.insert(t1 | s6 + s); }
                    CHECK_TAG(0b00000101) { EDGE_boundary.insert(t2 | s0 + s); }
                    CHECK_TAG(0b00001010) { EDGE_boundary.insert(t2 | s1 + s); }
                    CHECK_TAG(0b01010000) { EDGE_boundary.insert(t2 | s4 + s); }
                    CHECK_TAG(0b10100000) { EDGE_boundary.insert(t2 | s5 + s); }
                    CHECK_TAG(0b00010001) { EDGE_boundary.insert(t4 | s0 + s); }
                    CHECK_TAG(0b00100010) { EDGE_boundary.insert(t4 | s1 + s); }
                    CHECK_TAG(0b01000100) { EDGE_boundary.insert(t4 | s2 + s); }
                    CHECK_TAG(0b10001000) { EDGE_boundary.insert(t4 | s3 + s); }

                    CHECK_TAG(0b00000011) { FACE_boundary.insert(t3 | s0 + s); }
                    CHECK_TAG(0b00000011) { FACE_boundary.insert(t5 | s0 + s); }
                    CHECK_TAG(0b00000011) { FACE_boundary.insert(t6 | s0 + s); }
                    CHECK_TAG(0b00000011) { FACE_boundary.insert(t6 | s1 + s); }
                    CHECK_TAG(0b00000011) { FACE_boundary.insert(t5 | s2 + s); }
                    CHECK_TAG(0b00000011) { FACE_boundary.insert(t3 | s4 + s); }
#undef CHECK_TAG
                    VOLUME_boundary.insert(t7 + s);
                }
            });

    CHECK(VOLUME_body.size());

    m_host_->GetRange(prefix + "_BODY_0").append(make_range(VERTEX_body));
    m_host_->GetRange(prefix + "_BODY_1").append(make_range(EDGE_body));
    m_host_->GetRange(prefix + "_BODY_2").append(make_range(FACE_body));
    m_host_->GetRange(prefix + "_BODY_3").append(make_range(VOLUME_body));

    m_host_->GetRange(prefix + "_BOUNDARY_0").append(make_range(VERTEX_boundary));
    m_host_->GetRange(prefix + "_BOUNDARY_3").append(make_range(VOLUME_boundary));

    m_host_->GetRange(prefix + "_BOUNDARY_1").append(make_range(EDGE_boundary));
    m_host_->GetRange(prefix + "_BOUNDARY_2").append(make_range(FACE_boundary));

    m_host_->GetRange(prefix + "_CUT_BOUNDARY_1").append(make_range(EDGE_CUT_boundary));
    m_host_->GetRange(prefix + "_CUT_BOUNDARY_2").append(make_range(FACE_CUT_boundary));
}

void TagCutVertices(engine::MeshBase const *m_host_, Array<int, ZSFC<3>> *vertex_tags, geometry::GeoObjectOCC const *g){

};

void CreateEBMesh(engine::MeshBase *m_host_, std::string const &prefix, geometry::GeoObject const *g) {
    Array<int, ZSFC<3>> vertex_tags{
        nullptr, geometry::Expand(std::get<1>(m_host_->GetMesh()->CheckOverlap(g)), index_tuple{3, 3, 3})};

    if (g->isA(typeid(geometry::GeoObjectOCC))) {
        TagCutVertices(m_host_, &vertex_tags, dynamic_cast<geometry::GeoObjectOCC const *>(g));
    } else {
        auto const *chart = m_host_->GetChart();
        vertex_tags = [&](index_type x, index_type y, index_type z) {
            return g->CheckInside(
                       chart->xyz(point_type{static_cast<Real>(x), static_cast<Real>(y), static_cast<Real>(z)}))
                       ? 1
                       : 0;
        };
    }

    UpdateRanges(m_host_, prefix, vertex_tags);
}

}  // namespace detail {
}  // namespace mesh {
}  // namespace simpla{
<commit_msg>snapshot<commit_after>//
// Created by salmon on 17-7-18.
//

#include "EBMesh.h"
#include <simpla/geometry/GeoObjectOCC.h>
#include "simpla/engine/Mesh.h"
#include "simpla/geometry/BoxUtilities.h"
#include "simpla/geometry/GeoObject.h"
namespace simpla {
namespace mesh {
namespace detail {
struct EntityIdHasher {
    size_t operator()(const EntityId &key) const { return static_cast<size_t>(key.v); }
};

std::shared_ptr<UnorderedRange<EntityId>> make_range(tbb::concurrent_unordered_set<EntityId, EntityIdHasher> const &t) {
    auto res = std::make_shared<UnorderedRange<EntityId>>();
    res->reset(t.size(), nullptr);
    std::copy(t.begin(), t.end(), res->get());
    return res;
}
void UpdateRanges(engine::MeshBase *m_host_, std::string const &prefix, Array<int, ZSFC<3>> const &vertex_tags) {
    /**
    *\verbatim
    *                ^s (dl)
    *               /
    *   (dz) t     /
    *        ^    /
    *        |  110-------------111
    *        |  /|              /|
    *        | / |             / |
    *        |/  |            /  |
    *       100--|----------101  |
    *        | m |           |   |
    *        |  010----------|--011
    *        |  /            |  /
    *        | /             | /
    *        |/              |/
    *       000-------------001---> r (dr)
    *
    *\endverbatim
    */

    //    Array<int, ZSFC<3>> volume_tags{nullptr, m_host_->IndexBox(0b111)};
    //
    //    volume_tags = ((vertex_tags(IdxShift{0, 0, 0})) << 0) |  //
    //                  ((vertex_tags(IdxShift{1, 0, 0})) << 1) |  //
    //                  ((vertex_tags(IdxShift{0, 1, 0})) << 2) |  //
    //                  ((vertex_tags(IdxShift{1, 1, 0})) << 3) |  //
    //                  ((vertex_tags(IdxShift{0, 0, 1})) << 4) |  //
    //                  ((vertex_tags(IdxShift{1, 0, 1})) << 5) |  //
    //                  ((vertex_tags(IdxShift{0, 1, 1})) << 6) |  //
    //                  ((vertex_tags(IdxShift{1, 1, 1})) << 7);

    tbb::concurrent_unordered_set<EntityId, detail::EntityIdHasher> VERTEX_body;
    tbb::concurrent_unordered_set<EntityId, detail::EntityIdHasher> EDGE_body;
    tbb::concurrent_unordered_set<EntityId, detail::EntityIdHasher> FACE_body;
    tbb::concurrent_unordered_set<EntityId, detail::EntityIdHasher> VOLUME_body;

    tbb::concurrent_unordered_set<EntityId, detail::EntityIdHasher> VERTEX_boundary;
    tbb::concurrent_unordered_set<EntityId, detail::EntityIdHasher> EDGE_boundary;
    tbb::concurrent_unordered_set<EntityId, detail::EntityIdHasher> FACE_boundary;
    tbb::concurrent_unordered_set<EntityId, detail::EntityIdHasher> EDGE_CUT_boundary;
    tbb::concurrent_unordered_set<EntityId, detail::EntityIdHasher> FACE_CUT_boundary;
    tbb::concurrent_unordered_set<EntityId, detail::EntityIdHasher> VOLUME_boundary;

    static const int b0 = 0b000;
    static const int b1 = 0b001;
    static const int b2 = 0b010;
    static const int b3 = 0b011;
    static const int b4 = 0b100;
    static const int b5 = 0b101;
    static const int b6 = 0b110;
    static const int b7 = 0b111;
    static const EntityId t0 = {0, 0, 0, 0b000};
    static const EntityId t1 = {0, 0, 0, 0b001};
    static const EntityId t2 = {0, 0, 0, 0b010};
    static const EntityId t3 = {0, 0, 0, 0b011};
    static const EntityId t4 = {0, 0, 0, 0b100};
    static const EntityId t5 = {0, 0, 0, 0b101};
    static const EntityId t6 = {0, 0, 0, 0b110};
    static const EntityId t7 = {0, 0, 0, 0b111};

    static const EntityId s0 = {0, 0, 0, 0};
    static const EntityId s1 = {1, 0, 0, 0};
    static const EntityId s2 = {0, 1, 0, 0};
    static const EntityId s3 = {1, 1, 0, 0};
    static const EntityId s4 = {0, 0, 1, 0};
    static const EntityId s5 = {1, 0, 1, 0};
    static const EntityId s6 = {0, 1, 1, 0};
    static const EntityId s7 = {1, 1, 1, 0};

    ZSFC<3>(geometry::Expand(m_host_->IndexBox(0b111), index_tuple{1, 1, 1}))
        .Foreach(  //
            [&](auto I, auto J, auto K) {

                EntityId s = {static_cast<int16_t>(I), static_cast<int16_t>(J), static_cast<int16_t>(K), 0};

                int tag = ((vertex_tags(I + 0, J + 0, K + 0)) << 0) |  //
                          ((vertex_tags(I + 1, J + 0, K + 0)) << 1) |  //
                          ((vertex_tags(I + 0, J + 1, K + 0)) << 2) |  //
                          ((vertex_tags(I + 1, J + 1, K + 0)) << 3) |  //
                          ((vertex_tags(I + 0, J + 0, K + 1)) << 4) |  //
                          ((vertex_tags(I + 1, J + 0, K + 1)) << 5) |  //
                          ((vertex_tags(I + 0, J + 1, K + 1)) << 6) |  //
                          ((vertex_tags(I + 1, J + 1, K + 1)) << 7);

                //
                if (tag == 0b11111111) {
                    /**
                     *\verbatim
                     *                ^s (dl)
                     *               /
                     *   (dz) t     /
                     *        ^    /
                     *        |   6 --------------7
                     *        |  /|              /|
                     *        | / |             / |
                     *        |/  |            /  |
                     *        4 --|---------- 5   |
                     *        | m |           |   |
                     *        |   2 ----------|-- 3
                     *        |  /            |  /
                     *        | /             | /
                     *        |/              |/
                     *        0 ------------- 1---> r (dr)
                     *
                     *\endverbatim
                     */

                    VERTEX_body.insert(s0 + s);
                    VERTEX_body.insert(s1 + s);
                    VERTEX_body.insert(s2 + s);
                    VERTEX_body.insert(s3 + s);
                    VERTEX_body.insert(s4 + s);
                    VERTEX_body.insert(s5 + s);
                    VERTEX_body.insert(s6 + s);
                    VERTEX_body.insert(s7 + s);

                    EDGE_body.insert((t1 | s0) + s);
                    EDGE_body.insert((t1 | s2) + s);
                    EDGE_body.insert((t1 | s4) + s);
                    EDGE_body.insert((t1 | s6) + s);

                    EDGE_body.insert((t2 | s0) + s);
                    EDGE_body.insert((t2 | s1) + s);
                    EDGE_body.insert((t2 | s4) + s);
                    EDGE_body.insert((t2 | s5) + s);

                    EDGE_body.insert((t4 | s0) + s);
                    EDGE_body.insert((t4 | s1) + s);
                    EDGE_body.insert((t4 | s2) + s);
                    EDGE_body.insert((t4 | s3) + s);

                    FACE_body.insert((t3 | s0) + s);
                    FACE_body.insert((t5 | s0) + s);
                    FACE_body.insert((t6 | s0) + s);

                    FACE_body.insert((t6 | s1) + s);
                    FACE_body.insert((t5 | s2) + s);
                    FACE_body.insert((t3 | s4) + s);

                    VOLUME_body.insert(t7 + s);

                } else if (tag > 0 && tag < 0b11111111) {
                    if ((tag & b0) != 0) { VERTEX_boundary.insert(s0 + s); }
                    if ((tag & b1) != 0) { VERTEX_boundary.insert(s1 + s); }
                    if ((tag & b2) != 0) { VERTEX_boundary.insert(s2 + s); }
                    if ((tag & b3) != 0) { VERTEX_boundary.insert(s3 + s); }
                    if ((tag & b4) != 0) { VERTEX_boundary.insert(s4 + s); }
                    if ((tag & b5) != 0) { VERTEX_boundary.insert(s5 + s); }
                    if ((tag & b6) != 0) { VERTEX_boundary.insert(s6 + s); }
                    if ((tag & b7) != 0) { VERTEX_boundary.insert(s7 + s); }

#define CHECK_TAG(_TAG_) if ((tag & _TAG_) == _TAG_)
                    CHECK_TAG(0b00000011) { EDGE_boundary.insert(t1 | s0 + s); }
                    CHECK_TAG(0b00001100) { EDGE_boundary.insert(t1 | s2 + s); }
                    CHECK_TAG(0b00110000) { EDGE_boundary.insert(t1 | s4 + s); }
                    CHECK_TAG(0b11000000) { EDGE_boundary.insert(t1 | s6 + s); }
                    CHECK_TAG(0b00000101) { EDGE_boundary.insert(t2 | s0 + s); }
                    CHECK_TAG(0b00001010) { EDGE_boundary.insert(t2 | s1 + s); }
                    CHECK_TAG(0b01010000) { EDGE_boundary.insert(t2 | s4 + s); }
                    CHECK_TAG(0b10100000) { EDGE_boundary.insert(t2 | s5 + s); }
                    CHECK_TAG(0b00010001) { EDGE_boundary.insert(t4 | s0 + s); }
                    CHECK_TAG(0b00100010) { EDGE_boundary.insert(t4 | s1 + s); }
                    CHECK_TAG(0b01000100) { EDGE_boundary.insert(t4 | s2 + s); }
                    CHECK_TAG(0b10001000) { EDGE_boundary.insert(t4 | s3 + s); }

                    CHECK_TAG(0b00000011) { FACE_boundary.insert(t3 | s0 + s); }
                    CHECK_TAG(0b00000011) { FACE_boundary.insert(t5 | s0 + s); }
                    CHECK_TAG(0b00000011) { FACE_boundary.insert(t6 | s0 + s); }
                    CHECK_TAG(0b00000011) { FACE_boundary.insert(t6 | s1 + s); }
                    CHECK_TAG(0b00000011) { FACE_boundary.insert(t5 | s2 + s); }
                    CHECK_TAG(0b00000011) { FACE_boundary.insert(t3 | s4 + s); }
#undef CHECK_TAG
                    VOLUME_boundary.insert(t7 + s);
                }
            });

    CHECK(VOLUME_body.size());

    m_host_->GetRange(prefix + "_BODY_0").append(make_range(VERTEX_body));
    m_host_->GetRange(prefix + "_BODY_1").append(make_range(EDGE_body));
    m_host_->GetRange(prefix + "_BODY_2").append(make_range(FACE_body));
    m_host_->GetRange(prefix + "_BODY_3").append(make_range(VOLUME_body));

    m_host_->GetRange(prefix + "_BOUNDARY_0").append(make_range(VERTEX_boundary));
    m_host_->GetRange(prefix + "_BOUNDARY_3").append(make_range(VOLUME_boundary));

    m_host_->GetRange(prefix + "_BOUNDARY_1").append(make_range(EDGE_boundary));
    m_host_->GetRange(prefix + "_BOUNDARY_2").append(make_range(FACE_boundary));

    m_host_->GetRange(prefix + "_CUT_BOUNDARY_1").append(make_range(EDGE_CUT_boundary));
    m_host_->GetRange(prefix + "_CUT_BOUNDARY_2").append(make_range(FACE_CUT_boundary));
}

void TagCutVertices(engine::MeshBase const *m_host_, Array<int, ZSFC<3>> *vertex_tags, geometry::GeoObjectOCC const *g){

};

void CreateEBMesh(engine::MeshBase *m_host_, std::string const &prefix, geometry::GeoObject const *g) {
    auto idx_box = geometry::Expand(std::get<1>(m_host_->GetMesh()->CheckOverlap(g)), index_tuple{3, 3, 3});
    Array<int, ZSFC<3>> vertex_tags{nullptr, idx_box};

    std::vector<Real> intersection_points;
    for (int dir = 0; dir < 3; ++dir) {
        index_tuple i0 = std::get<0>(idx_box);

        i0[dir] = 0;
        auto c = m_host_->GetMesh()->GetAxisCurve(i0, 0);
    }

    geometry::curve_intersection_surface(g, c, &intersection_points);

    if (g->isA(typeid(geometry::GeoObjectOCC))) {
        TagCutVertices(m_host_, &vertex_tags, dynamic_cast<geometry::GeoObjectOCC const *>(g));
    } else {
        auto const *chart = m_host_->GetChart();
        vertex_tags = [&](index_type x, index_type y, index_type z) {
            return g->CheckInside(
                       chart->xyz(point_type{static_cast<Real>(x), static_cast<Real>(y), static_cast<Real>(z)}))
                       ? 1
                       : 0;
        };
    }

    UpdateRanges(m_host_, prefix, vertex_tags);
}

}  // namespace detail {
}  // namespace mesh {
}  // namespace simpla{
<|endoftext|>


<commit_before>#include "../Include/CGotoSceneVisitor.h"
#include "../Include/CSceneNode.h"
#include "../Include/CSequenceNode.h"

#include "cocos2d.h"

using namespace cocos2d;

namespace LM
{

CGotoSceneVisitor::CGotoSceneVisitor(const std::string& a_sSceneID) :
    m_sSceneID(a_sSceneID)
{

}

Result CGotoSceneVisitor::ProcessNodeTopDown(CNode* a_pNode)
{
  CSceneNode* pSceneNode = dynamic_cast<CSceneNode*>(a_pNode);
  if (pSceneNode)
  {
    if (pSceneNode->GetSceneID() == m_sSceneID)
    {
		CSequenceNode* pSequence = dynamic_cast<CSequenceNode*>(pSceneNode->GetParent());
		pSequence->SetCurrentNode(pSceneNode);
      Scene* pNewScene = pSceneNode->CreateScene();
      pSceneNode->init();

      Director::getInstance()->replaceScene(TransitionPageTurn::create(1.5f, pNewScene, false));
      return RESULT_PRUNE;
    }
  }
  return RESULT_CONTINUE;
}

} // namespace LM
<commit_msg>changed animation in CGotoSceneVisitor<commit_after>#include "../Include/CGotoSceneVisitor.h"
#include "../Include/CSceneNode.h"
#include "../Include/CSequenceNode.h"

#include "cocos2d.h"

using namespace cocos2d;

namespace LM
{

CGotoSceneVisitor::CGotoSceneVisitor(const std::string& a_sSceneID) :
    m_sSceneID(a_sSceneID)
{

}

Result CGotoSceneVisitor::ProcessNodeTopDown(CNode* a_pNode)
{
  CSceneNode* pSceneNode = dynamic_cast<CSceneNode*>(a_pNode);
  if (pSceneNode)
  {
    if (pSceneNode->GetSceneID() == m_sSceneID)
    {
		CSequenceNode* pSequence = dynamic_cast<CSequenceNode*>(pSceneNode->GetParent());
		pSequence->SetCurrentNode(pSceneNode);
      Scene* pNewScene = pSceneNode->CreateScene();
      pSceneNode->init();

      Director::getInstance()->replaceScene(TransitionShrinkGrow::create(1.5f, pNewScene));
      return RESULT_PRUNE;
    }
  }
  return RESULT_CONTINUE;
}

} // namespace LM
<|endoftext|>


<commit_before>//
//  snowcrash.cc
//  snowcrash
//
//  Created by Zdenek Nemec on 4/27/13.
//  Copyright (c) 2013 Apiary Inc. All rights reserved.
//

#include <iostream>
#include <sstream>
#include <fstream>
#include "snowcrash.h"
#include "SerializeJSON.h"
#include "SerializeYAML.h"
#include "cmdline.h"

using snowcrash::SourceAnnotation;
using snowcrash::Error;

static const std::string OutputArgument = "output";
static const std::string FormatArgument = "format";
static const std::string RenderArgument = "render";
static const std::string ValidateArgument = "validate";

/// \enum Snow Crash AST output format.
enum SerializationFormat {
    YAMLSerializationFormat,
    JSONSerializationFormat
};

/// \brief Print Markdown source annotation.
/// \param prefix A string prefix for the annotation
/// \param annotation An annotation to print
void PrintAnnotation(const std::string& prefix, const snowcrash::SourceAnnotation& annotation)
{
    std::cerr << prefix;

    if (annotation.code != SourceAnnotation::OK) {
        std::cerr << " (" << annotation.code << ") ";
    }

    if (!annotation.message.empty()) {
        std::cerr << " " << annotation.message;
    }

    if (!annotation.location.empty()) {
        for (snowcrash::SourceDataBlock::const_iterator it = annotation.location.begin(); it != annotation.location.end(); ++it) {
            std::cerr << ((it == annotation.location.begin()) ? " :" : ";");
            std::cerr << it->location << ":" << it->length;
        }
    }

    std::cerr << std::endl;
}

/// \brief Print parser result to stderr.
/// \param result A parser result to print
void PrintResult(const snowcrash::Result& result)
{
    std::cerr << std::endl;

    if (result.error.code == Error::OK) {
        std::cerr << "OK.\n";
    }
    else {
        PrintAnnotation("error:", result.error);
    }

    for (snowcrash::Warnings::const_iterator it = result.warnings.begin(); it != result.warnings.end(); ++it) {
        PrintAnnotation("warning:", *it);
    }
}

int main(int argc, const char *argv[])
{
    cmdline::parser argumentParser;

    argumentParser.set_program_name("snowcrash");
    std::stringstream ss;
    ss << "<input file>\n\n";
    ss << "API Blueprint Parser\n";
    ss << "If called without <input file>, 'snowcrash' will listen on stdin.\n";
    argumentParser.footer(ss.str());

    argumentParser.add<std::string>(OutputArgument, 'o', "save output AST into file", false);
    argumentParser.add<std::string>(FormatArgument, 'f', "output AST format", false, "yaml", cmdline::oneof<std::string>("yaml", "json"));
    // TODO: argumentParser.add("render", 'r', "render markdown descriptions");
    argumentParser.add("help", 'h', "display this help message");
    argumentParser.add(ValidateArgument, 'v', "validate input only, do not print AST");

    argumentParser.parse_check(argc, argv);
    if (argumentParser.rest().size() > 1) {
        std::cerr << "one input file expected, got " << argumentParser.rest().size() << std::endl;
        exit(EXIT_FAILURE);
    }

    // Input
    std::stringstream inputStream;
    if (argumentParser.rest().empty()) {
        // Read stdin
        inputStream << std::cin.rdbuf();
    }
    else {
        // Read from file
        std::ifstream inputFileStream;
        std::string inputFileName = argumentParser.rest().front();
        inputFileStream.open(inputFileName.c_str());
        if (!inputFileStream.is_open()) {
            std::cerr << "fatal: unable to open input file '" << inputFileName << "'\n";
            exit(EXIT_FAILURE);
        }

        inputStream << inputFileStream.rdbuf();
        inputFileStream.close();
    }

    // Parse
    snowcrash::BlueprintParserOptions options = 0;  // Or snowcrash::RequireBlueprintNameOption
    snowcrash::Result result;
    snowcrash::Blueprint blueprint;
    snowcrash::parse(inputStream.str(), options, result, blueprint);

    // Output
    if (!argumentParser.exist(ValidateArgument)) {

        std::stringstream outputStream;

        if (argumentParser.get<std::string>(FormatArgument) == "json") {
            SerializeJSON(blueprint, outputStream);
        }
        else if (argumentParser.get<std::string>(FormatArgument) == "yaml") {
            SerializeYAML(blueprint, outputStream);
        }

        std::string outputFileName = argumentParser.get<std::string>(OutputArgument);
        if (!outputFileName.empty()) {
            // Serialize to file
            std::ofstream outputFileStream;
            outputFileStream.open(outputFileName.c_str());
            if (!outputFileStream.is_open()) {
                std::cerr << "fatal: unable to write to file '" <<  outputFileName << "'\n";
                exit(EXIT_FAILURE);
            }

            outputFileStream << outputStream.rdbuf();
            outputFileStream.close();
        }
        else {
            // Serialize to stdout
            std::cout << outputStream.rdbuf();
        }
    }

    // Result
    PrintResult(result);
    return result.error.code;
}
<commit_msg>Update snowcrash cli tool to use characters source maps<commit_after>//
//  snowcrash.cc
//  snowcrash
//
//  Created by Zdenek Nemec on 4/27/13.
//  Copyright (c) 2013 Apiary Inc. All rights reserved.
//

#include <iostream>
#include <sstream>
#include <fstream>
#include "snowcrash.h"
#include "SerializeJSON.h"
#include "SerializeYAML.h"
#include "cmdline.h"

using snowcrash::SourceAnnotation;
using snowcrash::Error;

static const std::string OutputArgument = "output";
static const std::string FormatArgument = "format";
static const std::string RenderArgument = "render";
static const std::string ValidateArgument = "validate";

/// \enum Snow Crash AST output format.
enum SerializationFormat {
    YAMLSerializationFormat,
    JSONSerializationFormat
};

/// \brief Print Markdown source annotation.
/// \param prefix A string prefix for the annotation
/// \param annotation An annotation to print
void PrintAnnotation(const std::string& prefix, const snowcrash::SourceAnnotation& annotation)
{
    std::cerr << prefix;

    if (annotation.code != SourceAnnotation::OK) {
        std::cerr << " (" << annotation.code << ") ";
    }

    if (!annotation.message.empty()) {
        std::cerr << " " << annotation.message;
    }

    if (!annotation.location.empty()) {
        for (snowcrash::SourceCharactersBlock::const_iterator it = annotation.location.begin();
             it != annotation.location.end();
             ++it) {
            std::cerr << ((it == annotation.location.begin()) ? " :" : ";");
            std::cerr << it->location << ":" << it->length;
        }
    }

    std::cerr << std::endl;
}

/// \brief Print parser result to stderr.
/// \param result A parser result to print
void PrintResult(const snowcrash::Result& result)
{
    std::cerr << std::endl;

    if (result.error.code == Error::OK) {
        std::cerr << "OK.\n";
    }
    else {
        PrintAnnotation("error:", result.error);
    }

    for (snowcrash::Warnings::const_iterator it = result.warnings.begin(); it != result.warnings.end(); ++it) {
        PrintAnnotation("warning:", *it);
    }
}

int main(int argc, const char *argv[])
{
    cmdline::parser argumentParser;

    argumentParser.set_program_name("snowcrash");
    std::stringstream ss;
    ss << "<input file>\n\n";
    ss << "API Blueprint Parser\n";
    ss << "If called without <input file>, 'snowcrash' will listen on stdin.\n";
    argumentParser.footer(ss.str());

    argumentParser.add<std::string>(OutputArgument, 'o', "save output AST into file", false);
    argumentParser.add<std::string>(FormatArgument, 'f', "output AST format", false, "yaml", cmdline::oneof<std::string>("yaml", "json"));
    // TODO: argumentParser.add("render", 'r', "render markdown descriptions");
    argumentParser.add("help", 'h', "display this help message");
    argumentParser.add(ValidateArgument, 'v', "validate input only, do not print AST");

    argumentParser.parse_check(argc, argv);
    if (argumentParser.rest().size() > 1) {
        std::cerr << "one input file expected, got " << argumentParser.rest().size() << std::endl;
        exit(EXIT_FAILURE);
    }

    // Input
    std::stringstream inputStream;
    if (argumentParser.rest().empty()) {
        // Read stdin
        inputStream << std::cin.rdbuf();
    }
    else {
        // Read from file
        std::ifstream inputFileStream;
        std::string inputFileName = argumentParser.rest().front();
        inputFileStream.open(inputFileName.c_str());
        if (!inputFileStream.is_open()) {
            std::cerr << "fatal: unable to open input file '" << inputFileName << "'\n";
            exit(EXIT_FAILURE);
        }

        inputStream << inputFileStream.rdbuf();
        inputFileStream.close();
    }

    // Parse
    snowcrash::BlueprintParserOptions options = 0;  // Or snowcrash::RequireBlueprintNameOption
    snowcrash::Result result;
    snowcrash::Blueprint blueprint;
    snowcrash::parse(inputStream.str(), options, result, blueprint);

    // Output
    if (!argumentParser.exist(ValidateArgument)) {

        std::stringstream outputStream;

        if (argumentParser.get<std::string>(FormatArgument) == "json") {
            SerializeJSON(blueprint, outputStream);
        }
        else if (argumentParser.get<std::string>(FormatArgument) == "yaml") {
            SerializeYAML(blueprint, outputStream);
        }

        std::string outputFileName = argumentParser.get<std::string>(OutputArgument);
        if (!outputFileName.empty()) {
            // Serialize to file
            std::ofstream outputFileStream;
            outputFileStream.open(outputFileName.c_str());
            if (!outputFileStream.is_open()) {
                std::cerr << "fatal: unable to write to file '" <<  outputFileName << "'\n";
                exit(EXIT_FAILURE);
            }

            outputFileStream << outputStream.rdbuf();
            outputFileStream.close();
        }
        else {
            // Serialize to stdout
            std::cout << outputStream.rdbuf();
        }
    }

    // Result
    PrintResult(result);
    return result.error.code;
}
<|endoftext|>


<commit_before>//
// Created by Mark van der Broek on 11/03/2017.
//

#include "solver.ih"

vector<int> Solver::costRemoval(Solution &solution, int q)
{
    // Customerlist to be deleted
    vector<int> orderedCustomers(solution.getCustomers().size());
    iota(begin(orderedCustomers), end(orderedCustomers), 0);

    vector<double> gains(solution.getCustomers().size());

    for (size_t customerIdx = 0; customerIdx != solution.getCustomers().size(); ++customerIdx)
    {
        gains[customerIdx] = computeRemovalGain(solution, customerIdx);

    }

    // Sort customers on descending gains
    sort(begin(orderedCustomers), end(orderedCustomers),
         [&](int lhs, int rhs)
         {
             return gains[lhs] > gains[rhs];
         });

    vector<int> customersToRemove{begin(orderedCustomers), begin(orderedCustomers) + q};
    removeCustomers(solution, customersToRemove);

    return customersToRemove;
}<commit_msg>Randomness costremoval implemented<commit_after>//
// Created by Mark van der Broek on 11/03/2017.
//

#include "solver.ih"

vector<int> Solver::costRemoval(Solution &solution, int q)
{
    // Customerlist to be deleted
    vector<int> orderedCustomers(solution.getCustomers().size());
    iota(begin(orderedCustomers), end(orderedCustomers), 0);

    vector<double> gains(solution.getCustomers().size());
    uniform_real_distribution<double> uni(0.8, 1.2);

    for (size_t customerIdx = 0; customerIdx != solution.getCustomers().size(); ++customerIdx)
    {
        gains[customerIdx] = uni(d_env->d_rng) * computeRemovalGain(solution, customerIdx);

    }

    // Sort customers on descending gains
    sort(begin(orderedCustomers), end(orderedCustomers),
         [&](int lhs, int rhs)
         {
             return gains[lhs] > gains[rhs];
         });

    vector<int> customersToRemove{begin(orderedCustomers), begin(orderedCustomers) + q};
    removeCustomers(solution, customersToRemove);

    return customersToRemove;
}<|endoftext|>


<commit_before>#include "mitkGeometry2DDataVtkMapper3D.h"

#include "PlaneGeometry.h"

#include "DataTree.h"
#include "mitkImageMapper2D.h"

#include "mitkSurfaceData.h"
#include "mitkGeometry2DDataToSurfaceDataFilter.h"

#include "vtkActor.h"
#include "vtkProperty.h"
#include "vtkTexture.h"
#include "vtkPlaneSource.h"
#include "vtkPolyDataMapper.h"
#include "vtkLookupTable.h"
//#include "vtkImageMapToWindowLevelColors";
#include "mitkColorProperty.h"
#include "mitkFloatProperty.h"
#include "mitkLevelWindowProperty.h"
#include "mitkSmartPointerProperty.h"
#include <vtkActor.h>
#include <vtkImageData.h>

#include "pic2vtk.h"

//##ModelId=3E691E09038E
mitk::Geometry2DDataVtkMapper3D::Geometry2DDataVtkMapper3D() : m_DataTreeIterator(NULL), m_LastTextureUpdateTime(0)
{
  m_VtkPlaneSource = vtkPlaneSource::New();

  m_VtkPolyDataMapper = vtkPolyDataMapper::New();
  //        m_VtkPolyDataMapper->SetInput(m_VtkPlaneSource->GetOutput());
  m_VtkPolyDataMapper->ImmediateModeRenderingOn();

  m_Actor = vtkActor::New();
  m_Actor->SetMapper(m_VtkPolyDataMapper);

  m_Prop3D = m_Actor;
		m_Prop3D->Register(NULL);

  m_VtkLookupTable = vtkLookupTable::New();
    m_VtkLookupTable->SetTableRange (-1024, 4096);
    m_VtkLookupTable->SetSaturationRange (0, 0);
    m_VtkLookupTable->SetHueRange (0, 0);
    m_VtkLookupTable->SetValueRange (0, 1);
    m_VtkLookupTable->Build ();

  m_VtkTexture = vtkTexture::New();
    m_VtkTexture->InterpolateOn();
    m_VtkTexture->SetLookupTable(m_VtkLookupTable);
    m_VtkTexture->MapColorScalarsThroughLookupTableOn();

    //    m_Actor->SetTexture(axialTexture);

    //  axialTexture->SetInput(axialSection->GetOutput());
    //  axialTexture->InterpolateOn();
    //  axialTexture->SetLookupTable (lut);
    //  axialTexture->MapColorScalarsThroughLookupTableOn();
    //m_VtkPlaneSource = vtkPlaneSource::New();
    //  m_VtkPlaneSource->SetXResolution(1);
    //  m_VtkPlaneSource->SetYResolution(1);
    //  m_VtkPlaneSource->SetOrigin(0.0, 0.0, slice);
    //  m_VtkPlaneSource->SetPoint1(xDim, 0.0, slice);
    //  m_VtkPlaneSource->SetPoint2(0.0, yDim, slice);
    //m_VtkPolyDataMapper = vtkPolyDataMapper::New();
    //  m_VtkPolyDataMapper->SetInput(m_VtkPlaneSource->GetOutput());
    //  m_VtkPolyDataMapper->ImmediateModeRenderingOn();
    //axial = vtkActor::New();
    //  axial->SetMapper(m_VtkPolyDataMapper);
    //  axial->SetTexture(axialTexture);

}

//##ModelId=3E691E090394
mitk::Geometry2DDataVtkMapper3D::~Geometry2DDataVtkMapper3D()
{
  delete m_DataTreeIterator;

  m_VtkPlaneSource->Delete();
  m_VtkPolyDataMapper->Delete();
  m_Actor->Delete();
  m_VtkLookupTable->Delete();
  m_VtkTexture->Delete();
}

//##ModelId=3E691E090380
const mitk::Geometry2DData *mitk::Geometry2DDataVtkMapper3D::GetInput()
{
  if (this->GetNumberOfInputs() < 1)
  {
    return 0;
  }

  return static_cast<const mitk::Geometry2DData * > ( GetData() );
}

//##ModelId=3E691E09038A
void mitk::Geometry2DDataVtkMapper3D::Update()
{

}

//##ModelId=3E691E090396
void mitk::Geometry2DDataVtkMapper3D::GenerateOutputInformation()
{
}

//##ModelId=3E691E09038C
void mitk::Geometry2DDataVtkMapper3D::GenerateData()
{
}

//##ModelId=3E6E874F0007
void mitk::Geometry2DDataVtkMapper3D::SetDataIteratorForTexture(mitk::DataTreeIterator* iterator)
{
  delete m_DataTreeIterator;
  m_DataTreeIterator = iterator->clone();
}

//##ModelId=3EF19F850151
void mitk::Geometry2DDataVtkMapper3D::Update(mitk::BaseRenderer* renderer)
{
  if(IsVisible(renderer)==false)
  {
    m_Actor->VisibilityOff();
    return;
  }
  m_Actor->VisibilityOn();

  mitk::Geometry2DData::Pointer input  = const_cast<mitk::Geometry2DData*>(this->GetInput());

  if(input.IsNotNull())
  {
    mitk::Geometry2DDataToSurfaceDataFilter::Pointer surfaceCreator;
    mitk::SmartPointerProperty::Pointer surfacecreatorprop;
    surfacecreatorprop=dynamic_cast<mitk::SmartPointerProperty*>(GetDataTreeNode()->GetProperty("surfacegeometry", renderer).GetPointer());
    if( (surfacecreatorprop.IsNull()) ||
      (surfacecreatorprop->GetSmartPointer().IsNull()) ||
      ((surfaceCreator=dynamic_cast<mitk::Geometry2DDataToSurfaceDataFilter*>(surfacecreatorprop->GetSmartPointer().GetPointer()))==NULL)
      )
    {
      surfaceCreator = mitk::Geometry2DDataToSurfaceDataFilter::New();
      surfacecreatorprop=new mitk::SmartPointerProperty(surfaceCreator);
      GetDataTreeNode()->SetProperty("surfacegeometry", surfacecreatorprop);
    }

    surfaceCreator->SetInput(input);

    int res;
    if(GetDataTreeNode()->GetIntProperty("xresolution", res, renderer))
      surfaceCreator->SetXResolution(res);
    if(GetDataTreeNode()->GetIntProperty("yresolution", res, renderer))
      surfaceCreator->SetYResolution(res);

    surfaceCreator->Update(); //FIXME ohne das crash
    m_VtkPolyDataMapper->SetInput(surfaceCreator->GetOutput()->GetVtkPolyData());

    if(m_DataTreeIterator)
    {
      mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
      while(it->hasNext())
      {
        it->next();
        mitk::DataTreeNode* node=it->get();
        mitk::Mapper::Pointer mapper = node->GetMapper(1);
        mitk::ImageMapper2D* imagemapper = dynamic_cast<ImageMapper2D*>(mapper.GetPointer());

        if(imagemapper)
        {
          mitk::SmartPointerProperty::Pointer rendererProp = dynamic_cast<mitk::SmartPointerProperty*>(GetDataTreeNode()->GetPropertyList()->GetProperty("renderer").GetPointer());
          if(rendererProp.IsNotNull())
          {
            mitk::BaseRenderer::Pointer renderer = dynamic_cast<mitk::BaseRenderer*>(rendererProp->GetSmartPointer().GetPointer());
            if(renderer.IsNotNull())
            {
              // check for level window prop and use it for display if it exists
              mitk::LevelWindow levelWindow;
              if(node->GetLevelWindow(levelWindow, renderer))
                m_VtkLookupTable->SetTableRange(levelWindow.GetMin(),levelWindow.GetMax());

              imagemapper->GenerateAllData();
              const ImageMapper2D::RendererInfo* ri=imagemapper->GetRendererInfo(renderer);
              if((ri!=NULL) && (m_LastTextureUpdateTime<ri->m_LastUpdateTime))
              {
                ipPicDescriptor *p=ri->m_Pic;
                vtkImageData* vtkimage=Pic2vtk::convert(p);
                m_VtkTexture->SetInput(vtkimage); vtkimage->Delete(); vtkimage=NULL;
                m_Actor->SetTexture(m_VtkTexture);
                m_LastTextureUpdateTime=ri->m_LastUpdateTime;
              }
              break;
            }
          }
        }
      }
    }

    //apply color read from the PropertyList
    ApplyProperties(m_Actor, renderer);
  }
  StandardUpdate();
}

<commit_msg>possible inconsistency with texture generation fixed.<commit_after>#include "mitkGeometry2DDataVtkMapper3D.h"

#include "PlaneGeometry.h"

#include "DataTree.h"
#include "mitkImageMapper2D.h"

#include "mitkSurfaceData.h"
#include "mitkGeometry2DDataToSurfaceDataFilter.h"

#include "vtkActor.h"
#include "vtkProperty.h"
#include "vtkTexture.h"
#include "vtkPlaneSource.h"
#include "vtkPolyDataMapper.h"
#include "vtkLookupTable.h"
//#include "vtkImageMapToWindowLevelColors";
#include "mitkColorProperty.h"
#include "mitkFloatProperty.h"
#include "mitkLevelWindowProperty.h"
#include "mitkSmartPointerProperty.h"
#include <vtkActor.h>
#include <vtkImageData.h>

#include "pic2vtk.h"

//##ModelId=3E691E09038E
mitk::Geometry2DDataVtkMapper3D::Geometry2DDataVtkMapper3D() : m_DataTreeIterator(NULL), m_LastTextureUpdateTime(0)
{
  m_VtkPlaneSource = vtkPlaneSource::New();

  m_VtkPolyDataMapper = vtkPolyDataMapper::New();
  //        m_VtkPolyDataMapper->SetInput(m_VtkPlaneSource->GetOutput());
  m_VtkPolyDataMapper->ImmediateModeRenderingOn();

  m_Actor = vtkActor::New();
  m_Actor->SetMapper(m_VtkPolyDataMapper);

  m_Prop3D = m_Actor;
		m_Prop3D->Register(NULL);

  m_VtkLookupTable = vtkLookupTable::New();
    m_VtkLookupTable->SetTableRange (-1024, 4096);
    m_VtkLookupTable->SetSaturationRange (0, 0);
    m_VtkLookupTable->SetHueRange (0, 0);
    m_VtkLookupTable->SetValueRange (0, 1);
    m_VtkLookupTable->Build ();

  m_VtkTexture = vtkTexture::New();
    m_VtkTexture->InterpolateOn();
    m_VtkTexture->SetLookupTable(m_VtkLookupTable);
    m_VtkTexture->MapColorScalarsThroughLookupTableOn();

    //    m_Actor->SetTexture(axialTexture);

    //  axialTexture->SetInput(axialSection->GetOutput());
    //  axialTexture->InterpolateOn();
    //  axialTexture->SetLookupTable (lut);
    //  axialTexture->MapColorScalarsThroughLookupTableOn();
    //m_VtkPlaneSource = vtkPlaneSource::New();
    //  m_VtkPlaneSource->SetXResolution(1);
    //  m_VtkPlaneSource->SetYResolution(1);
    //  m_VtkPlaneSource->SetOrigin(0.0, 0.0, slice);
    //  m_VtkPlaneSource->SetPoint1(xDim, 0.0, slice);
    //  m_VtkPlaneSource->SetPoint2(0.0, yDim, slice);
    //m_VtkPolyDataMapper = vtkPolyDataMapper::New();
    //  m_VtkPolyDataMapper->SetInput(m_VtkPlaneSource->GetOutput());
    //  m_VtkPolyDataMapper->ImmediateModeRenderingOn();
    //axial = vtkActor::New();
    //  axial->SetMapper(m_VtkPolyDataMapper);
    //  axial->SetTexture(axialTexture);

}

//##ModelId=3E691E090394
mitk::Geometry2DDataVtkMapper3D::~Geometry2DDataVtkMapper3D()
{
  delete m_DataTreeIterator;

  m_VtkPlaneSource->Delete();
  m_VtkPolyDataMapper->Delete();
  m_Actor->Delete();
  m_VtkLookupTable->Delete();
  m_VtkTexture->Delete();
}

//##ModelId=3E691E090380
const mitk::Geometry2DData *mitk::Geometry2DDataVtkMapper3D::GetInput()
{
  if (this->GetNumberOfInputs() < 1)
  {
    return 0;
  }

  return static_cast<const mitk::Geometry2DData * > ( GetData() );
}

//##ModelId=3E691E09038A
void mitk::Geometry2DDataVtkMapper3D::Update()
{

}

//##ModelId=3E691E090396
void mitk::Geometry2DDataVtkMapper3D::GenerateOutputInformation()
{
}

//##ModelId=3E691E09038C
void mitk::Geometry2DDataVtkMapper3D::GenerateData()
{
}

//##ModelId=3E6E874F0007
void mitk::Geometry2DDataVtkMapper3D::SetDataIteratorForTexture(mitk::DataTreeIterator* iterator)
{
  delete m_DataTreeIterator;
  m_DataTreeIterator = iterator->clone();
}

//##ModelId=3EF19F850151
void mitk::Geometry2DDataVtkMapper3D::Update(mitk::BaseRenderer* renderer)
{
  if(IsVisible(renderer)==false)
  {
    m_Actor->VisibilityOff();
    return;
  }
  m_Actor->VisibilityOn();

  mitk::Geometry2DData::Pointer input  = const_cast<mitk::Geometry2DData*>(this->GetInput());

  if(input.IsNotNull())
  {
    mitk::Geometry2DDataToSurfaceDataFilter::Pointer surfaceCreator;
    mitk::SmartPointerProperty::Pointer surfacecreatorprop;
    surfacecreatorprop=dynamic_cast<mitk::SmartPointerProperty*>(GetDataTreeNode()->GetProperty("surfacegeometry", renderer).GetPointer());
    if( (surfacecreatorprop.IsNull()) ||
      (surfacecreatorprop->GetSmartPointer().IsNull()) ||
      ((surfaceCreator=dynamic_cast<mitk::Geometry2DDataToSurfaceDataFilter*>(surfacecreatorprop->GetSmartPointer().GetPointer()))==NULL)
      )
    {
      surfaceCreator = mitk::Geometry2DDataToSurfaceDataFilter::New();
      surfacecreatorprop=new mitk::SmartPointerProperty(surfaceCreator);
      GetDataTreeNode()->SetProperty("surfacegeometry", surfacecreatorprop);
    }

    surfaceCreator->SetInput(input);

    int res;
    if(GetDataTreeNode()->GetIntProperty("xresolution", res, renderer))
      surfaceCreator->SetXResolution(res);
    if(GetDataTreeNode()->GetIntProperty("yresolution", res, renderer))
      surfaceCreator->SetYResolution(res);

    surfaceCreator->Update(); //FIXME ohne das crash
    m_VtkPolyDataMapper->SetInput(surfaceCreator->GetOutput()->GetVtkPolyData());

    if(m_DataTreeIterator)
    {
      mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
      while(it->hasNext())
      {
        it->next();
        mitk::DataTreeNode* node=it->get();
        mitk::Mapper::Pointer mapper = node->GetMapper(1);
        mitk::ImageMapper2D* imagemapper = dynamic_cast<ImageMapper2D*>(mapper.GetPointer());

        if(imagemapper)
        {
          mitk::SmartPointerProperty::Pointer rendererProp = dynamic_cast<mitk::SmartPointerProperty*>(GetDataTreeNode()->GetPropertyList()->GetProperty("renderer").GetPointer());
          if(rendererProp.IsNotNull())
          {
            mitk::BaseRenderer::Pointer renderer = dynamic_cast<mitk::BaseRenderer*>(rendererProp->GetSmartPointer().GetPointer());
            if(renderer.IsNotNull())
            {
              // check for level window prop and use it for display if it exists
              mitk::LevelWindow levelWindow;
              if(node->GetLevelWindow(levelWindow, renderer))
                m_VtkLookupTable->SetTableRange(levelWindow.GetMin(),levelWindow.GetMax());

              //we have to do this before GenerateAllData() is called there may be
              //no RendererInfo for renderer yet, thus GenerateAllData won't update
              //the (non-existing) RendererInfo for renderer. By calling GetRendererInfo
              //a RendererInfo will be created for renderer (if it does not exist yet).
              const ImageMapper2D::RendererInfo* ri=imagemapper->GetRendererInfo(renderer);
              imagemapper->GenerateAllData();
              if((ri!=NULL) && (m_LastTextureUpdateTime<ri->m_LastUpdateTime))
              {
                ipPicDescriptor *p=ri->m_Pic;
                vtkImageData* vtkimage=Pic2vtk::convert(p);
                m_VtkTexture->SetInput(vtkimage); vtkimage->Delete(); vtkimage=NULL;
                m_Actor->SetTexture(m_VtkTexture);
                m_LastTextureUpdateTime=ri->m_LastUpdateTime;
              }
              break;
            }
          }
        }
      }
    }

    //apply color read from the PropertyList
    ApplyProperties(m_Actor, renderer);
  }
  StandardUpdate();
}

<|endoftext|>


<commit_before>/** @file nwrcde_main.cc
 *
 *  @author Dongryeol Lee (dongryel@cc.gatech.edu)
 */

#include "contrib/dongryel/multitree_template/multitree_dfs.h"
#include "mlpack/kde/dataset_scaler.h"
#include "mlpack/series_expansion/kernel_aux.h"
#include "nwrcde_problem.h"

template<typename TKernelAux>
void StartComputation(const Matrix &queries, const Matrix &references,
		      const Matrix &reference_targets,
		      struct datanode *nwrcde_module) {

  // Output file name for the fast algorithm.
  const char *output_file_name = fx_param_str(nwrcde_module, "output",
                                              "nwrcde_results.txt");

  // Declare the computation object.
  MultiTreeDepthFirst<NWRCdeProblem<TKernelAux> > algorithm;
  typename NWRCdeProblem<TKernelAux>::MultiTreeQueryResult query_results;

  // The array list of pointers to the query/reference sets and the
  // reference targets.
  ArrayList<const Matrix *> reference_sets;
  ArrayList<const Matrix *> query_sets;
  ArrayList<const Matrix *> reference_targets_set;

  // Nadaraya-Watson regression/conditional density estimation is a
  // two-body problem, hence there is only one reference set.
  reference_sets.Init(1);
  reference_sets[0] = &references;
  query_sets.Init(1);
  query_sets[0] = &queries;
  reference_targets_set.Init(1);
  reference_targets_set[0] = &reference_targets;

  algorithm.InitMultiChromatic(reference_sets, &reference_targets_set,
			       nwrcde_module);

  printf("Starting the multitree computation...\n");
  fx_timer_start(fx_root, "multitree_compute");
  algorithm.Compute(&query_sets, &query_results);
  fx_timer_stop(fx_root, "multitree_compute");
  printf("Finished the multitree computation...\n");

  query_results.PrintDebug(output_file_name);

  // If the do_naive flag is specified, then run the naive algorithm
  // as well.
  if(fx_param_exists(nwrcde_module, "do_naive")) {
    typename NWRCdeProblem<TKernelAux>::MultiTreeQueryResult
      naive_query_results;
    const char *naive_output_file_name =
      fx_param_str(nwrcde_module, "naive_output", "naive_nwrcde_results.txt");

    printf("Starting the naive computation...\n");
    fx_timer_start(fx_root, "naive_compute");
    algorithm.NaiveCompute(&query_sets, &naive_query_results);
    fx_timer_stop(fx_root, "naive_compute");
    printf("Finished the naive computation...\n");

    naive_query_results.PrintDebug(naive_output_file_name);

    // Compute the difference between the naively computed estimates
    // and the approximated estimates.
    Vector difference;
    la::SubInit(naive_query_results.final_results,
                query_results.final_results, &difference);

    // The maximum relative error.
    double max_relative_error = 0;
    int within_limit = 0;
    for(index_t i = 0; i < queries.n_cols(); i++) {
      double relative_error =
        (naive_query_results.final_results[i] ==
         query_results.final_results[i]) ?
        0:(fabs(difference[i]) /
           fabs(naive_query_results.final_results[i]));
      max_relative_error = std::max(max_relative_error, relative_error);

      if(relative_error <= fx_param_double(nwrcde_module, "relative_error",
					   0.1)) {
        within_limit++;
      }
    }
    fx_format_result(nwrcde_module, "max_relative_error", "%g",
                     max_relative_error);
    fx_format_result(nwrcde_module, "under_relative_error_limit", "%d",
                     within_limit);
  }

  // Output the prune statistics as well for the fast algorithm.
  fx_format_result(nwrcde_module, "num_finite_difference_prunes", "%d",
		   query_results.num_finite_difference_prunes);
  fx_format_result(nwrcde_module, "num_far_to_local_prunes", "%d",
		   query_results.num_far_to_local_prunes);
  fx_format_result(nwrcde_module, "num_direct_far_prunes", "%d",
		   query_results.num_direct_far_prunes);
  fx_format_result(nwrcde_module, "num_direct_local_prunes", "%d",
		   query_results.num_direct_local_prunes);
}

int main(int argc, char *argv[]) {

  // Initialize FastExec...
  fx_init(argc, argv, NULL);

  ////////// READING PARAMETERS AND LOADING DATA /////////////////////

  // FASTexec organizes parameters and results into submodules.  Think
  // of this as creating a new folder named "nwrcde_module" under the
  // root directory (NULL) for the NwrCde object to work inside.
  // Here, we initialize it with all parameters defined
  // "--nwrcde/...=...".
  struct datanode* nwrcde_module = fx_submodule(fx_root, "nwrcde");

  // The reference data file is a required parameter.
  const char* references_file_name = fx_param_str_req(fx_root, "data");

  // The file containing the reference target values is a required
  // parameter.
  const char* reference_targets_file_name = fx_param_str_req
    (fx_root, "dtarget");

  // The query data file defaults to the references.
  const char* queries_file_name = fx_param_str(fx_root, "query",
					       references_file_name);

  // query and reference datasets and target training values.
  Matrix references;
  Matrix reference_targets;
  Matrix queries;

  // data::Load inits a matrix with the contents of a .csv or .arff.
  data::Load(references_file_name, &references);
  data::Load(queries_file_name, &queries);
  data::Load(reference_targets_file_name, &reference_targets);
  Matrix reference_targets_transposed;
  reference_targets_transposed.Init(reference_targets.n_cols(),
				    reference_targets.n_rows() * 2);

  for(index_t r = 0; r < reference_targets.n_rows(); r++) {
    for(index_t c = 0; c < reference_targets.n_cols(); c++) {

      reference_targets_transposed.set(c, r, reference_targets.get(r, c));
      reference_targets_transposed.set(c, 2 * r + 1, 1.0);
    }
  }

  // Run the appropriate algorithm based on the kernel type.
  if(!strcmp(fx_param_str(nwrcde_module, "kernel", "gaussian"), "gaussian")) {

    printf("Chose the Gaussian kernel...\n");
    StartComputation<GaussianKernelAux>(queries, references,
					reference_targets_transposed,
					nwrcde_module);
  }
  else if(!strcmp(fx_param_str(nwrcde_module, "kernel", "epan"), "epan")) {

    printf("Chose the Epanechnikov kernel...\n");
    StartComputation<EpanKernelAux>(queries, references,
				    reference_targets_transposed,
				    nwrcde_module);
  }

  // Finalize FastExec and print output results.
  fx_done(fx_root);
  return 0;
}
<commit_msg>Scaling option added.<commit_after>/** @file nwrcde_main.cc
 *
 *  @author Dongryeol Lee (dongryel@cc.gatech.edu)
 */

#include "contrib/dongryel/multitree_template/multitree_dfs.h"
#include "mlpack/kde/dataset_scaler.h"
#include "mlpack/series_expansion/kernel_aux.h"
#include "nwrcde_problem.h"

template<typename TKernelAux>
void StartComputation(const Matrix &queries, const Matrix &references,
		      const Matrix &reference_targets,
		      struct datanode *nwrcde_module) {

  // Output file name for the fast algorithm.
  const char *output_file_name = fx_param_str(nwrcde_module, "output",
                                              "nwrcde_results.txt");

  // Declare the computation object.
  MultiTreeDepthFirst<NWRCdeProblem<TKernelAux> > algorithm;
  typename NWRCdeProblem<TKernelAux>::MultiTreeQueryResult query_results;

  // The array list of pointers to the query/reference sets and the
  // reference targets.
  ArrayList<const Matrix *> reference_sets;
  ArrayList<const Matrix *> query_sets;
  ArrayList<const Matrix *> reference_targets_set;

  // Nadaraya-Watson regression/conditional density estimation is a
  // two-body problem, hence there is only one reference set.
  reference_sets.Init(1);
  reference_sets[0] = &references;
  query_sets.Init(1);
  query_sets[0] = &queries;
  reference_targets_set.Init(1);
  reference_targets_set[0] = &reference_targets;

  algorithm.InitMultiChromatic(reference_sets, &reference_targets_set,
			       nwrcde_module);

  printf("Starting the multitree computation...\n");
  fx_timer_start(fx_root, "multitree_compute");
  algorithm.Compute(&query_sets, &query_results);
  fx_timer_stop(fx_root, "multitree_compute");
  printf("Finished the multitree computation...\n");

  query_results.PrintDebug(output_file_name);

  // If the do_naive flag is specified, then run the naive algorithm
  // as well.
  if(fx_param_exists(nwrcde_module, "do_naive")) {
    typename NWRCdeProblem<TKernelAux>::MultiTreeQueryResult
      naive_query_results;
    const char *naive_output_file_name =
      fx_param_str(nwrcde_module, "naive_output", "naive_nwrcde_results.txt");

    printf("Starting the naive computation...\n");
    fx_timer_start(fx_root, "naive_compute");
    algorithm.NaiveCompute(&query_sets, &naive_query_results);
    fx_timer_stop(fx_root, "naive_compute");
    printf("Finished the naive computation...\n");

    naive_query_results.PrintDebug(naive_output_file_name);

    // Compute the difference between the naively computed estimates
    // and the approximated estimates.
    Vector difference;
    la::SubInit(naive_query_results.final_results,
                query_results.final_results, &difference);

    // The maximum relative error.
    double max_relative_error = 0;
    int within_limit = 0;
    for(index_t i = 0; i < queries.n_cols(); i++) {
      double relative_error =
        (naive_query_results.final_results[i] ==
         query_results.final_results[i]) ?
        0:(fabs(difference[i]) /
           fabs(naive_query_results.final_results[i]));
      max_relative_error = std::max(max_relative_error, relative_error);

      if(relative_error <= fx_param_double(nwrcde_module, "relative_error",
					   0.1)) {
        within_limit++;
      }
    }
    fx_format_result(nwrcde_module, "max_relative_error", "%g",
                     max_relative_error);
    fx_format_result(nwrcde_module, "under_relative_error_limit", "%d",
                     within_limit);
  }

  // Output the prune statistics as well for the fast algorithm.
  fx_format_result(nwrcde_module, "num_finite_difference_prunes", "%d",
		   query_results.num_finite_difference_prunes);
  fx_format_result(nwrcde_module, "num_far_to_local_prunes", "%d",
		   query_results.num_far_to_local_prunes);
  fx_format_result(nwrcde_module, "num_direct_far_prunes", "%d",
		   query_results.num_direct_far_prunes);
  fx_format_result(nwrcde_module, "num_direct_local_prunes", "%d",
		   query_results.num_direct_local_prunes);
}

int main(int argc, char *argv[]) {

  // Initialize FastExec...
  fx_init(argc, argv, NULL);

  ////////// READING PARAMETERS AND LOADING DATA /////////////////////

  // FASTexec organizes parameters and results into submodules.  Think
  // of this as creating a new folder named "nwrcde_module" under the
  // root directory (NULL) for the NwrCde object to work inside.
  // Here, we initialize it with all parameters defined
  // "--nwrcde/...=...".
  struct datanode* nwrcde_module = fx_submodule(fx_root, "nwrcde");

  // The reference data file is a required parameter.
  const char* references_file_name = fx_param_str_req(fx_root, "data");

  // The file containing the reference target values is a required
  // parameter.
  const char* reference_targets_file_name = fx_param_str_req
    (fx_root, "dtarget");

  // The query data file defaults to the references.
  const char* queries_file_name = fx_param_str(fx_root, "query",
					       references_file_name);

  // query and reference datasets and target training values.
  Matrix references;
  Matrix reference_targets;
  Matrix queries;

  // data::Load inits a matrix with the contents of a .csv or .arff.
  data::Load(references_file_name, &references);

  bool queries_equal_references = !strcmp(references_file_name,
                                          queries_file_name);

  if(queries_equal_references) {
    queries.Alias(references);
  }
  else {
    data::Load(queries_file_name, &queries);
  }
  data::Load(reference_targets_file_name, &reference_targets);
  Matrix reference_targets_transposed;
  reference_targets_transposed.Init(reference_targets.n_cols(),
				    reference_targets.n_rows() * 2);

  for(index_t r = 0; r < reference_targets.n_rows(); r++) {
    for(index_t c = 0; c < reference_targets.n_cols(); c++) {

      reference_targets_transposed.set(c, r, reference_targets.get(r, c));
      reference_targets_transposed.set(c, 2 * r + 1, 1.0);
    }
  }

  // Confirm whether the user asked for scaling of the dataset
  if(!strcmp(fx_param_str(nwrcde_module, "scaling", "none"), "range")) {
    printf("Range scaling...\n");
    DatasetScaler::ScaleDataByMinMax(queries, references,
                                     queries_equal_references);
  }
  else if(!strcmp(fx_param_str(nwrcde_module, "scaling", "none"),
                  "standardize")) {
    printf("Standardized scaling...\n");
    DatasetScaler::StandardizeData(queries, references,
                                   queries_equal_references);
  }

  // Run the appropriate algorithm based on the kernel type.
  if(!strcmp(fx_param_str(nwrcde_module, "kernel", "gaussian"), "gaussian")) {

    printf("Chose the Gaussian kernel...\n");
    StartComputation<GaussianKernelAux>(queries, references,
					reference_targets_transposed,
					nwrcde_module);
  }
  else if(!strcmp(fx_param_str(nwrcde_module, "kernel", "epan"), "epan")) {

    printf("Chose the Epanechnikov kernel...\n");
    StartComputation<EpanKernelAux>(queries, references,
				    reference_targets_transposed,
				    nwrcde_module);
  }

  // Finalize FastExec and print output results.
  fx_done(fx_root);
  return 0;
}
<|endoftext|>