text
stringlengths 5
1.04M
|
|---|
/**
* @file maze_generator.cpp
* @author Ferenc Nemeth
* @date 3 Dec 2018
* @brief Base class: methods and variables used by every maze generator.
*
* Copyright (c) 2018 Ferenc Nemeth - https://github.com/ferenc-nemeth/
*/
#include "maze_generator.h"
/**
* @brief Constructor. Generates a 2D vector, which represents the maze.
* @param height - Height of the maze.
* @param width - Width of the maze.
* @return void
*/
maze::maze_generator::maze_generator(uint32_t height, uint32_t width)
{
/* Make sure, that the dimensions are odd numbers, otherwise the maze would look strange. */
if ((!(height%2u)) || (!(width%2u)))
{
throw std::invalid_argument("Height and width must be odd numbers!");
}
/* Create an area filled with walls. */
area.resize(height);
for (uint32_t y = 0u; y < height; y++)
{
area[y].resize(width);
for (uint32_t x = 0u; x < width; x++)
{
area[y][x] = wall;
}
}
}
/**
* @brief Manually changes the value of a cell.
* @param y - The y coordinate of the cell.
* @param x - The x coordinate of the cell.
* @param value - The value, either 0 or 1.
* @return void
*/
void maze::maze_generator::set_cell(uint32_t y, uint32_t x, uint32_t value)
{
if ((area.size() <= y) || (area[y].size() <= x))
{
throw std::invalid_argument("Out of boundary!");
}
else if ((wall != value) && (hole != value))
{
throw std::invalid_argument("The input can only contain 0 or 1.");
}
else
{
area[y][x] = value;
}
}
/**
* @brief Returns the value of a cell.
* @param y - The y coordinate of the hole.
* @param x - The x coordinate of the hole.
* @return value - The actual value of the cell, either 0 or 1.
*/
uint32_t maze::maze_generator::get_cell(uint32_t y, uint32_t x)
{
return area[y][x];
}
/**
* @brief Returns the maze.
* @param void
* @return area - 2D vector of the maze. 1 represents a hole, 0 represents a wall.
*/
std::vector<std::vector<uint32_t>> maze::maze_generator::get_maze(void)
{
return area;
}
/**
* @brief Overwrites the current maze.
* @param vect - 2D vector of the maze. 1 represents a hole, 0 represents a wall.
* @return void
*/
void maze::maze_generator::set_maze(std::vector<std::vector<uint32_t>> vect)
{
if ((vect.size() != area.size()) || (vect[0u].size() != area[0u].size()))
{
throw std::invalid_argument("Wrong size!");
}
else
{
for (uint32_t y = 0u; y < vect.size(); y++)
{
for (uint32_t x = 0u; x < vect[y].size(); x++)
{
if ((wall != vect[y][x]) && (hole != vect[y][x]))
{
throw std::invalid_argument("The input can only contain 0 or 1.");
}
else
{
area[y][x] = vect[y][x];
}
}
}
}
}
/**
* @brief Reshapes the maze.
* @param height - New height of the maze.
* @param width - New width of the maze.
* @return void
*/
void maze::maze_generator::reshape(uint32_t height, uint32_t width)
{
/* Make sure, that the dimensions are odd numbers, otherwise the maze would look strange. */
if ((!(height%2u)) || (!(width%2u)))
{
throw std::invalid_argument("Height and width must be odd numbers!");
}
/* Resize. */
area.resize(height);
for (uint32_t y = 0u; y < height; y++)
{
area[y].resize(width);
}
}
/**
* @brief Returns the height of the maze.
* @param void
* @return height
*/
uint32_t maze::maze_generator::get_height(void)
{
return area.size();
}
/**
* @brief Returns the width of the maze.
* @param void
* @return width
*/
uint32_t maze::maze_generator::get_width(void)
{
return area[0u].size();
}
|
/**********************************************************************
*
* FILE: MultiTextureControl.cpp
*
* DESCRIPTION: Read/Write osg::MultiTextureControl in binary format to disk.
*
* CREATED BY: Auto generated by iveGenerate
* and later modified by Rune Schmidt Jensen.
*
* HISTORY: Created 24.3.2003
*
* Copyright 2003 VR-C
**********************************************************************/
#include "Exception.h"
#include "MultiTextureControl.h"
#include "Group.h"
using namespace ive;
void MultiTextureControl::write(DataOutputStream* out){
// Write MultiTextureControl's identification.
out->writeInt(IVEMULTITEXTURECONTROL);
// If the osg class is inherited by any other class we should also write this to file.
osg::Group* group = dynamic_cast<osg::Group*>(this);
if(group){
((ive::Group*)(group))->write(out);
}
else
throw Exception("MultiTextureControl::write(): Could not cast this osg::MultiTextureControl to an osg::Group.");
// Write MultiTextureControl's properties.
// Write rangelist
unsigned int size = getNumTextureWeights();
out->writeUInt(size);
for(unsigned int i=0;i<size;i++)
{
out->writeFloat(getTextureWeight(i));
}
}
void MultiTextureControl::read(DataInputStream* in){
// Peek on MultiTextureControl's identification.
int id = in->peekInt();
if(id == IVEMULTITEXTURECONTROL){
// Read MultiTextureControl's identification.
id = in->readInt();
// If the osg class is inherited by any other class we should also read this from file.
osg::Group* group = dynamic_cast<osg::Group*>(this);
if(group){
((ive::Group*)(group))->read(in);
}
else
throw Exception("MultiTextureControl::read(): Could not cast this osg::MultiTextureControl to an osg::Group.");
// Read MultiTextureControl's properties
// Read rangelist
unsigned int size = in->readUInt();
for(unsigned int i=0;i<size;i++)
{
float value = in->readFloat();
setTextureWeight(i, value);
}
}
else{
throw Exception("MultiTextureControl::read(): Expected MultiTextureControl identification.");
}
}
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE789_Uncontrolled_Mem_Alloc__new_wchar_t_fixed_11.cpp
Label Definition File: CWE789_Uncontrolled_Mem_Alloc__new.label.xml
Template File: sources-sinks-11.tmpl.cpp
*/
/*
* @description
* CWE: 789 Uncontrolled Memory Allocation
* BadSource: fixed Large, fixed value
* GoodSource: Small number greater than zero
* Sinks:
* GoodSink: Allocate memory with new [] and check the size of the memory to be allocated
* BadSink : Allocate memory with new [], but incorrectly check the size of the memory to be allocated
* Flow Variant: 11 Control flow: if(global_returns_t()) and if(global_returns_f())
* */
#include "std_testcase.h"
#define HELLO_STRING L"hello"
namespace CWE789_Uncontrolled_Mem_Alloc__new_wchar_t_fixed_11
{
#ifndef OMITBAD
void bad()
{
int data;
/* Initialize data */
data = -1;
if(global_returns_t())
{
/* POTENTIAL FLAW: Use a relatively large number for memory allocation */
data = 10000;
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
/* FIX: Use a relatively small number for memory allocation */
data = 20;
}
if(global_returns_t())
{
{
wchar_t * wchar_t_string;
/* FLAW: No MAXIMUM limitation for memory allocation and no check to ensure data is large enough
* for the wcscpy() function to not cause a buffer overflow */
/* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
if (data > 0)
{
wchar_t_string = new wchar_t[data];
/* Copy a small string into wchar_t_string$ */
wcscpy(wchar_t_string, HELLO_STRING);
printWLine(wchar_t_string);
delete [] wchar_t_string;
}
else
{
printLine("Input is less than 0");
}
}
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
{
wchar_t * wchar_t_string;
/* FIX: Include a MAXIMUM limitation for memory allocation and a check to ensure data is large enough
* for the wcscpy() function to not cause a buffer overflow */
/* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
if ((size_t)data > wcslen(HELLO_STRING) && data < 100)
{
wchar_t_string = new wchar_t[data];
/* Copy a small string into wchar_t_string$ */
wcscpy(wchar_t_string, HELLO_STRING);
printWLine(wchar_t_string);
delete [] wchar_t_string;
}
else
{
printLine("Input is less than the length of the source string or too large");
}
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodB2G1() - use badsource and goodsink by changing the second global_returns_t() to global_returns_f() */
static void goodB2G1()
{
int data;
/* Initialize data */
data = -1;
if(global_returns_t())
{
/* POTENTIAL FLAW: Use a relatively large number for memory allocation */
data = 10000;
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
/* FIX: Use a relatively small number for memory allocation */
data = 20;
}
if(global_returns_f())
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
{
wchar_t * wchar_t_string;
/* FLAW: No MAXIMUM limitation for memory allocation and no check to ensure data is large enough
* for the wcscpy() function to not cause a buffer overflow */
/* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
if (data > 0)
{
wchar_t_string = new wchar_t[data];
/* Copy a small string into wchar_t_string$ */
wcscpy(wchar_t_string, HELLO_STRING);
printWLine(wchar_t_string);
delete [] wchar_t_string;
}
else
{
printLine("Input is less than 0");
}
}
}
else
{
{
wchar_t * wchar_t_string;
/* FIX: Include a MAXIMUM limitation for memory allocation and a check to ensure data is large enough
* for the wcscpy() function to not cause a buffer overflow */
/* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
if ((size_t)data > wcslen(HELLO_STRING) && data < 100)
{
wchar_t_string = new wchar_t[data];
/* Copy a small string into wchar_t_string$ */
wcscpy(wchar_t_string, HELLO_STRING);
printWLine(wchar_t_string);
delete [] wchar_t_string;
}
else
{
printLine("Input is less than the length of the source string or too large");
}
}
}
}
/* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */
static void goodB2G2()
{
int data;
/* Initialize data */
data = -1;
if(global_returns_t())
{
/* POTENTIAL FLAW: Use a relatively large number for memory allocation */
data = 10000;
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
/* FIX: Use a relatively small number for memory allocation */
data = 20;
}
if(global_returns_t())
{
{
wchar_t * wchar_t_string;
/* FIX: Include a MAXIMUM limitation for memory allocation and a check to ensure data is large enough
* for the wcscpy() function to not cause a buffer overflow */
/* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
if ((size_t)data > wcslen(HELLO_STRING) && data < 100)
{
wchar_t_string = new wchar_t[data];
/* Copy a small string into wchar_t_string$ */
wcscpy(wchar_t_string, HELLO_STRING);
printWLine(wchar_t_string);
delete [] wchar_t_string;
}
else
{
printLine("Input is less than the length of the source string or too large");
}
}
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
{
wchar_t * wchar_t_string;
/* FLAW: No MAXIMUM limitation for memory allocation and no check to ensure data is large enough
* for the wcscpy() function to not cause a buffer overflow */
/* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
if (data > 0)
{
wchar_t_string = new wchar_t[data];
/* Copy a small string into wchar_t_string$ */
wcscpy(wchar_t_string, HELLO_STRING);
printWLine(wchar_t_string);
delete [] wchar_t_string;
}
else
{
printLine("Input is less than 0");
}
}
}
}
/* goodG2B1() - use goodsource and badsink by changing the first global_returns_t() to global_returns_f() */
static void goodG2B1()
{
int data;
/* Initialize data */
data = -1;
if(global_returns_f())
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
/* POTENTIAL FLAW: Use a relatively large number for memory allocation */
data = 10000;
}
else
{
/* FIX: Use a relatively small number for memory allocation */
data = 20;
}
if(global_returns_t())
{
{
wchar_t * wchar_t_string;
/* FLAW: No MAXIMUM limitation for memory allocation and no check to ensure data is large enough
* for the wcscpy() function to not cause a buffer overflow */
/* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
if (data > 0)
{
wchar_t_string = new wchar_t[data];
/* Copy a small string into wchar_t_string$ */
wcscpy(wchar_t_string, HELLO_STRING);
printWLine(wchar_t_string);
delete [] wchar_t_string;
}
else
{
printLine("Input is less than 0");
}
}
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
{
wchar_t * wchar_t_string;
/* FIX: Include a MAXIMUM limitation for memory allocation and a check to ensure data is large enough
* for the wcscpy() function to not cause a buffer overflow */
/* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
if ((size_t)data > wcslen(HELLO_STRING) && data < 100)
{
wchar_t_string = new wchar_t[data];
/* Copy a small string into wchar_t_string$ */
wcscpy(wchar_t_string, HELLO_STRING);
printWLine(wchar_t_string);
delete [] wchar_t_string;
}
else
{
printLine("Input is less than the length of the source string or too large");
}
}
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */
static void goodG2B2()
{
int data;
/* Initialize data */
data = -1;
if(global_returns_t())
{
/* FIX: Use a relatively small number for memory allocation */
data = 20;
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
/* POTENTIAL FLAW: Use a relatively large number for memory allocation */
data = 10000;
}
if(global_returns_t())
{
{
wchar_t * wchar_t_string;
/* FLAW: No MAXIMUM limitation for memory allocation and no check to ensure data is large enough
* for the wcscpy() function to not cause a buffer overflow */
/* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
if (data > 0)
{
wchar_t_string = new wchar_t[data];
/* Copy a small string into wchar_t_string$ */
wcscpy(wchar_t_string, HELLO_STRING);
printWLine(wchar_t_string);
delete [] wchar_t_string;
}
else
{
printLine("Input is less than 0");
}
}
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
{
wchar_t * wchar_t_string;
/* FIX: Include a MAXIMUM limitation for memory allocation and a check to ensure data is large enough
* for the wcscpy() function to not cause a buffer overflow */
/* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
if ((size_t)data > wcslen(HELLO_STRING) && data < 100)
{
wchar_t_string = new wchar_t[data];
/* Copy a small string into wchar_t_string$ */
wcscpy(wchar_t_string, HELLO_STRING);
printWLine(wchar_t_string);
delete [] wchar_t_string;
}
else
{
printLine("Input is less than the length of the source string or too large");
}
}
}
}
void good()
{
goodB2G1();
goodB2G2();
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
} // close namespace
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE789_Uncontrolled_Mem_Alloc__new_wchar_t_fixed_11; // so that we can use good and bad easily
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
// generated from rosidl_generator_cpp/resource/idl.hpp.em
// generated code does not contain a copyright notice
#ifndef RMF_BUILDING_MAP_MSGS__MSG__PLACE_HPP_
#define RMF_BUILDING_MAP_MSGS__MSG__PLACE_HPP_
#include "rmf_building_map_msgs/msg/detail/place__struct.hpp"
#include "rmf_building_map_msgs/msg/detail/place__builder.hpp"
#include "rmf_building_map_msgs/msg/detail/place__traits.hpp"
#endif // RMF_BUILDING_MAP_MSGS__MSG__PLACE_HPP_
|
#pragma once
#include "kernel.h"
#define PIC1 0x20 // Master PIC
#define PIC2 0xA0 // Slave PIC
#define PIC1_DATA (PIC1 + 1)
#define PIC2_DATA (PIC2 + 1)
#define PIC_EOI 0x20 // end of interrupt
#define IRQ_BASE 0x20
// Exceptions, cf. http://wiki.osdev.org/Exceptions
#define EXCEPTION_DE 0
#define EXCEPTION_DB 1
#define EXCEPTION_BP 3
#define EXCEPTION_OF 4
#define EXCEPTION_BR 5
#define EXCEPTION_UD 6
#define EXCEPTION_NM 7
#define EXCEPTION_DF 8
#define EXCEPTION_TS 10
#define EXCEPTION_NP 11
#define EXCEPTION_SS 12
#define EXCEPTION_GP 13
#define EXCEPTION_PF 14
// 15 is "reserved"
#define EXCEPTION_MF 16
#define EXCEPTION_AC 17
// ...
// Hardware interrupts
#define IRQ0 32
#define IRQ1 33
#define IRQ2 34
#define IRQ3 35
#define IRQ4 36
#define IRQ5 37
#define IRQ6 38
#define IRQ7 39
#define IRQ8 40
#define IRQ9 41
#define IRQ10 42
#define IRQ11 43
#define IRQ12 44
extern "C"
{
//Declared in asm
extern void exc0();
extern void exc1();
extern void exc2();
extern void exc3();
extern void exc4();
extern void exc5();
extern void exc6();
extern void exc7();
extern void exc8();
extern void exc9();
extern void exc10();
extern void exc11();
extern void exc12();
extern void exc13();
extern void exc14();
extern void exc15();
extern void exc16();
extern void exc17();
extern void exc18();
extern void exc19();
extern void exc20();
extern void exc21();
extern void exc22();
extern void exc23();
extern void exc24();
extern void exc25();
extern void exc26();
extern void exc27();
extern void exc28();
extern void exc29();
extern void exc30();
extern void exc31();
extern void exc48();
extern void exc128();
extern void irq0();
extern void irq1();
extern void irq2();
extern void irq3();
extern void irq4();
extern void irq5();
extern void irq6();
extern void irq7();
extern void irq8();
extern void irq9();
extern void irq10();
extern void irq11();
extern void irq12();
}
typedef struct _stack
{
uint64_t r15; // 0
uint64_t r14; // 8
uint64_t r13; // 16
uint64_t r12; // 24
uint64_t r11; // 32
uint64_t r10; // 40
uint64_t r9; // 48
uint64_t r8; // 56
uint64_t rbp; // 64
uint64_t rdi; // 72
uint64_t rsi; // 80
uint64_t rdx; // 88
uint64_t rcx; // 96
uint64_t rbx; // 104
uint64_t rax; // 112
uint64_t id; // 120
uint64_t errorCode; // 128
uint64_t instructionPointer; // 136
uint64_t codeSegment; // 144
uint64_t cpuFlags; // 152
uint64_t stackPointer; // 160
uint64_t stackSegment; // 168
} PACKED InterruptStack;
typedef void (*InterruptHandler)(InterruptStack* stack);
typedef void (*InterruptHandlerArg)(InterruptStack *stack, void *data);
class Interrupts
{
public:
struct HandlerInfo
{
InterruptHandlerArg handler;
void *data;
};
private:
InterruptHandler handlers[256];
HandlerInfo argHandlers[256];
public:
void Init();
bool InterruptsEnabled();
void EnableInterrupts();
void DisableInterrupts();
void RegisterHandler(uint64_t id, InterruptHandler handler);
void RegisterHandler(uint64_t id, InterruptHandlerArg handler, void *data);
inline InterruptHandler GetHandler(int index)
{
if(index >= 0 && index <= sizeof(handlers) / sizeof(handlers[0]))
{
return handlers[index];
}
return NULL;
}
inline HandlerInfo *GetHandlerArg(int index)
{
if(index >= 0 && index <= sizeof(argHandlers) / sizeof(argHandlers[0]))
{
return &argHandlers[index];
}
return NULL;
}
};
extern Interrupts interrupts;
/**
* This is the handler for software interrupts and exceptions.
*
* - Exceptions: These are generated internally by the CPU and used to alert
* the running kernel of an event or situation which requires its attention.
* On x86 CPUs, these include exception conditions such as Double Fault, Page
* Fault, General Protection Fault, etc.
* - Software Interrupt: This is an interrupt signalled by software running on
* a CPU to indicate that it needs the kernel's attention. These types of
* interrupts are generally used for System Calls.
*
* @param s the interrupt stack
*/
void interruptIntHandler(InterruptStack s) __asm__("int_handler");
/**
* This is the handler for hardware interrupts.
*
* Interrupt Request (IRQ) or Hardware Interrupt are a type of interrupt that
* is generated externally by the chipset, and it is signalled by latching onto
* the INTR pin or equivalent signal of the CPU in question.
*
* @param s the interrupt stack
*/
void interruptIRQHandler(InterruptStack s) __asm__("irq_handler");
|
//
// CBLiteTool.cc
//
// Copyright (c) 2017 Couchbase, Inc All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "CBLiteTool.hh"
#include "CBLiteCommand.hh"
#include "StringUtil.hh" // for digittoint(), on non-BSD-like systems
using namespace litecore;
using namespace std;
using namespace fleece;
int main(int argc, const char * argv[]) {
CBLiteTool tool;
return tool.main(argc, argv);
}
CBLiteTool::~CBLiteTool() {
if (_shouldCloseDB && _db) {
C4Error err;
bool ok = c4db_close(_db, &err);
if (!ok)
cerr << "Warning: error closing database: " << c4error_descriptionStr(err) << "\n";
}
}
void CBLiteTool::usage() {
cerr <<
ansiBold() << "cblite: Couchbase Lite / LiteCore database multi-tool\n\n" << ansiReset() <<
bold("Usage:\n") <<
" cblite " << it("[FLAGS] SUBCOMMAND /path/to/db.cblite2 ...") << "\n"
" cblite " << it("[FLAGS] /path/to/db.cblite2 ...") << " (interactive mode*)\n"
" cblite " << it("[FLAGS] wss://host:port/dbname ...") << " (interactive mode*)\n"
"\n" <<
bold("Global Flags") << " (before the subcommand name):\n"
" --color : Use bold/italic (sometimes color), if terminal supports it\n"
" --create : Create the database if it doesn't already exist.\n"
#ifdef COUCHBASE_ENTERPRISE
" --encrypted : Open an encrypted database (prompts for password)\n"
#endif
" --upgrade : Allow DB version upgrade (breaking backward compatibility)\n"
" --upgrade=vv: Upgrade DB from rev-trees to version vectors (experimental! irreversible!)\n"
" --version : Display version info and exit\n"
" --writeable : Open the database with read+write access\n"
"\n" <<
bold("Subcommands:\n") <<
" cat, get : display document body(ies) as JSON\n"
" check : check for database corruption\n"
" compact : free up unused space\n"
" edit : update or create a document as JSON in a text editor\n"
#ifdef COUCHBASE_ENTERPRISE
" encrypt,decrypt: add or remove encryption\n"
#endif
" help : print more help for a subcommand\n"
" import, export : copy to/from JSON files\n"
" info : information & stats about the database\n"
" logcat : convert binary log files to textual form\n"
" ls : list the IDs of documents in the database\n"
#ifdef HAS_COLLECTIONS
" mv : move documents from one collection to another\n"
" mkcoll : create a collection\n"
#endif
" open : open DB and start interactive mode*\n"
" openremote : pull remote DB to temp file & start interactive mode*\n"
" push, pull : replicate to/from a remote database\n"
" put : create or modify a document\n"
" query, select : run a N1QL or JSON query\n"
" reindex : drop and recreates an index\n"
" revs : show the revisions of a document\n"
" rm : delete documents\n"
" serve : start a simple REST server on the DB\n"
"\n"
" Most subcommands take their own flags or parameters, following the name.\n"
" For details, run `cblite help " << it("SUBCOMMAND") << "`.\n"
"\n" <<
bold("Interactive Mode:\n") <<
" * The interactive 'shell' displays a `(cblite)` prompt and lets you enter a subcommand.\n"
" Since the database is already open, you don't have to give its path again, nor any of\n"
" the global flags, simply the subcommand and any flags or parameters it takes.\n"
" For example: `cat doc123`, `ls -l`, `help push`.\n"
" Exit the shell by entering `quit` or pressing Ctrl-D (on Unix) or Ctrl-Z (on Windows).\n"
;
}
void CBLiteTool::displayVersion() {
alloc_slice version = c4_getVersion();
cout << "Couchbase Lite Core " << version << "\n";
exit(0);
}
int CBLiteTool::run() {
// Initial pre-subcommand flags:
processFlags({
{"--create", [&]{_dbFlags |= kC4DB_Create; _dbFlags &= ~kC4DB_ReadOnly;}},
{"--writeable", [&]{_dbFlags &= ~kC4DB_ReadOnly;}},
{"--upgrade", [&]{_dbFlags &= ~(kC4DB_NoUpgrade | kC4DB_ReadOnly);}},
#if LITECORE_API_VERSION >= 300
{"--upgrade=vv",[&]{_dbFlags &= ~(kC4DB_NoUpgrade | kC4DB_ReadOnly);
_dbFlags |= kC4DB_VersionVectors;}},
#endif
{"--encrypted", [&]{_dbNeedsPassword = true;}},
{"--version", [&]{displayVersion();}},
{"-v", [&]{displayVersion();}},
});
c4log_setCallbackLevel(kC4LogWarning);
if (!hasArgs()) {
cerr << ansiBold()
<< "cblite: Couchbase Lite / LiteCore database multi-tool\n" << ansiReset()
<< "ERROR: Missing subcommand or database path.\n"
<< "For a list of subcommands, run " << ansiBold() << "cblite help" << ansiReset() << ".\n"
<< "To start the interactive mode, run "
<< ansiBold() << "cblite " << ansiItalic() << "/path/of/db.cblite2" << ansiReset() << '\n';
fail();
}
string cmd = nextArg("subcommand or database path");
if (isDatabaseURL(cmd)) {
// Interactive mode on remote URL:
endOfArgs();
CBLiteCommand::runInteractiveWithURL(*this, cmd);
} else if (isDatabasePath(cmd)) {
// Interactive mode:
endOfArgs();
CBLiteCommand::runInteractive(*this, cmd);
} else if (cmd == "help") {
// Run "help" subcommand:
helpCommand();
} else {
// Run subcommand:
auto subcommandInstance = subcommand(cmd);
if (subcommandInstance) {
subcommandInstance->runSubcommand();
} else {
if (cmd.find(FilePath::kSeparator) != string::npos || cmd.find('.') || cmd.size() > 10)
fail(format("Not a valid database path (must end in %s) or subcommand name: %s",
kC4DatabaseFilenameExtension, cmd.c_str()));
else
failMisuse(format("Unknown subcommand '%s'", cmd.c_str()));
}
}
return 0;
}
#pragma mark - OPENING DATABASE:
bool CBLiteTool::isDatabasePath(const string &path) {
return ! splitDBPath(path).second.empty();
}
pair<string,string> CBLiteTool::splitDBPath(const string &pathStr) {
FilePath path(pathStr);
if (path.extension() != kC4DatabaseFilenameExtension)
return {"",""};
return {path.parentDir(), path.unextendedName()};
}
bool CBLiteTool::isDatabaseURL(const string &str) {
C4Address addr;
C4String dbName;
return c4address_fromURL(slice(str), &addr, &dbName);
}
#if COUCHBASE_ENTERPRISE
static bool setHexKey(C4EncryptionKey *key, const string &str) {
if (str.size() != 2 * kC4EncryptionKeySizeAES256)
return false;
uint8_t *dst = &key->bytes[0];
for (size_t src = 0; src < 2 * kC4EncryptionKeySizeAES256; src += 2) {
if (!isxdigit(str[src]) || !isxdigit(str[src+1]))
return false;
*dst++ = (uint8_t)(16*digittoint(str[src]) + digittoint(str[src+1]));
}
key->algorithm = kC4EncryptionAES256;
return true;
}
#endif
void CBLiteTool::openDatabase(string pathStr, bool interactive) {
fixUpPath(pathStr);
auto [parentDir, dbName] = splitDBPath(pathStr);
if (dbName.empty())
fail("Database filename must have a '.cblite2' extension");
C4DatabaseConfig2 config = {slice(parentDir), _dbFlags};
C4Error err;
const C4Error kEncryptedDBError = {LiteCoreDomain, kC4ErrorNotADatabaseFile};
if (!_dbNeedsPassword) {
_db = c4db_openNamed(slice(dbName), &config, &err);
} else {
// If --encrypted flag given, skip opening db as unencrypted
err = kEncryptedDBError;
}
while (!_db && err == kEncryptedDBError) {
#ifdef COUCHBASE_ENTERPRISE
// Database is encrypted
if (!interactive && !_dbNeedsPassword) {
// Don't prompt for a password unless this is an interactive session
fail("Database is encrypted (use `--encrypted` flag to get a password prompt)");
}
const char *prompt = "Database password or hex key:";
if (config.encryptionKey.algorithm != kC4EncryptionNone)
prompt = "Sorry, try again: ";
string password = readPassword(prompt);
if (password.empty())
exit(1);
if (!setHexKey(&config.encryptionKey, password)
&& !c4key_setPassword(&config.encryptionKey, slice(password), kC4EncryptionAES256)) {
cout << "Error: Couldn't derive key from password\n";
continue;
}
_db = c4db_openNamed(slice(dbName), &config, &err);
#else
fail("Database is encrypted (Enterprise Edition is required to open encrypted databases)");
#endif
}
if (!_db) {
if (err.domain == LiteCoreDomain && err.code == kC4ErrorCantUpgradeDatabase
&& (_dbFlags & kC4DB_NoUpgrade)) {
fail("The database needs to be upgraded to be opened by this version of LiteCore.\n"
"**This will likely make it unreadable by earlier versions.**\n"
"To upgrade, add the `--upgrade` flag before the database path.\n"
"(Detailed error message", err);
}
fail(format("Couldn't open database %s", pathStr.c_str()), err);
}
_shouldCloseDB = true;
}
#pragma mark - COMMANDS:
void CBLiteTool::helpCommand() {
if (hasArgs()) {
string currentCommand = nextArg("subcommand");
auto subcommandInstance = this->subcommand(currentCommand);
if (subcommandInstance)
subcommandInstance->usage();
else
cerr << format("Unknown subcommand '%s'\n", currentCommand.c_str());
} else {
usage();
}
}
using ToolFactory = CBLiteCommand* (*)(CBLiteTool&);
static constexpr struct {const char* name; ToolFactory factory;} kSubcommands[] = {
{"cat", newCatCommand},
{"check", newCheckCommand},
{"compact", newCompactCommand},
{"cp", newCpCommand},
{"edit", newEditCommand},
{"export", newExportCommand},
{"file", newInfoCommand},
{"get", newCatCommand},
{"import", newImportCommand},
{"info", newInfoCommand},
{"log", newLogcatCommand},
{"logcat", newLogcatCommand},
{"ls", newListCommand},
{"open", newOpenCommand},
{"openremote", newOpenRemoteCommand},
{"pull", newPullCommand},
{"push", newPushCommand},
{"put", newPutCommand},
{"query", newQueryCommand},
{"reindex", newReindexCommand},
{"revs", newRevsCommand},
{"rm", newRmCommand},
{"SELECT", newSelectCommand},
{"select", newSelectCommand},
{"sql", newSQLCommand},
{"serve", newServeCommand},
#ifdef HAS_COLLECTIONS
{"cd", newCdCommand},
{"mkcoll", newMkCollCommand},
{"mv", newMvCommand},
#endif
#ifdef COUCHBASE_ENTERPRISE
{"decrypt", newDecryptCommand},
{"encrypt", newEncryptCommand},
#endif
};
unique_ptr<CBLiteCommand> CBLiteTool::subcommand(const string &name) {
for (const auto &entry : kSubcommands) {
if (name == entry.name) {
unique_ptr<CBLiteCommand> command( entry.factory(*this) );
command->setName(name);
return command;
}
}
return nullptr;
}
void CBLiteTool::addLineCompletions(ArgumentTokenizer &tokenizer,
std::function<void(const string&)> addCompletion)
{
string arg = tokenizer.argument();
if (!tokenizer.spaceAfterArgument()) {
// Incomplete subcommand name:
for (const auto &entry : kSubcommands) {
if (strncmp(arg.c_str(), entry.name, arg.size()) == 0)
addCompletion(string(entry.name) + " ");
}
} else {
// Instantiate subcommand and ask it to complete:
if (auto cmd = subcommand(arg)) {
tokenizer.next();
cmd->addLineCompletions(tokenizer, [&](const string &completion) {
// Prepend the previous arg to the subcommand's completion string:
addCompletion(arg + " " + completion);
});
}
}
}
|
/* This file is part of Jellyfish.
Jellyfish 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 version.
Jellyfish 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 Jellyfish. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __JELLYFISH_LARGE_HASH_ARRAY_HPP__
#define __JELLYFISH_LARGE_HASH_ARRAY_HPP__
#include <jellyfish/storage.hpp>
#include <jellyfish/atomic_gcc.hpp>
#include <jellyfish/allocators_mmap.hpp>
#include <jellyfish/offsets_key_value.hpp>
#include <jellyfish/misc.hpp>
#include <jellyfish/err.hpp>
#include <jellyfish/mer_dna.hpp>
#include <jellyfish/rectangular_binary_matrix.hpp>
#include <jellyfish/simple_circular_buffer.hpp>
#include <jellyfish/large_hash_iterator.hpp>
namespace jellyfish { namespace large_hash {
/* Contains an integer, the reprobe limit. It is capped based on the
* reprobe strategy to not be bigger than the size of the hash
* array. Also, the length to encode reprobe limit must not be larger
* than the length to encode _size.
*/
class reprobe_limit_t {
uint_t limit;
public:
reprobe_limit_t(uint_t _limit, const size_t *_reprobes, size_t _size) :
limit(_limit)
{
while(_reprobes[limit] >= _size && limit >= 1)
limit--;
}
inline uint_t val() const { return limit; }
};
// Key is any type with the following two methods: get_bits(unsigned
// int start, unsigned int len); and set_bits(unsigned int start,
// unsigned int len, uint64_t bits). These methods get and set the
// bits [start, start + len). Start and len may not be aligned to word
// boundaries. On the other hand, len is guaranteed to be <
// sizeof(uint64_t). I.e. never more than 1 word is fetched or set.
template<typename Key, typename word, typename atomic_t, typename Derived>
class array_base {
static const int wsize = std::numeric_limits<word>::digits; // Word size in bits
// Can't be done. Resort to an evil macro!
// static const word fmask = std::numeric_limits<word>::max(); // Mask full of ones
#define fmask (std::numeric_limits<word>::max())
public:
define_error_class(ErrorAllocation);
typedef word data_word;
typedef typename Offsets<word>::offset_t offset_t;
typedef struct offset_t::key key_offsets;
typedef struct offset_t::val val_offsets;
typedef Key key_type;
typedef uint64_t mapped_type;
typedef std::pair<Key&, mapped_type> value_type;
typedef stl_iterator_base<array_base> iterator;
typedef stl_iterator_base<array_base> const_iterator;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef value_type* pointer;
typedef const value_type* const_pointer;
typedef eager_iterator_base<array_base> eager_iterator;
typedef lazy_iterator_base<array_base> lazy_iterator;
typedef region_iterator_base<array_base> region_iterator;
/// Status of a (key,value) pair. LBSET means that the large bit is
/// set. Hence, it contains a pointer back to the original key and a
/// large value.
enum key_status { FILLED, EMPTY, LBSET};
protected:
uint16_t lsize_; // log of size
size_t size_, size_mask_;
reprobe_limit_t reprobe_limit_;
uint16_t key_len_; // Length of key in bits
uint16_t raw_key_len_; // Length of key stored raw (i.e. complement of implied length)
Offsets<word> offsets_; // key len reduced by size of hash array
size_t size_bytes_;
word * const data_;
atomic_t atomic_;
const size_t *reprobes_;
RectangularBinaryMatrix hash_matrix_;
RectangularBinaryMatrix hash_inverse_matrix_;
public:
/// Give information about memory usage and array size.
struct usage_info {
uint16_t key_len_, val_len_, reprobe_limit_;
const size_t* reprobes_;
usage_info(uint16_t key_len, uint16_t val_len, uint16_t reprobe_limit,
const size_t* reprobes = jellyfish::quadratic_reprobes) :
key_len_(key_len), val_len_(val_len), reprobe_limit_(reprobe_limit), reprobes_(reprobes) { }
/// Memory usage for a given size.
size_t mem(size_t size) {
uint16_t lsize(ceilLog2(size));
size_t asize((size_t)1 << lsize);
reprobe_limit_t areprobe_limit(reprobe_limit_, reprobes_, asize);
uint16_t raw_key_len(key_len_ > lsize ? key_len_ - lsize : 0);
Offsets<word> offsets(raw_key_len + bitsize(areprobe_limit.val() + 1), val_len_,
areprobe_limit.val() + 1);
return div_ceil(asize,
(size_t)offsets.block_len()) * offsets.block_word_len() * sizeof(word) + sizeof(array_base) + sizeof(Offsets<word>);
}
/// Actual size for a given size.
size_t asize(size_t size) { return (size_t)1 << ceilLog2(size); }
struct fit_in {
usage_info* i_;
size_t mem_;
fit_in(usage_info* i, size_t mem) : i_(i), mem_(mem) { }
bool operator()(uint16_t size_bits) const { return i_->mem((size_t)1 << size_bits) < mem_; }
};
/// Maximum size for a given maximum memory.
size_t size(size_t mem) { return (size_t)1 << size_bits(mem); }
/// Log of maximum size for a given maximum memory
uint16_t size_bits(size_t mem) {
uint16_t res = *binary_search_first_false(pointer_integer<uint16_t>(0), pointer_integer<uint16_t>(64),
fit_in(this, mem));
return res > 0 ? res - 1 : 0;
}
size_t size_bits_linear(size_t mem) {
fit_in predicate(this, mem);
uint16_t i = 0;
for( ; i < 64; ++i)
if(!predicate(i))
break;
return i > 0 ? i - 1 : 0;
}
};
array_base(size_t size, // Size of hash. To be rounded up to a power of 2
uint16_t key_len, // Size of key in bits
uint16_t val_len, // Size of val in bits
uint16_t reprobe_limit, // Maximum reprobe
RectangularBinaryMatrix m,
const size_t* reprobes = quadratic_reprobes) : // Reprobing policy
lsize_(ceilLog2(size)),
size_((size_t)1 << lsize_),
size_mask_(size_ - 1),
reprobe_limit_(reprobe_limit, reprobes, size_),
key_len_(key_len),
raw_key_len_(key_len_ > lsize_ ? key_len_ - lsize_ : 0),
offsets_(raw_key_len_ + bitsize(reprobe_limit_.val() + 1), val_len, reprobe_limit_.val() + 1),
size_bytes_(div_ceil(size_, (size_t)offsets_.block_len()) * offsets_.block_word_len() * sizeof(word)),
data_(static_cast<Derived*>(this)->alloc_data(size_bytes_)),
reprobes_(reprobes),
hash_matrix_(m),
hash_inverse_matrix_(hash_matrix_.pseudo_inverse())
{
if(!data_)
eraise(ErrorAllocation) << "Failed to allocate "
<< (div_ceil(size, (size_t)offsets_.block_len()) * offsets_.block_word_len() * sizeof(word))
<< " bytes of memory";
}
array_base(array_base&& ary) :
lsize_(ary.lsize_),
size_(ary.size_),
size_mask_(size_ - 1),
reprobe_limit_(ary.reprobe_limit_),
key_len_(ary.key_len_),
raw_key_len_(ary.raw_key_len_),
offsets_(std::move(ary.offsets_)),
size_bytes_(ary.size_bytes_),
data_(ary.data_),
reprobes_(ary.reprobes_),
hash_matrix_(std::move(ary.hash_matrix_)),
hash_inverse_matrix_(std::move(ary.hash_inverse_matrix_))
{ }
array_base& operator=(const array_base& rhs) = delete;
array_base& operator=(array_base&& rhs) = delete;
size_t size() const { return size_; }
size_t lsize() const { return lsize_; }
size_t size_mask() const { return size_mask_; }
uint_t key_len() const { return key_len_; }
uint_t val_len() const { return offsets_.val_len(); }
const size_t* reprobes() const { return reprobes_; }
uint_t max_reprobe() const { return reprobe_limit_.val(); }
size_t max_reprobe_offset() const { return reprobes_[reprobe_limit_.val()]; }
const RectangularBinaryMatrix& matrix() const { return hash_matrix_; }
const RectangularBinaryMatrix& inverse_matrix() const { return hash_inverse_matrix_; }
void matrix(const RectangularBinaryMatrix& m) {
hash_inverse_matrix_ = m.pseudo_inverse();
hash_matrix_ = m;
}
/**
* Clear hash table. Not thread safe.
*/
void clear() {
memset(data_, '\0', size_bytes_);
}
/**
* Write the hash table raw to a stream. Not thread safe.
*/
void write(std::ostream& os) const {
os.write((const char*)data_, size_bytes_);
}
size_t size_bytes() const { return size_bytes_; }
/* The storage of the hash is organized in "blocks". A (key,value)
* pair always start at bit 0 of the block. The following methods
* work with the blocks of the hash.
*/
/**
* Number of blocks needed to fit at least a given number of
* records. Given a number of records, it returns the number of
* blocks necessary and the actual number of records these blocks
* contain.
*/
std::pair<size_t, size_t> blocks_for_records(size_t nb_records) const {
return offsets_.blocks_for_records(nb_records);
}
/**
* Convert coordinate from (start, blen) given in blocks to
* coordinate in char* and length in bytes. It also makes sure that
* the pointer and length returned do not go beyond allocated
* memory.
*/
void block_to_ptr(const size_t start, const size_t blen,
char **start_ptr, size_t *memlen) const {
*start_ptr = (char *)(data_ + start * offsets_.block_word_len());
char *end_ptr = (char *)data_ + size_bytes_;
if(*start_ptr >= end_ptr) {
*memlen = 0;
return;
}
*memlen = blen * offsets_.block_word_len() * sizeof(word);
if(*start_ptr + *memlen > end_ptr)
*memlen = end_ptr - *start_ptr;
}
/**
* Zero out blocks in [start, start+length), where start and
* length are given in number of blocks.
**/
void zero_blocks(const size_t start, const size_t length) {
char *start_ptr;
size_t memlen;
block_to_ptr(start, length, &start_ptr, &memlen);
memset(start_ptr, '\0', memlen);
}
/**
* Use hash values as counters.
*
* The matrix multiplication gets only a uint64_t. The lsb of the
* matrix product, the hsb are assume to be equal to the key itself
* (the matrix has a partial identity on the first rows).
*
* In case of failure (false is returned), carry_shift contains the
* number of bits of the value that were successfully stored in the
* hash (low significant bits). If carry_shift == 0, then nothing
* was stored and the key is not in the hash at all. In that case,
* the value of *is_new and *id are not valid. If carry_shift > 0,
* then the key is present but the value stored is not correct
* (missing the high significant bits of value), but *is_new and *id
* contain the proper information.
*/
inline bool add(const key_type& key, mapped_type val, unsigned int* carry_shift, bool* is_new, size_t* id) {
uint64_t hash = hash_matrix_.times(key);
*carry_shift = 0;
return add_rec(hash & size_mask_, key, val, false, is_new, id, carry_shift);
}
inline bool add(const key_type& key, mapped_type val, unsigned int* carry_shift) {
bool is_new = false;
size_t id = 0;
return add(key, val, carry_shift, &is_new, &id);
}
inline bool add(const key_type& key, mapped_type val) {
unsigned int carry_shift = 0;
return add(key, val, &carry_shift);
}
inline bool set(const key_type& key) {
bool is_new;
size_t id;
return set(key, &is_new, &id);
}
bool set(const key_type& key, bool* is_new, size_t* id) {
word* w;
const offset_t* o;
*id = hash_matrix_.times(key) & size_mask_;
return claim_key(key, is_new, id, &o, &w);
}
/**
* Use hash values as counters, if already exists
*
* Add val to the value associated with key if key is already in the
* hash. Returns true if the update was done, false otherwise.
*/
inline bool update_add(const key_type& key, mapped_type val) {
key_type tmp_key;
unsigned int carry_shift;
return update_add(key, val, &carry_shift, tmp_key);
}
// Optimization. Use tmp_key as buffer. Avoids allocation if update_add is called repeatedly.
bool update_add(const key_type& key, mapped_type val, unsigned int* carry_shift, key_type& tmp_key) {
size_t id;
word* w;
const offset_t* o;
*carry_shift = 0;
if(get_key_id(key, &id, tmp_key, (const word**)&w, &o))
return add_rec_at(id, key, val, o, w, carry_shift);
return false;
}
// Get the value, stored in *val, associated with key. If the key is
// not found, false is returned, otherwise true is returned and *val
// is updated. If carry_bit is true, then the first bit of the key
// field indicates whether we should reprobe to get the complete
// value.
inline bool get_val_for_key(const key_type& key, mapped_type* val, bool carry_bit = false) const {
key_type tmp_key;
size_t id;
return get_val_for_key(key, val, tmp_key, &id, carry_bit);
}
// Optimization version. A tmp_key buffer is passed and the id where
// the key was found is return in *id. If get_val_for_key is called
// many times consecutively, it may be faster to pass the same
// tmp_key buffer instead of allocating it every time.
bool get_val_for_key(const key_type& key, mapped_type* val, key_type& tmp_key,
size_t* id, bool carry_bit = false) const {
const word* w;
const offset_t* o;
if(!get_key_id(key, id, tmp_key, &w, &o))
return false;
*val = get_val_at_id(*id, w, o, true, carry_bit);
return true;
}
// Return true if the key is present in the hash
inline bool has_key(const key_type& key) const {
size_t id;
return get_key_id(key, &id);
}
// Get the id of the key in the hash. Returns true if the key is
// found in the hash, false otherwise.
inline bool get_key_id(const key_type& key, size_t* id) const {
key_type tmp_key;
const word* w;
const offset_t* o;
return get_key_id(key, id, tmp_key, &w, &o);
}
// Optimization version where a tmp_key buffer is provided instead
// of being allocated. May be faster if many calls to get_key_id are
// made consecutively by passing the same tmp_key each time.
inline bool get_key_id(const key_type& key, size_t* id, key_type& tmp_key) const {
const word* w;
const offset_t* o;
return get_key_id(key, id, tmp_key, &w, &o);
}
protected:
// Information and methods to manage the prefetched data.
struct prefetch_info {
size_t id;
const word* w;
const offset_t *o, *lo;
};
typedef simple_circular_buffer::pre_alloc<prefetch_info, 8> prefetch_buffer;
void warm_up_cache(prefetch_buffer& buffer, size_t oid) const {
buffer.clear();
for(int i = 0; i < buffer.capacity(); ++i) {
buffer.push_back();
prefetch_info& info = buffer.back();
info.id = (oid + (i > 0 ? reprobes_[i] : 0)) & size_mask_;
info.w = offsets_.word_offset(info.id, &info.o, &info.lo, data_);
__builtin_prefetch(info.w + info.o->key.woff, 0, 1);
__builtin_prefetch(info.o, 0, 3);
}
}
void prefetch_next(prefetch_buffer& buffer, size_t oid, uint_t reprobe) const {
buffer.pop_front();
// if(reprobe + buffer.capacity() <= reprobe_limit_.val()) {
buffer.push_back();
prefetch_info& info = buffer.back();
info.id = (oid + reprobes_[reprobe + buffer.capacity() - 1]) & size_mask_;
info.w = offsets_.word_offset(info.id, &info.o, &info.lo, data_);
__builtin_prefetch(info.w + info.o->key.woff, 0, 1);
__builtin_prefetch(info.o, 0, 3);
// }
}
public:
// Optimization version again. Also return the word and the offset
// information where the key was found. These can be used later one
// to fetch the value associated with the key.
inline bool get_key_id(const key_type& key, size_t* id, key_type& tmp_key, const word** w, const offset_t** o) const {
return get_key_id(key, id, tmp_key, w, o, hash_matrix_.times(key) & size_mask_);
}
// Find the actual id of the key in the hash, starting at oid.
bool get_key_id(const key_type& key, size_t* id, key_type& tmp_key, const word** w, const offset_t** o, const size_t oid) const {
// This static_assert makes clang++ happy
static_assert(std::is_pod<prefetch_info>::value, "prefetch_info must be a POD");
prefetch_info info_ary[prefetch_buffer::capacity()];
prefetch_buffer buffer(info_ary);
warm_up_cache(buffer, oid);
for(uint_t reprobe = 0; reprobe <= reprobe_limit_.val(); ++reprobe) {
prefetch_info& info = buffer.front();
key_status st = get_key_at_id(info.id, tmp_key, info.w, info.o);
switch(st) {
case EMPTY:
return false;
case FILLED:
if(oid != tmp_key.get_bits(0, lsize_))
break;
tmp_key.template set_bits<false>(0, lsize_, key.get_bits(0, lsize_));
if(tmp_key != key)
break;
*id = info.id;
*w = info.w;
*o = info.o;
return true;
default:
break;
}
prefetch_next(buffer, oid, reprobe + 1);
} // for
return false;
}
//////////////////////////////
// Iterator
//////////////////////////////
const_iterator begin() { return const_iterator(this); }
const_iterator begin() const { return const_iterator(this); }
const_iterator end() { return const_iterator(); }
const_iterator end() const { return const_iterator(); }
/// Get a slice of an array as an iterator
template<typename Iterator>
Iterator iterator_slice(size_t index, size_t nb_slices) const {
std::pair<size_t, size_t> res = slice(index, nb_slices, size());
return Iterator(this, res.first, res.second);
}
template<typename Iterator>
Iterator iterator_all() const { return iterator_slice<Iterator>(0, 1); }
// See hash_counter.hpp for why we added this method. It should not
// be needed, but I can't get the thing to compile without :(.
eager_iterator eager_slice(size_t index, size_t nb_slices) const {
return iterator_slice<eager_iterator>(index, nb_slices);
}
region_iterator region_slice(size_t index, size_t nb_slices) const {
return iterator_slice<region_iterator>(index, nb_slices);
}
// Claim a key with the large bit not set. I.e. first entry for a key.
//
// id is input/output. Equal to hash & size_maks on input. Equal to
// actual id where key was set on output. key is already hash
// shifted and masked to get higher bits. (>> lsize & key_mask)
// is_new is set on output to true if key did not exists in hash
// before. *ao points to the actual offsets object and w to the word
// holding the value.
bool claim_key(const key_type& key, bool* is_new, size_t* id, const offset_t** _ao, word** _w) {
uint_t reprobe = 0;
const offset_t *o, *lo;
word *w, *kw, nkey;
bool key_claimed = false;
size_t cid = *id;
// Akey contains first word of what to store in the key
// field. I.e. part of the original key (the rest is encoded in
// the original position) and the reprobe value to substract from
// the actual position to get to the original position.
//
// MSB LSB
// +--------------+-------------+
// | MSB of key | reprobe |
// + -------------+-------------+
// raw_key_len reprobe_len
//
// Akey is updated at every operation to reflect the current
// reprobe value. nkey is the temporary word containing the part
// to be stored in the current word kw (+ some offset).
word akey = 1; // start reprobe value == 0. Store reprobe value + 1
const int to_copy = std::min((uint16_t)(wsize - offsets_.reprobe_len()), raw_key_len_);
const int implied_copy = std::min(key_len_, lsize_);
akey |= key.get_bits(implied_copy, to_copy) << offsets_.reprobe_len();
const int abits_copied = implied_copy + to_copy; // Bits from original key already copied, explicitly or implicitly
do {
int bits_copied = abits_copied;
w = offsets_.word_offset(cid, &o, &lo, data_);
kw = w + o->key.woff;
if(o->key.sb_mask1) { // key split on multiple words
nkey = akey << o->key.boff;
nkey |= o->key.sb_mask1;
nkey &= o->key.mask1;
key_claimed = set_key(kw, nkey, o->key.mask1, o->key.mask1, is_new);
if(key_claimed) {
nkey = akey >> o->key.shift;
if(o->key.full_words) {
// Copy full words. First one is special
nkey |= key.get_bits(bits_copied, o->key.shift - 1) << (wsize - o->key.shift);
bits_copied += o->key.shift - 1;
nkey |= o->key.sb_mask1; // Set bit is MSB
int copied_full_words = 1;
key_claimed = set_key(kw + copied_full_words, nkey, fmask, fmask, is_new);
// Copy more full words if needed
while(bits_copied + wsize - 1 <= key_len_ && key_claimed) {
nkey = key.get_bits(bits_copied, wsize - 1);
bits_copied += wsize - 1;
nkey |= o->key.sb_mask1;
copied_full_words += 1;
key_claimed = set_key(kw + copied_full_words, nkey, fmask, fmask, is_new);
}
assert(!key_claimed || (bits_copied < key_len_) == (o->key.sb_mask2 != 0));
if(o->key.sb_mask2 && key_claimed) { // Copy last word
nkey = key.get_bits(bits_copied, key_len_ - bits_copied);
nkey |= o->key.sb_mask2;
copied_full_words += 1;
key_claimed = set_key(kw + copied_full_words, nkey, o->key.mask2, o->key.mask2, is_new);
}
} else if(o->key.sb_mask2) { // if bits_copied + wsize - 1 < key_len
// Copy last word, no full words copied
nkey |= key.get_bits(bits_copied, key_len_ - bits_copied) << (wsize - o->key.shift);
nkey |= o->key.sb_mask2;
nkey &= o->key.mask2;
key_claimed = set_key(kw + 1, nkey, o->key.mask2, o->key.mask2, is_new);
}
} // if(key_claimed)
} else { // key on one word
nkey = akey << o->key.boff;
nkey &= o->key.mask1;
key_claimed = set_key(kw, nkey, o->key.mask1, o->key.mask1, is_new);
}
if(!key_claimed) { // reprobe
if(++reprobe > reprobe_limit_.val())
return false;
cid = (*id + reprobes_[reprobe]) & size_mask_;
akey = (akey & ~offsets_.reprobe_mask()) | (reprobe + 1);
}
} while(!key_claimed);
*id = cid;
*_w = w;
*_ao = o;
return true;
}
// Claim large key. Enter an entry for a key when it is not the
// first entry. Only encode the number of reprobe hops back to the
// first entry of the key in the hash table. It is simpler as can
// takes less than one word in length.
bool claim_large_key(size_t* id, const offset_t** _ao, word** _w) {
uint_t reprobe = 0;
size_t cid = *id;
const offset_t *o, *lo;
word *w, *kw, nkey;
bool key_claimed = false;
do {
w = offsets_.word_offset(cid, &o, &lo, data_);
kw = w + lo->key.woff;
if(lo->key.sb_mask1) { // key split on multiple words
nkey = (reprobe << lo->key.boff) | lo->key.sb_mask1 | lo->key.lb_mask;
nkey &= lo->key.mask1;
// Use o->key.mask1 and not lo->key.mask1 as the first one is
// guaranteed to be bigger. The key needs to be free on its
// longer mask to claim it!
key_claimed = set_key(kw, nkey, o->key.mask1, lo->key.mask1);
if(key_claimed) {
nkey = (reprobe >> lo->key.shift) | lo->key.sb_mask2;
nkey &= lo->key.mask2;
key_claimed = set_key(kw + 1, nkey, o->key.full_words ? fmask : o->key.mask2, lo->key.mask2);
}
} else { // key on 1 word
nkey = (reprobe << lo->key.boff) | lo->key.lb_mask;
nkey &= lo->key.mask1;
key_claimed = set_key(kw, nkey, o->key.mask1, lo->key.mask1);
}
if(!key_claimed) { //reprobe
if(++reprobe > reprobe_limit_.val())
return false;
cid = (*id + reprobes_[reprobe]) & size_mask_;
}
} while(!key_claimed);
*id = cid;
*_w = w;
*_ao = lo;
return true;
}
// Add val to key. id is the starting place (result of hash
// computation). eid is set to the effective place in the
// array. large is set to true is setting a large key (upon
// recurrence if there is a carry).
bool add_rec(size_t id, const key_type& key, word val, bool large, bool* is_new, size_t* eid, unsigned int* carry_shift) {
const offset_t *ao = 0;
word *w = 0;
bool claimed = false;
if(large)
claimed = claim_large_key(&id, &ao, &w);
else
claimed = claim_key(key, is_new, &id, &ao, &w);
if(!claimed)
return false;
*eid = id;
return add_rec_at(id, key, val, ao, w, carry_shift);
}
bool add_rec_at(size_t id, const key_type& key, word val, const offset_t* ao, word* w, unsigned int* carry_shift) {
// Increment value
word *vw = w + ao->val.woff;
word cary = add_val(vw, val, ao->val.boff, ao->val.mask1);
cary >>= ao->val.shift;
*carry_shift += ao->val.shift;
if(cary && ao->val.mask2) { // value split on two words
cary = add_val(vw + 1, cary, 0, ao->val.mask2);
cary >>= ao->val.cshift;
*carry_shift += ao->val.cshift;
}
if(!cary)
return true;
id = (id + reprobes_[0]) & size_mask_;
size_t ignore_eid;
bool ignore_is_new;
return add_rec(id, key, cary, true, &ignore_is_new, &ignore_eid, carry_shift);
// // Adding failed, table is full. Need to back-track and
// // substract val.
// std::cerr << "Failed to add large part of value -> return false\n";
// cary = add_val(vw, ((word)1 << offsets_.val_len()) - val,
// ao->val.boff, ao->val.mask1);
// cary >>= ao->val.shift;
// if(cary && ao->val.mask2) {
// // Can I ignore the cary here? Table is known to be full, so
// // not much of a choice. But does it leave the table in a
// // consistent state?
// add_val(vw + 1, cary, 0, ao->val.mask2);
// }
// return false;
}
// Atomic methods to set the key. Attempt to set nkey in word w. All
// bits matching free_mask must be unset and the bits matching
// equal_mask must be equal for a success in setting the key. Set
// is_new to true if the spot was previously empty. Otherwise, if
// is_new is false but true is returned, the key was already present
// at that spot.
inline bool set_key(word *w, word nkey, word free_mask, word equal_mask, bool *is_new) {
word ow = *w, nw, okey;
okey = ow & free_mask;
while(okey == 0) { // large bit not set && key is free
nw = atomic_.cas(w, ow, ow | nkey);
if(nw == ow) {
*is_new = true;
return true;
}
ow = nw;
okey = ow & free_mask;
}
*is_new = false;
return (ow & equal_mask) == nkey;
}
inline bool set_key(word *w, word nkey, word free_mask, word equal_mask) {
bool is_new;
return set_key(w, nkey, free_mask, equal_mask, &is_new);
}
// Add val the value in word w, with shift and mask giving the
// particular part of the word in which the value is stored. The
// return value is the carry.
inline word add_val(word *w, word val, uint_t shift, word mask) {
word now = *w, ow, nw, nval;
do {
ow = now;
nval = ((ow & mask) >> shift) + val;
nw = (ow & ~mask) | ((nval << shift) & mask);
now = atomic_.cas(w, ow, nw);
} while(now != ow);
return nval & (~(mask >> shift));
}
// Return the key and value at position id. If the slot at id is
// empty or has the large bit set, returns false. Otherwise, returns
// the key and the value is the sum of all the entries in the hash
// table for that key. I.e., the table is search forward for entries
// with large bit set pointing back to the key at id, and all those
// values are summed up.
key_status get_key_val_at_id(size_t id, key_type& key, word& val, const bool carry_bit = false) const {
const word* w;
const offset_t* o;
key_status st = get_key_at_id(id, key, &w, &o);
if(st != FILLED)
return st;
val = get_val_at_id(id, w, o, true, carry_bit);
return FILLED;
}
// Get a the key at the given id. It also returns the word and
// offset information in w and o. The return value is EMPTY (no key
// at id), FILLED (there is a key at id), LBSET (the large bit is
// set, hence the key is only a pointer back to the real key).
//
// The key returned contains the original id in the hash as its
// lsize_ lsb bits. To obtain the full key, one needs to compute the
// product with the inverse matrix to get the lsb bits.
inline key_status get_key_at_id(size_t id, key_type& key, const word** w, const offset_t** o) const {
const offset_t *lo;
*w = offsets_.word_offset(id, o, &lo, data_);
return get_key_at_id(id, key, *w, *o);
}
// Sam as above, but it assume that the word w and o for id have
// already be computed (like already prefetched).
key_status get_key_at_id(size_t id, key_type&key, const word* w, const offset_t* o) const {
const word* kvw = w + o->key.woff;
word key_word = *kvw;
word kreprobe = 0;
const key_offsets& key_o = o->key;
if(key_word & key_o.lb_mask)
return LBSET;
const int implied_copy = std::min(lsize_, key_len_);
int bits_copied = implied_copy;
if(key_o.sb_mask1) {
if((key_word & key_o.sb_mask1) == 0)
return EMPTY;
kreprobe = (key_word & key_o.mask1 & ~key_o.sb_mask1) >> key_o.boff;
if(key_o.full_words) {
// Copy full words. First one is special
key_word = *(kvw + 1);
if(offsets_.reprobe_len() < key_o.shift) {
key.set_bits(bits_copied, key_o.shift - offsets_.reprobe_len(), kreprobe >> offsets_.reprobe_len());
bits_copied += key_o.shift - offsets_.reprobe_len();
kreprobe &= offsets_.reprobe_mask();
key.set_bits(bits_copied, wsize - 1, key_word & ~key_o.sb_mask1);
bits_copied += wsize - 1;
} else {
int reprobe_left = offsets_.reprobe_len() - key_o.shift;
kreprobe |= (key_word & (((word)1 << reprobe_left) - 1)) << key_o.shift;
key.set_bits(bits_copied, wsize - 1 - reprobe_left, (key_word & ~key_o.sb_mask1) >> reprobe_left);
bits_copied += wsize - 1 - reprobe_left;
}
int word_copied = 2;
while(bits_copied + wsize - 1 <= key_len_) {
key.set_bits(bits_copied, wsize - 1, *(kvw + word_copied++) & (fmask >> 1));
bits_copied += wsize - 1;
}
if(key_o.sb_mask2)
key.set_bits(bits_copied, key_len_ - bits_copied, *(kvw + word_copied) & key_o.mask2 & ~key_o.sb_mask2);
} else if(key_o.sb_mask2) { // if(bits_copied + wsize - 1 < key_len
// Two words but no full words
key_word = *(kvw + 1) & key_o.mask2 & ~key_o.sb_mask2;
if(offsets_.reprobe_len() < key_o.shift) {
key.set_bits(bits_copied, key_o.shift - offsets_.reprobe_len(), kreprobe >> offsets_.reprobe_len());
bits_copied += key_o.shift - offsets_.reprobe_len();
kreprobe &= offsets_.reprobe_mask();
key.set_bits(bits_copied, key_len_ - bits_copied, key_word);
} else {
int reprobe_left = offsets_.reprobe_len() - key_o.shift;
kreprobe |= (key_word & (((word)1 << reprobe_left) - 1)) << key_o.shift;
key.set_bits(bits_copied, key_len_ - bits_copied, key_word >> reprobe_left);
}
}
} else { // if(key_o.sb_mask1
// Everything in 1 word
key_word = (key_word & key_o.mask1) >> key_o.boff;
if(key_word == 0)
return EMPTY;
kreprobe = key_word & offsets_.reprobe_mask();
key.set_bits(bits_copied, raw_key_len_, key_word >> offsets_.reprobe_len());
}
// Compute missing oid so that the original key can be computed
// back through the inverse matrix. Although the key may have a
// length of key_len_, which may be less than lsize_, assume that
// it still fit here as lsize_ is less than a word length. Need all lsize_.
size_t oid = id; // Original id
if(kreprobe > 1)
oid -= reprobes_[kreprobe - 1];
oid &= size_mask_;
// Can use more bits than mer size. That's OK, will fix it later
// when computing the actual mers by computing the product with
// the inverse matrix.
key.template set_bits<0>(0, lsize_, oid);
return FILLED;
}
word get_val_at_id(const size_t id, const word* w, const offset_t* o, const bool reprobe = true,
const bool carry_bit = false) const {
word val = 0;
if(val_len() == 0)
return val;
// First part of value
const word* kvw = w + o->val.woff;
val = ((*kvw) & o->val.mask1) >> o->val.boff;
if(o->val.mask2)
val |= ((*(kvw+1)) & o->val.mask2) << o->val.shift;
// Do we want to get the large value
bool do_reprobe = reprobe;
if(carry_bit && do_reprobe) {
do_reprobe = do_reprobe && (val & 0x1);
val >>= 1;
}
if(!do_reprobe)
return val;
return resolve_val_rec((id + reprobes_[0]) & size_mask_, val, carry_bit);
}
word resolve_val_rec(const size_t id, word val, const bool carry_bit, const uint_t overflows = 0) const {
uint_t reprobe = 0;
size_t cid = id;
while(reprobe <= reprobe_limit_.val()) {
const offset_t *o, *lo;
const word* w = offsets_.word_offset(cid, &o, &lo, data_);
const word* kw = w + o->key.woff;
word nkey = *kw;
const key_offsets& lkey = lo->key;
if(nkey & lkey.lb_mask) {
// If the large bit is set, the size of the key (reprobe_len)
// is guaranteed to have a length of at most 1 word.
if(lkey.sb_mask1) {
nkey = (nkey & lkey.mask1 & ~lkey.sb_mask1) >> lkey.boff;
nkey |= ((*(kw+1)) & lkey.mask2 & ~lkey.sb_mask2) << lkey.shift;
} else {
nkey = (nkey & lkey.mask1) >> lkey.boff;
}
if(nkey == reprobe) {
const val_offsets& lval = lo->val;
const word* vw = w + lval.woff;
word nval = ((*vw) & lval.mask1) >> lval.boff;
if(lval.mask2)
nval |= ((*(vw+1)) & lval.mask2) << lval.shift;
bool do_reprobe = true;
if(carry_bit) {
do_reprobe = nval & 0x1;
nval >>= 1;
}
nval <<= offsets_.val_len();
nval <<= offsets_.lval_len() * overflows;
val += nval;
if(!do_reprobe)
return val;
return resolve_val_rec((cid + reprobes_[0]) & size_mask_, val, carry_bit, overflows + 1);
}
} else if((nkey & o->key.mask1) == 0) {
break;
}
cid = (id + reprobes_[++reprobe]) & size_mask_;
}
return val;
}
};
template<typename Key, typename word = uint64_t, typename atomic_t = ::atomic::gcc, typename mem_block_t = ::allocators::mmap>
class array :
protected mem_block_t,
public array_base<Key, word, atomic_t, array<Key, word, atomic_t, mem_block_t> >
{
typedef array_base<Key, word, atomic_t, array<Key, word, atomic_t, mem_block_t> > super;
friend class array_base<Key, word, atomic_t, array<Key, word, atomic_t, mem_block_t> >;
public:
array(size_t size, // Size of hash. To be rounded up to a power of 2
uint16_t key_len, // Size of key in bits
uint16_t val_len, // Size of val in bits
uint16_t reprobe_limit, // Maximum reprobe
const size_t* reprobes = quadratic_reprobes) : // Reprobing policy
mem_block_t(),
super(size, key_len, val_len, reprobe_limit, RectangularBinaryMatrix(ceilLog2(size), key_len).randomize_pseudo_inverse(),
reprobes)
{ }
protected:
word* alloc_data(size_t s) {
mem_block_t::realloc(s);
return (word*)mem_block_t::get_ptr();
}
};
struct ptr_info {
void* ptr_;
size_t bytes_;
ptr_info(void* ptr, size_t bytes) : ptr_(ptr), bytes_(bytes) { }
};
template<typename Key, typename word = uint64_t, typename atomic_t = ::atomic::gcc>
class array_raw :
protected ptr_info,
public array_base<Key, word, atomic_t, array<Key, word, atomic_t> >
{
typedef array_base<Key, word, atomic_t, array<Key, word, atomic_t> > super;
friend class array_base<Key, word, atomic_t, array<Key, word, atomic_t> >;
public:
array_raw(void* ptr,
size_t bytes, // Memory available at ptr
size_t size, // Size of hash in number of entries. To be rounded up to a power of 2
uint16_t key_len, // Size of key in bits
uint16_t val_len, // Size of val in bits
uint16_t reprobe_limit, // Maximum reprobe
RectangularBinaryMatrix m,
const size_t* reprobes = quadratic_reprobes) : // Reprobing policy
ptr_info(ptr, bytes),
super(size, key_len, val_len, reprobe_limit, m, reprobes)
{ }
protected:
word* alloc_data(size_t s) {
assert(bytes_ == s);
return (word*)ptr_;
}
};
} } // namespace jellyfish { namespace large_hash_array
#endif /* __JELLYFISH_LARGE_HASH_ARRAY_HPP__ */
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync/test/integration/sync_test.h"
#include <vector>
#include "base/basictypes.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/stringprintf.h"
#include "base/synchronization/waitable_event.h"
#include "base/test/test_timeouts.h"
#include "base/threading/platform_thread.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/password_manager/encryptor.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/search_engines/template_url_service.h"
#include "chrome/browser/search_engines/template_url_service_factory.h"
#include "chrome/browser/sync/profile_sync_service_factory.h"
#include "chrome/browser/sync/profile_sync_service_harness.h"
#include "chrome/browser/sync/test/integration/sync_datatype_helper.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/net/gaia/gaia_urls.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/url_fetcher.h"
#include "content/public/common/url_fetcher_delegate.h"
#include "content/test/test_browser_thread.h"
#include "content/test/test_url_fetcher_factory.h"
#include "googleurl/src/gurl.h"
#include "net/base/escape.h"
#include "net/base/load_flags.h"
#include "net/base/network_change_notifier.h"
#include "net/proxy/proxy_config.h"
#include "net/proxy/proxy_config_service_fixed.h"
#include "net/proxy/proxy_service.h"
#include "net/test/test_server.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
#include "net/url_request/url_request_status.h"
#include "sync/notifier/p2p_notifier.h"
#include "sync/protocol/sync.pb.h"
using content::BrowserThread;
namespace switches {
const char kPasswordFileForTest[] = "password-file-for-test";
const char kSyncUserForTest[] = "sync-user-for-test";
const char kSyncPasswordForTest[] = "sync-password-for-test";
const char kSyncServerCommandLine[] = "sync-server-command-line";
}
namespace {
// The URLs for different calls in the Google Accounts programmatic login API.
const char kClientLoginUrl[] = "https://www.google.com/accounts/ClientLogin";
const char kGetUserInfoUrl[] = "https://www.google.com/accounts/GetUserInfo";
const char kIssueAuthTokenUrl[] =
"https://www.google.com/accounts/IssueAuthToken";
const char kSearchDomainCheckUrl[] =
"https://www.google.com/searchdomaincheck?format=domain&type=chrome";
const char kOAuth2LoginTokenValidResponse[] =
"{"
" \"refresh_token\": \"rt1\","
" \"access_token\": \"at1\","
" \"expires_in\": 3600,"
" \"token_type\": \"Bearer\""
"}";
}
// Helper class that checks whether a sync test server is running or not.
class SyncServerStatusChecker : public content::URLFetcherDelegate {
public:
SyncServerStatusChecker() : running_(false) {}
virtual void OnURLFetchComplete(const content::URLFetcher* source) {
std::string data;
source->GetResponseAsString(&data);
running_ =
(source->GetStatus().status() == net::URLRequestStatus::SUCCESS &&
source->GetResponseCode() == 200 && data.find("ok") == 0);
MessageLoop::current()->Quit();
}
bool running() const { return running_; }
private:
bool running_;
};
void SetProxyConfigCallback(
base::WaitableEvent* done,
net::URLRequestContextGetter* url_request_context_getter,
const net::ProxyConfig& proxy_config) {
net::ProxyService* proxy_service =
url_request_context_getter->GetURLRequestContext()->proxy_service();
proxy_service->ResetConfigService(
new net::ProxyConfigServiceFixed(proxy_config));
done->Signal();
}
SyncTest::SyncTest(TestType test_type)
: sync_server_(net::TestServer::TYPE_SYNC,
net::TestServer::kLocalhost,
FilePath()),
test_type_(test_type),
server_type_(SERVER_TYPE_UNDECIDED),
num_clients_(-1),
use_verifier_(true),
notifications_enabled_(true),
test_server_handle_(base::kNullProcessHandle),
number_of_default_sync_items_(0) {
sync_datatype_helper::AssociateWithTest(this);
switch (test_type_) {
case SINGLE_CLIENT: {
num_clients_ = 1;
break;
}
case TWO_CLIENT: {
num_clients_ = 2;
break;
}
case MULTIPLE_CLIENT: {
num_clients_ = 3;
break;
}
}
}
SyncTest::~SyncTest() {}
void SyncTest::SetUp() {
CommandLine* cl = CommandLine::ForCurrentProcess();
if (cl->HasSwitch(switches::kPasswordFileForTest)) {
ReadPasswordFile();
} else if (cl->HasSwitch(switches::kSyncUserForTest) &&
cl->HasSwitch(switches::kSyncPasswordForTest)) {
username_ = cl->GetSwitchValueASCII(switches::kSyncUserForTest);
password_ = cl->GetSwitchValueASCII(switches::kSyncPasswordForTest);
} else {
SetupMockGaiaResponses();
}
if (!cl->HasSwitch(switches::kSyncServiceURL) &&
!cl->HasSwitch(switches::kSyncServerCommandLine)) {
// If neither a sync server URL nor a sync server command line is
// provided, start up a local python sync test server and point Chrome
// to its URL. This is the most common configuration, and the only
// one that makes sense for most developers.
server_type_ = LOCAL_PYTHON_SERVER;
} else if (cl->HasSwitch(switches::kSyncServiceURL) &&
cl->HasSwitch(switches::kSyncServerCommandLine)) {
// If a sync server URL and a sync server command line are provided,
// start up a local sync server by running the command line. Chrome
// will connect to the server at the URL that was provided.
server_type_ = LOCAL_LIVE_SERVER;
} else if (cl->HasSwitch(switches::kSyncServiceURL) &&
!cl->HasSwitch(switches::kSyncServerCommandLine)) {
// If a sync server URL is provided, but not a server command line,
// it is assumed that the server is already running. Chrome will
// automatically connect to it at the URL provided. There is nothing
// to do here.
server_type_ = EXTERNAL_LIVE_SERVER;
} else {
// If a sync server command line is provided, but not a server URL,
// we flag an error.
LOG(FATAL) << "Can't figure out how to run a server.";
}
if (username_.empty() || password_.empty())
LOG(FATAL) << "Cannot run sync tests without GAIA credentials.";
// Mock the Mac Keychain service. The real Keychain can block on user input.
#if defined(OS_MACOSX)
Encryptor::UseMockKeychain(true);
#endif
// Yield control back to the InProcessBrowserTest framework.
InProcessBrowserTest::SetUp();
}
void SyncTest::TearDown() {
// Allow the InProcessBrowserTest framework to perform its tear down.
InProcessBrowserTest::TearDown();
// Stop the local python test server. This is a no-op if one wasn't started.
TearDownLocalPythonTestServer();
// Stop the local sync test server. This is a no-op if one wasn't started.
TearDownLocalTestServer();
}
void SyncTest::SetUpCommandLine(CommandLine* cl) {
AddTestSwitches(cl);
AddOptionalTypesToCommandLine(cl);
}
void SyncTest::AddTestSwitches(CommandLine* cl) {
// TODO(rsimha): Until we implement a fake Tango server against which tests
// can run, we need to set the --sync-notification-method to "p2p".
if (!cl->HasSwitch(switches::kSyncNotificationMethod))
cl->AppendSwitchASCII(switches::kSyncNotificationMethod, "p2p");
// Disable non-essential access of external network resources.
if (!cl->HasSwitch(switches::kDisableBackgroundNetworking))
cl->AppendSwitch(switches::kDisableBackgroundNetworking);
}
void SyncTest::AddOptionalTypesToCommandLine(CommandLine* cl) {
// TODO(sync): Remove this once sessions sync is enabled by default.
if (!cl->HasSwitch(switches::kEnableSyncTabs))
cl->AppendSwitch(switches::kEnableSyncTabs);
}
// static
Profile* SyncTest::MakeProfile(const FilePath::StringType name) {
FilePath path;
PathService::Get(chrome::DIR_USER_DATA, &path);
path = path.Append(name);
if (!file_util::PathExists(path))
CHECK(file_util::CreateDirectory(path));
Profile* profile =
Profile::CreateProfile(path, NULL, Profile::CREATE_MODE_SYNCHRONOUS);
g_browser_process->profile_manager()->RegisterTestingProfile(profile, true);
return profile;
}
Profile* SyncTest::GetProfile(int index) {
if (profiles_.empty())
LOG(FATAL) << "SetupClients() has not yet been called.";
if (index < 0 || index >= static_cast<int>(profiles_.size()))
LOG(FATAL) << "GetProfile(): Index is out of bounds.";
return profiles_[index];
}
Browser* SyncTest::GetBrowser(int index) {
if (browsers_.empty())
LOG(FATAL) << "SetupClients() has not yet been called.";
if (index < 0 || index >= static_cast<int>(browsers_.size()))
LOG(FATAL) << "GetBrowser(): Index is out of bounds.";
return browsers_[index];
}
ProfileSyncServiceHarness* SyncTest::GetClient(int index) {
if (clients_.empty())
LOG(FATAL) << "SetupClients() has not yet been called.";
if (index < 0 || index >= static_cast<int>(clients_.size()))
LOG(FATAL) << "GetClient(): Index is out of bounds.";
return clients_[index];
}
Profile* SyncTest::verifier() {
if (verifier_ == NULL)
LOG(FATAL) << "SetupClients() has not yet been called.";
return verifier_;
}
void SyncTest::DisableVerifier() {
use_verifier_ = false;
}
bool SyncTest::SetupClients() {
if (num_clients_ <= 0)
LOG(FATAL) << "num_clients_ incorrectly initialized.";
if (!profiles_.empty() || !browsers_.empty() || !clients_.empty())
LOG(FATAL) << "SetupClients() has already been called.";
// Start up a sync test server if one is needed.
SetUpTestServerIfRequired();
// Create the required number of sync profiles, browsers and clients.
profiles_.resize(num_clients_);
browsers_.resize(num_clients_);
clients_.resize(num_clients_);
for (int i = 0; i < num_clients_; ++i) {
InitializeInstance(i);
}
// Create the verifier profile.
verifier_ = MakeProfile(FILE_PATH_LITERAL("Verifier"));
ui_test_utils::WaitForBookmarkModelToLoad(verifier()->GetBookmarkModel());
ui_test_utils::WaitForTemplateURLServiceToLoad(
TemplateURLServiceFactory::GetForProfile(verifier()));
return (verifier_ != NULL);
}
void SyncTest::InitializeInstance(int index) {
profiles_[index] = MakeProfile(
base::StringPrintf(FILE_PATH_LITERAL("Profile%d"), index));
EXPECT_FALSE(GetProfile(index) == NULL) << "Could not create Profile "
<< index << ".";
browsers_[index] = Browser::Create(GetProfile(index));
EXPECT_FALSE(GetBrowser(index) == NULL) << "Could not create Browser "
<< index << ".";
clients_[index] = new ProfileSyncServiceHarness(GetProfile(index),
username_,
password_);
EXPECT_FALSE(GetClient(index) == NULL) << "Could not create Client "
<< index << ".";
ui_test_utils::WaitForBookmarkModelToLoad(
GetProfile(index)->GetBookmarkModel());
ui_test_utils::WaitForTemplateURLServiceToLoad(
TemplateURLServiceFactory::GetForProfile(GetProfile(index)));
}
void SyncTest::RestartSyncService(int index) {
DVLOG(1) << "Restarting profile sync service for profile " << index << ".";
delete clients_[index];
Profile* profile = GetProfile(index);
ProfileSyncService* service =
ProfileSyncServiceFactory::GetForProfile(profile);
service->ResetForTest();
clients_[index] = new ProfileSyncServiceHarness(profile,
username_,
password_);
service->Initialize();
GetClient(index)->AwaitSyncRestart();
}
bool SyncTest::SetupSync() {
// Create sync profiles and clients if they haven't already been created.
if (profiles_.empty()) {
if (!SetupClients())
LOG(FATAL) << "SetupClients() failed.";
}
// Sync each of the profiles.
for (int i = 0; i < num_clients_; ++i) {
if (!GetClient(i)->SetupSync())
LOG(FATAL) << "SetupSync() failed.";
}
// Because clients may modify sync data as part of startup (for example local
// session-releated data is rewritten), we need to ensure all startup-based
// changes have propagated between the clients.
AwaitQuiescence();
// The number of default entries is the number of entries existing after
// sync startup excluding top level folders and other permanent items.
// This value must be updated whenever new permanent items are added (although
// this should handle new datatype-specific top level folders).
number_of_default_sync_items_ = GetClient(0)->GetNumEntries() -
GetClient(0)->GetNumDatatypes() - 7;
DVLOG(1) << "Setting " << number_of_default_sync_items_ << " as default "
<< " number of entries.";
return true;
}
void SyncTest::CleanUpOnMainThread() {
// Close all browser windows.
BrowserList::CloseAllBrowsers();
ui_test_utils::RunAllPendingInMessageLoop();
// All browsers should be closed at this point, or else we could see memory
// corruption in QuitBrowser().
CHECK_EQ(0U, BrowserList::size());
clients_.reset();
}
void SyncTest::SetUpInProcessBrowserTestFixture() {
// We don't take a reference to |resolver|, but mock_host_resolver_override_
// does, so effectively assumes ownership.
net::RuleBasedHostResolverProc* resolver =
new net::RuleBasedHostResolverProc(host_resolver());
resolver->AllowDirectLookup("*.google.com");
// On Linux, we use Chromium's NSS implementation which uses the following
// hosts for certificate verification. Without these overrides, running the
// integration tests on Linux causes error as we make external DNS lookups.
resolver->AllowDirectLookup("*.thawte.com");
resolver->AllowDirectLookup("*.geotrust.com");
resolver->AllowDirectLookup("*.gstatic.com");
mock_host_resolver_override_.reset(
new net::ScopedDefaultHostResolverProc(resolver));
}
void SyncTest::TearDownInProcessBrowserTestFixture() {
mock_host_resolver_override_.reset();
}
void SyncTest::ReadPasswordFile() {
CommandLine* cl = CommandLine::ForCurrentProcess();
password_file_ = cl->GetSwitchValuePath(switches::kPasswordFileForTest);
if (password_file_.empty())
LOG(FATAL) << "Can't run live server test without specifying --"
<< switches::kPasswordFileForTest << "=<filename>";
std::string file_contents;
file_util::ReadFileToString(password_file_, &file_contents);
ASSERT_NE(file_contents, "") << "Password file \""
<< password_file_.value() << "\" does not exist.";
std::vector<std::string> tokens;
std::string delimiters = "\r\n";
Tokenize(file_contents, delimiters, &tokens);
ASSERT_EQ(2U, tokens.size()) << "Password file \""
<< password_file_.value()
<< "\" must contain exactly two lines of text.";
username_ = tokens[0];
password_ = tokens[1];
}
void SyncTest::SetupMockGaiaResponses() {
username_ = "user@gmail.com";
password_ = "password";
factory_.reset(new URLFetcherImplFactory());
fake_factory_.reset(new FakeURLFetcherFactory(factory_.get()));
fake_factory_->SetFakeResponse(kClientLoginUrl, "SID=sid\nLSID=lsid", true);
fake_factory_->SetFakeResponse(kGetUserInfoUrl, "email=user@gmail.com", true);
fake_factory_->SetFakeResponse(kIssueAuthTokenUrl, "auth", true);
fake_factory_->SetFakeResponse(kSearchDomainCheckUrl, ".google.com", true);
fake_factory_->SetFakeResponse(
GaiaUrls::GetInstance()->client_login_to_oauth2_url(),
"some_response",
true);
fake_factory_->SetFakeResponse(
GaiaUrls::GetInstance()->oauth2_token_url(),
kOAuth2LoginTokenValidResponse,
true);
}
// Start up a local sync server based on the value of server_type_, which
// was determined from the command line parameters.
void SyncTest::SetUpTestServerIfRequired() {
if (server_type_ == LOCAL_PYTHON_SERVER) {
if (!SetUpLocalPythonTestServer())
LOG(FATAL) << "Failed to set up local python sync and XMPP servers";
} else if (server_type_ == LOCAL_LIVE_SERVER) {
// Using mock gaia credentials requires the use of a mock XMPP server.
if (username_ == "user@gmail.com" && !SetUpLocalPythonTestServer())
LOG(FATAL) << "Failed to set up local python XMPP server";
if (!SetUpLocalTestServer())
LOG(FATAL) << "Failed to set up local test server";
} else if (server_type_ == EXTERNAL_LIVE_SERVER) {
// Nothing to do; we'll just talk to the URL we were given.
} else {
LOG(FATAL) << "Don't know which server environment to run test in.";
}
}
bool SyncTest::SetUpLocalPythonTestServer() {
EXPECT_TRUE(sync_server_.Start())
<< "Could not launch local python test server.";
CommandLine* cl = CommandLine::ForCurrentProcess();
if (server_type_ == LOCAL_PYTHON_SERVER) {
std::string sync_service_url = sync_server_.GetURL("chromiumsync").spec();
cl->AppendSwitchASCII(switches::kSyncServiceURL, sync_service_url);
DVLOG(1) << "Started local python sync server at " << sync_service_url;
}
int xmpp_port = 0;
if (!sync_server_.server_data().GetInteger("xmpp_port", &xmpp_port)) {
LOG(ERROR) << "Could not find valid xmpp_port value";
return false;
}
if ((xmpp_port <= 0) || (xmpp_port > kuint16max)) {
LOG(ERROR) << "Invalid xmpp port: " << xmpp_port;
return false;
}
net::HostPortPair xmpp_host_port_pair(sync_server_.host_port_pair());
xmpp_host_port_pair.set_port(xmpp_port);
xmpp_port_.reset(new net::ScopedPortException(xmpp_port));
if (!cl->HasSwitch(switches::kSyncNotificationHostPort)) {
cl->AppendSwitchASCII(switches::kSyncNotificationHostPort,
xmpp_host_port_pair.ToString());
// The local XMPP server only supports insecure connections.
cl->AppendSwitch(switches::kSyncAllowInsecureXmppConnection);
}
DVLOG(1) << "Started local python XMPP server at "
<< xmpp_host_port_pair.ToString();
return true;
}
bool SyncTest::SetUpLocalTestServer() {
CommandLine* cl = CommandLine::ForCurrentProcess();
CommandLine::StringType server_cmdline_string = cl->GetSwitchValueNative(
switches::kSyncServerCommandLine);
CommandLine::StringVector server_cmdline_vector;
CommandLine::StringType delimiters(FILE_PATH_LITERAL(" "));
Tokenize(server_cmdline_string, delimiters, &server_cmdline_vector);
CommandLine server_cmdline(server_cmdline_vector);
base::LaunchOptions options;
#if defined(OS_WIN)
options.start_hidden = true;
#endif
if (!base::LaunchProcess(server_cmdline, options, &test_server_handle_))
LOG(ERROR) << "Could not launch local test server.";
const int kMaxWaitTime = TestTimeouts::action_max_timeout_ms();
const int kNumIntervals = 15;
if (WaitForTestServerToStart(kMaxWaitTime, kNumIntervals)) {
DVLOG(1) << "Started local test server at "
<< cl->GetSwitchValueASCII(switches::kSyncServiceURL) << ".";
return true;
} else {
LOG(ERROR) << "Could not start local test server at "
<< cl->GetSwitchValueASCII(switches::kSyncServiceURL) << ".";
return false;
}
}
bool SyncTest::TearDownLocalPythonTestServer() {
if (!sync_server_.Stop()) {
LOG(ERROR) << "Could not stop local python test server.";
return false;
}
xmpp_port_.reset();
return true;
}
bool SyncTest::TearDownLocalTestServer() {
if (test_server_handle_ != base::kNullProcessHandle) {
EXPECT_TRUE(base::KillProcess(test_server_handle_, 0, false))
<< "Could not stop local test server.";
base::CloseProcessHandle(test_server_handle_);
test_server_handle_ = base::kNullProcessHandle;
}
return true;
}
bool SyncTest::WaitForTestServerToStart(int time_ms, int intervals) {
for (int i = 0; i < intervals; ++i) {
if (IsTestServerRunning())
return true;
base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(
time_ms / intervals));
}
return false;
}
bool SyncTest::IsTestServerRunning() {
CommandLine* cl = CommandLine::ForCurrentProcess();
std::string sync_url = cl->GetSwitchValueASCII(switches::kSyncServiceURL);
GURL sync_url_status(sync_url.append("/healthz"));
SyncServerStatusChecker delegate;
scoped_ptr<content::URLFetcher> fetcher(content::URLFetcher::Create(
sync_url_status, content::URLFetcher::GET, &delegate));
fetcher->SetLoadFlags(net::LOAD_DISABLE_CACHE |
net::LOAD_DO_NOT_SEND_COOKIES |
net::LOAD_DO_NOT_SAVE_COOKIES);
fetcher->SetRequestContext(g_browser_process->system_request_context());
fetcher->Start();
ui_test_utils::RunMessageLoop();
return delegate.running();
}
void SyncTest::EnableNetwork(Profile* profile) {
SetProxyConfig(profile->GetRequestContext(),
net::ProxyConfig::CreateDirect());
if (notifications_enabled_) {
EnableNotificationsImpl();
}
// TODO(rsimha): Remove this line once http://crbug.com/53857 is fixed.
net::NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
}
void SyncTest::DisableNetwork(Profile* profile) {
DisableNotificationsImpl();
// Set the current proxy configuration to a nonexistent proxy to effectively
// disable networking.
net::ProxyConfig config;
config.proxy_rules().ParseFromString("http=127.0.0.1:0");
SetProxyConfig(profile->GetRequestContext(), config);
// TODO(rsimha): Remove this line once http://crbug.com/53857 is fixed.
net::NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
}
bool SyncTest::EnableEncryption(int index, syncable::ModelType type) {
return GetClient(index)->EnableEncryptionForType(type);
}
bool SyncTest::IsEncrypted(int index, syncable::ModelType type) {
return GetClient(index)->IsTypeEncrypted(type);
}
bool SyncTest::AwaitQuiescence() {
return ProfileSyncServiceHarness::AwaitQuiescence(clients());
}
bool SyncTest::ServerSupportsNotificationControl() const {
EXPECT_NE(SERVER_TYPE_UNDECIDED, server_type_);
// Supported only if we're using the python testserver.
return server_type_ == LOCAL_PYTHON_SERVER;
}
void SyncTest::DisableNotificationsImpl() {
ASSERT_TRUE(ServerSupportsNotificationControl());
std::string path = "chromiumsync/disablenotifications";
ui_test_utils::NavigateToURL(browser(), sync_server_.GetURL(path));
ASSERT_EQ("Notifications disabled",
UTF16ToASCII(browser()->GetSelectedWebContents()->GetTitle()));
}
void SyncTest::DisableNotifications() {
DisableNotificationsImpl();
notifications_enabled_ = false;
}
void SyncTest::EnableNotificationsImpl() {
ASSERT_TRUE(ServerSupportsNotificationControl());
std::string path = "chromiumsync/enablenotifications";
ui_test_utils::NavigateToURL(browser(), sync_server_.GetURL(path));
ASSERT_EQ("Notifications enabled",
UTF16ToASCII(browser()->GetSelectedWebContents()->GetTitle()));
}
void SyncTest::EnableNotifications() {
EnableNotificationsImpl();
notifications_enabled_ = true;
}
void SyncTest::TriggerNotification(
syncable::ModelTypeSet changed_types) {
ASSERT_TRUE(ServerSupportsNotificationControl());
const std::string& data =
sync_notifier::P2PNotificationData("from_server",
sync_notifier::NOTIFY_ALL,
changed_types).ToString();
const std::string& path =
std::string("chromiumsync/sendnotification?channel=") +
sync_notifier::kSyncP2PNotificationChannel + "&data=" + data;
ui_test_utils::NavigateToURL(browser(), sync_server_.GetURL(path));
ASSERT_EQ("Notification sent",
UTF16ToASCII(browser()->GetSelectedWebContents()->GetTitle()));
}
bool SyncTest::ServerSupportsErrorTriggering() const {
EXPECT_NE(SERVER_TYPE_UNDECIDED, server_type_);
// Supported only if we're using the python testserver.
return server_type_ == LOCAL_PYTHON_SERVER;
}
void SyncTest::TriggerMigrationDoneError(
syncable::ModelTypeSet model_types) {
ASSERT_TRUE(ServerSupportsErrorTriggering());
std::string path = "chromiumsync/migrate";
char joiner = '?';
for (syncable::ModelTypeSet::Iterator it = model_types.First();
it.Good(); it.Inc()) {
path.append(
base::StringPrintf(
"%ctype=%d", joiner,
syncable::GetSpecificsFieldNumberFromModelType(it.Get())));
joiner = '&';
}
ui_test_utils::NavigateToURL(browser(), sync_server_.GetURL(path));
ASSERT_EQ("Migration: 200",
UTF16ToASCII(browser()->GetSelectedWebContents()->GetTitle()));
}
void SyncTest::TriggerBirthdayError() {
ASSERT_TRUE(ServerSupportsErrorTriggering());
std::string path = "chromiumsync/birthdayerror";
ui_test_utils::NavigateToURL(browser(), sync_server_.GetURL(path));
ASSERT_EQ("Birthday error",
UTF16ToASCII(browser()->GetSelectedWebContents()->GetTitle()));
}
void SyncTest::TriggerTransientError() {
ASSERT_TRUE(ServerSupportsErrorTriggering());
std::string path = "chromiumsync/transienterror";
ui_test_utils::NavigateToURL(browser(), sync_server_.GetURL(path));
ASSERT_EQ("Transient error",
UTF16ToASCII(browser()->GetSelectedWebContents()->GetTitle()));
}
void SyncTest::TriggerAuthError() {
ASSERT_TRUE(ServerSupportsErrorTriggering());
std::string path = "chromiumsync/cred";
ui_test_utils::NavigateToURL(browser(), sync_server_.GetURL(path));
}
namespace {
sync_pb::SyncEnums::ErrorType
GetClientToServerResponseErrorType(
browser_sync::SyncProtocolErrorType error) {
switch (error) {
case browser_sync::SYNC_SUCCESS:
return sync_pb::SyncEnums::SUCCESS;
case browser_sync::NOT_MY_BIRTHDAY:
return sync_pb::SyncEnums::NOT_MY_BIRTHDAY;
case browser_sync::THROTTLED:
return sync_pb::SyncEnums::THROTTLED;
case browser_sync::CLEAR_PENDING:
return sync_pb::SyncEnums::CLEAR_PENDING;
case browser_sync::TRANSIENT_ERROR:
return sync_pb::SyncEnums::TRANSIENT_ERROR;
case browser_sync::MIGRATION_DONE:
return sync_pb::SyncEnums::MIGRATION_DONE;
case browser_sync::UNKNOWN_ERROR:
return sync_pb::SyncEnums::UNKNOWN;
default:
NOTREACHED();
return sync_pb::SyncEnums::UNKNOWN;
}
}
sync_pb::SyncEnums::Action GetClientToServerResponseAction(
const browser_sync::ClientAction& action) {
switch (action) {
case browser_sync::UPGRADE_CLIENT:
return sync_pb::SyncEnums::UPGRADE_CLIENT;
case browser_sync::CLEAR_USER_DATA_AND_RESYNC:
return sync_pb::SyncEnums::CLEAR_USER_DATA_AND_RESYNC;
case browser_sync::ENABLE_SYNC_ON_ACCOUNT:
return sync_pb::SyncEnums::ENABLE_SYNC_ON_ACCOUNT;
case browser_sync::STOP_AND_RESTART_SYNC:
return sync_pb::SyncEnums::STOP_AND_RESTART_SYNC;
case browser_sync::DISABLE_SYNC_ON_CLIENT:
return sync_pb::SyncEnums::DISABLE_SYNC_ON_CLIENT;
case browser_sync::UNKNOWN_ACTION:
return sync_pb::SyncEnums::UNKNOWN_ACTION;
default:
NOTREACHED();
return sync_pb::SyncEnums::UNKNOWN_ACTION;
}
}
} // namespace
void SyncTest::TriggerSyncError(const browser_sync::SyncProtocolError& error,
SyncErrorFrequency frequency) {
ASSERT_TRUE(ServerSupportsErrorTriggering());
std::string path = "chromiumsync/error";
int error_type =
static_cast<int>(GetClientToServerResponseErrorType(
error.error_type));
int action = static_cast<int>(GetClientToServerResponseAction(
error.action));
path.append(base::StringPrintf("?error=%d", error_type));
path.append(base::StringPrintf("&action=%d", action));
path.append(base::StringPrintf("&error_description=%s",
error.error_description.c_str()));
path.append(base::StringPrintf("&url=%s", error.url.c_str()));
path.append(base::StringPrintf("&frequency=%d", frequency));
ui_test_utils::NavigateToURL(browser(), sync_server_.GetURL(path));
std::string output = UTF16ToASCII(
browser()->GetSelectedWebContents()->GetTitle());
ASSERT_TRUE(output.find("SetError: 200") != string16::npos);
}
void SyncTest::TriggerSetSyncTabs() {
ASSERT_TRUE(ServerSupportsErrorTriggering());
std::string path = "chromiumsync/synctabs";
ui_test_utils::NavigateToURL(browser(), sync_server_.GetURL(path));
ASSERT_EQ("Sync Tabs",
UTF16ToASCII(browser()->GetSelectedWebContents()->GetTitle()));
}
void SyncTest::TriggerCreateSyncedBookmarks() {
ASSERT_TRUE(ServerSupportsErrorTriggering());
std::string path = "chromiumsync/createsyncedbookmarks";
ui_test_utils::NavigateToURL(browser(), sync_server_.GetURL(path));
ASSERT_EQ("Synced Bookmarks",
UTF16ToASCII(browser()->GetSelectedWebContents()->GetTitle()));
}
int SyncTest::NumberOfDefaultSyncItems() const {
return number_of_default_sync_items_;
}
void SyncTest::SetProxyConfig(net::URLRequestContextGetter* context_getter,
const net::ProxyConfig& proxy_config) {
base::WaitableEvent done(false, false);
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&SetProxyConfigCallback, &done,
make_scoped_refptr(context_getter), proxy_config));
done.Wait();
}
|
// FILE NAME: $HeadURL: svn+ssh://svn.cm.aol.com/advertising/adlearn/gen1/trunk/lib/cpp/DataProxy/test/ExecutionProxyTest.hpp $
//
// REVISION: $Revision: 280002 $
//
// COPYRIGHT: (c) 2006 Advertising.com All Rights Reserved.
//
// LAST UPDATED: $Date: 2013-06-03 15:11:03 -0400 (Mon, 03 Jun 2013) $
// UPDATED BY: $Author: sstrick $
#ifndef _EXECUTION_PROXY_TEST_HPP_
#define _EXECUTION_PROXY_TEST_HPP_
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include <boost/scoped_ptr.hpp>
class TempDirectory;
class ExecutionProxyTest : public CppUnit::TestFixture
{
private:
CPPUNIT_TEST_SUITE( ExecutionProxyTest );
CPPUNIT_TEST( testInvalidXml );
CPPUNIT_TEST( testOperationAttributeParsing );
CPPUNIT_TEST( testPing );
CPPUNIT_TEST( testLoad );
CPPUNIT_TEST( testLoadError );
CPPUNIT_TEST( testLoadTimeout );
CPPUNIT_TEST( testLoadNotSupported );
CPPUNIT_TEST( testStore );
CPPUNIT_TEST( testStoreError );
CPPUNIT_TEST( testStoreTimeout );
CPPUNIT_TEST( testStoreNotSupported );
CPPUNIT_TEST( testDelete );
CPPUNIT_TEST( testDeleteError );
CPPUNIT_TEST( testDeleteTimeout );
CPPUNIT_TEST( testDeleteNotSupported );
CPPUNIT_TEST_SUITE_END();
public:
ExecutionProxyTest();
virtual ~ExecutionProxyTest();
void setUp();
void tearDown();
void testInvalidXml();
void testOperationAttributeParsing();
void testPing();
void testLoad();
void testLoadError();
void testLoadTimeout();
void testLoadNotSupported();
void testStore();
void testStoreError();
void testStoreTimeout();
void testStoreNotSupported();
void testDelete();
void testDeleteError();
void testDeleteTimeout();
void testDeleteNotSupported();
private:
boost::scoped_ptr<TempDirectory> m_pTempDir;
};
#endif //_EXECUTION_PROXY_TEST_HPP_
|
// Fig. 21.6: fig21_06.cpp
// Aiming a derived-class pointer at a base-class object.
#include "CommissionEmployee.h"
#include "BasePlusCommissionEmployee.h"
int main()
{
CommissionEmployee commissionEmployee(
"Sue", "Jones", "222-22-2222", 10000, .06 );
BasePlusCommissionEmployee *basePlusCommissionEmployeePtr = 0;
// aim derived-class pointer at base-class object
// Error: a CommissionEmployee is not a BasePlusCommissionEmployee
basePlusCommissionEmployeePtr = &commissionEmployee;
} // end main
/**************************************************************************
* (C) Copyright 1992-2010 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/
|
#pragma once
#include "../Component.hpp"
class PreEvent
{
protected:
class UObject* PE_Caller; // The calling class/unreal object.
class UFunction* PE_Function; // Unreal function, used as a reference in Process Event to call the native function.
void* PE_Params; // If params are provided in the function, this would be a pointer to a struct with said params in them.
bool PE_Detour; // If we should detour this event or not through Process Event, this is entirely up to us and not the game.
public:
PreEvent();
PreEvent(class UObject* caller, class UFunction* function, void* params);
~PreEvent();
public:
class UObject* Caller() const;
template <typename T> T* GetCaller() const;
class UFunction* Function() const;
void* Params() const;
template <typename T> T* GetParams() const;
bool Detour() const;
void SetDetour(bool bDetour);
public:
PreEvent operator=(const PreEvent& other);
};
class PostEvent : public PreEvent
{
private:
void* PE_Result; // Unused result after going through Process Event.
public:
PostEvent();
PostEvent(class UObject* caller, class UFunction* function, void* params, void* result);
~PostEvent();
public:
void* Result() const;
template <typename T> T* GetResult() const;
public:
PostEvent operator=(const PostEvent& other);
};
namespace Hooks
{
void HUDPostRender(PreEvent& event);
void HUDPostRenderPost(const PostEvent& event);
void GameViewPortPostRender(PreEvent& event);
void GFxDataMainMenuAdded(PreEvent& event);
void PlayerControllerTick(PreEvent& event);
void GameViewPortKeyPress(PreEvent& event);
}
typedef void(*ProcessEventType)(class UObject*, class UFunction*, void*, void*); // Calling object, function, structure pointer with parameters, unused result
// Manages everything related to hooking functions form Process Event, as well as detouring.
class EventsComponent : public Component
{
private:
static inline bool Detoured;
static inline ProcessEventType ProcessEvent;
static inline std::map<int32_t, std::vector<std::function<void(PreEvent&)>>> PreHookedEvents; // Hooked function's internal integer and bound function.
static inline std::map<int32_t, std::vector<std::function<void(const PostEvent&)>>> PostHookedEvents; // Hooked function's internal integer and bound function.
static inline std::vector<int32_t> BlacklistedEvents; // Blacklisted function's internal integer.
public:
EventsComponent();
~EventsComponent() override;
public:
void OnCreate() override;
void OnDestroy() override;
public:
static bool IsDetoured();
static void AttachDetour(const ProcessEventType& detourFunction); // Redirects the process event virtual function to our own void, for us to manually process later to the typedef.
static void DetachDetour(); // Called by the deconstuctor, necessary for if your DLL gets intentionally (or unintentionally) unloaded before your game exits.
static void ProcessEventDetour(class UObject* caller, class UFunction* function, void* params, void* result); // Process event gets detoured to this function, then we manually proxy it through to "ProcessEvent".
static bool IsEventBlacklisted(int32_t functionInteger);
void BlacklistEvent(const std::string& function);
void WhitelistEvent(const std::string& function);
void HookEventPre(const std::string& function, std::function<void(PreEvent&)> hook);
void HookEventPost(const std::string& function, std::function<void(const PostEvent&)> hook);
void Initialize(); // Initializes hooking events to functions.
};
extern class EventsComponent Events;
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2020 The Bitcoin Core developers
// Copyright (c) 2013-2021 The Riecoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <rpc/client.h>
#include <util/system.h>
#include <set>
#include <stdint.h>
class CRPCConvertParam
{
public:
std::string methodName; //!< method whose params want conversion
int paramIdx; //!< 0-based idx of param to convert
std::string paramName; //!< parameter name
};
// clang-format off
/**
* Specify a (method, idx, name) here if the argument is a non-string RPC
* argument and needs to be converted from JSON.
*
* @note Parameter indexes start from 0.
*/
static const CRPCConvertParam vRPCConvertParams[] =
{
{ "setmocktime", 0, "timestamp" },
{ "mockscheduler", 0, "delta_time" },
{ "utxoupdatepsbt", 1, "descriptors" },
{ "generatetoaddress", 0, "nblocks" },
{ "generatetoaddress", 2, "maxtries" },
{ "generatetodescriptor", 0, "num_blocks" },
{ "generatetodescriptor", 2, "maxtries" },
{ "generateblock", 1, "transactions" },
{ "getnetworkminingpower", 0, "nblocks" },
{ "getnetworkminingpower", 1, "height" },
{ "sendtoaddress", 1, "amount" },
{ "sendtoaddress", 4, "subtractfeefromamount" },
{ "sendtoaddress", 5 , "replaceable" },
{ "sendtoaddress", 6 , "conf_target" },
{ "sendtoaddress", 8, "avoid_reuse" },
{ "sendtoaddress", 9, "fee_rate"},
{ "sendtoaddress", 10, "verbose"},
{ "settxfee", 0, "amount" },
{ "sethdseed", 0, "newkeypool" },
{ "getreceivedbyaddress", 1, "minconf" },
{ "getreceivedbylabel", 1, "minconf" },
{ "listreceivedbyaddress", 0, "minconf" },
{ "listreceivedbyaddress", 1, "include_empty" },
{ "listreceivedbyaddress", 2, "include_watchonly" },
{ "listreceivedbylabel", 0, "minconf" },
{ "listreceivedbylabel", 1, "include_empty" },
{ "listreceivedbylabel", 2, "include_watchonly" },
{ "getbalance", 1, "minconf" },
{ "getbalance", 2, "include_watchonly" },
{ "getbalance", 3, "avoid_reuse" },
{ "getblockhash", 0, "height" },
{ "waitforblockheight", 0, "height" },
{ "waitforblockheight", 1, "timeout" },
{ "waitforblock", 1, "timeout" },
{ "waitfornewblock", 0, "timeout" },
{ "listtransactions", 1, "count" },
{ "listtransactions", 2, "skip" },
{ "listtransactions", 3, "include_watchonly" },
{ "walletpassphrase", 1, "timeout" },
{ "getblocktemplate", 0, "template_request" },
{ "listsinceblock", 1, "target_confirmations" },
{ "listsinceblock", 2, "include_watchonly" },
{ "listsinceblock", 3, "include_removed" },
{ "sendmany", 1, "amounts" },
{ "sendmany", 2, "minconf" },
{ "sendmany", 4, "subtractfeefrom" },
{ "sendmany", 5 , "replaceable" },
{ "sendmany", 6 , "conf_target" },
{ "sendmany", 8, "fee_rate"},
{ "sendmany", 9, "verbose" },
{ "deriveaddresses", 1, "range" },
{ "scantxoutset", 1, "scanobjects" },
{ "addmultisigaddress", 0, "nrequired" },
{ "addmultisigaddress", 1, "keys" },
{ "createmultisig", 0, "nrequired" },
{ "createmultisig", 1, "keys" },
{ "listunspent", 0, "minconf" },
{ "listunspent", 1, "maxconf" },
{ "listunspent", 2, "addresses" },
{ "listunspent", 3, "include_unsafe" },
{ "listunspent", 4, "query_options" },
{ "getblock", 1, "verbosity" },
{ "getblock", 1, "verbose" },
{ "getblockheader", 1, "verbose" },
{ "getresult", 1, "detailed" },
{ "getchaintxstats", 0, "nblocks" },
{ "gettransaction", 1, "include_watchonly" },
{ "gettransaction", 2, "verbose" },
{ "getrawtransaction", 1, "verbose" },
{ "createrawtransaction", 0, "inputs" },
{ "createrawtransaction", 1, "outputs" },
{ "createrawtransaction", 2, "locktime" },
{ "createrawtransaction", 3, "replaceable" },
{ "decoderawtransaction", 1, "iswitness" },
{ "signrawtransactionwithkey", 1, "privkeys" },
{ "signrawtransactionwithkey", 2, "prevtxs" },
{ "signrawtransactionwithwallet", 1, "prevtxs" },
{ "sendrawtransaction", 1, "maxfeerate" },
{ "testmempoolaccept", 0, "rawtxs" },
{ "testmempoolaccept", 1, "maxfeerate" },
{ "combinerawtransaction", 0, "txs" },
{ "fundrawtransaction", 1, "options" },
{ "fundrawtransaction", 2, "iswitness" },
{ "walletcreatefundedpsbt", 0, "inputs" },
{ "walletcreatefundedpsbt", 1, "outputs" },
{ "walletcreatefundedpsbt", 2, "locktime" },
{ "walletcreatefundedpsbt", 3, "options" },
{ "walletcreatefundedpsbt", 4, "bip32derivs" },
{ "walletprocesspsbt", 1, "sign" },
{ "walletprocesspsbt", 3, "bip32derivs" },
{ "createpsbt", 0, "inputs" },
{ "createpsbt", 1, "outputs" },
{ "createpsbt", 2, "locktime" },
{ "createpsbt", 3, "replaceable" },
{ "combinepsbt", 0, "txs"},
{ "joinpsbts", 0, "txs"},
{ "finalizepsbt", 1, "extract"},
{ "converttopsbt", 1, "permitsigdata"},
{ "converttopsbt", 2, "iswitness"},
{ "gettxout", 1, "n" },
{ "gettxout", 2, "include_mempool" },
{ "gettxoutproof", 0, "txids" },
{ "gettxoutsetinfo", 1, "hash_or_height" },
{ "gettxoutsetinfo", 2, "use_index"},
{ "lockunspent", 0, "unlock" },
{ "lockunspent", 1, "transactions" },
{ "send", 0, "outputs" },
{ "send", 1, "conf_target" },
{ "send", 3, "fee_rate"},
{ "send", 4, "options" },
{ "importprivkey", 2, "rescan" },
{ "importaddress", 2, "rescan" },
{ "importaddress", 3, "p2sh" },
{ "importpubkey", 2, "rescan" },
{ "importmulti", 0, "requests" },
{ "importmulti", 1, "options" },
{ "importdescriptors", 0, "requests" },
{ "verifychain", 0, "checklevel" },
{ "verifychain", 1, "nblocks" },
{ "getblockstats", 0, "hash_or_height" },
{ "getblockstats", 1, "stats" },
{ "pruneblockchain", 0, "height" },
{ "keypoolrefill", 0, "newsize" },
{ "getrawmempool", 0, "verbose" },
{ "getrawmempool", 1, "mempool_sequence" },
{ "estimatesmartfee", 0, "conf_target" },
{ "estimaterawfee", 0, "conf_target" },
{ "estimaterawfee", 1, "threshold" },
{ "prioritisetransaction", 1, "dummy" },
{ "prioritisetransaction", 2, "fee_delta" },
{ "setban", 2, "bantime" },
{ "setban", 3, "absolute" },
{ "setnetworkactive", 0, "state" },
{ "setwalletflag", 1, "value" },
{ "getmempoolancestors", 1, "verbose" },
{ "getmempooldescendants", 1, "verbose" },
{ "bumpfee", 1, "options" },
{ "psbtbumpfee", 1, "options" },
{ "logging", 0, "include" },
{ "logging", 1, "exclude" },
{ "disconnectnode", 1, "nodeid" },
{ "upgradewallet", 0, "version" },
// Echo with conversion (For testing only)
{ "echojson", 0, "arg0" },
{ "echojson", 1, "arg1" },
{ "echojson", 2, "arg2" },
{ "echojson", 3, "arg3" },
{ "echojson", 4, "arg4" },
{ "echojson", 5, "arg5" },
{ "echojson", 6, "arg6" },
{ "echojson", 7, "arg7" },
{ "echojson", 8, "arg8" },
{ "echojson", 9, "arg9" },
{ "rescanblockchain", 0, "start_height"},
{ "rescanblockchain", 1, "stop_height"},
{ "createwallet", 1, "disable_private_keys"},
{ "createwallet", 2, "blank"},
{ "createwallet", 4, "avoid_reuse"},
{ "createwallet", 5, "descriptors"},
{ "createwallet", 6, "load_on_startup"},
{ "createwallet", 7, "external_signer"},
{ "loadwallet", 1, "load_on_startup"},
{ "unloadwallet", 1, "load_on_startup"},
{ "getnodeaddresses", 0, "count"},
{ "addpeeraddress", 1, "port"},
{ "stop", 0, "wait" },
};
// clang-format on
class CRPCConvertTable
{
private:
std::set<std::pair<std::string, int>> members;
std::set<std::pair<std::string, std::string>> membersByName;
public:
CRPCConvertTable();
bool convert(const std::string& method, int idx) {
return (members.count(std::make_pair(method, idx)) > 0);
}
bool convert(const std::string& method, const std::string& name) {
return (membersByName.count(std::make_pair(method, name)) > 0);
}
};
CRPCConvertTable::CRPCConvertTable()
{
for (const auto& cp : vRPCConvertParams) {
members.emplace(cp.methodName, cp.paramIdx);
membersByName.emplace(cp.methodName, cp.paramName);
}
}
static CRPCConvertTable rpcCvtTable;
/** Non-RFC4627 JSON parser, accepts internal values (such as numbers, true, false, null)
* as well as objects and arrays.
*/
UniValue ParseNonRFCJSONValue(const std::string& strVal)
{
UniValue jVal;
if (!jVal.read(std::string("[")+strVal+std::string("]")) ||
!jVal.isArray() || jVal.size()!=1)
throw std::runtime_error(std::string("Error parsing JSON: ") + strVal);
return jVal[0];
}
UniValue RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
UniValue params(UniValue::VARR);
for (unsigned int idx = 0; idx < strParams.size(); idx++) {
const std::string& strVal = strParams[idx];
if (!rpcCvtTable.convert(strMethod, idx)) {
// insert string value directly
params.push_back(strVal);
} else {
// parse string as JSON, insert bool/number/object/etc. value
params.push_back(ParseNonRFCJSONValue(strVal));
}
}
return params;
}
UniValue RPCConvertNamedValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
UniValue params(UniValue::VOBJ);
for (const std::string &s: strParams) {
size_t pos = s.find('=');
if (pos == std::string::npos) {
throw(std::runtime_error("No '=' in named argument '"+s+"', this needs to be present for every argument (even if it is empty)"));
}
std::string name = s.substr(0, pos);
std::string value = s.substr(pos+1);
if (!rpcCvtTable.convert(strMethod, name)) {
// insert string value directly
params.pushKV(name, value);
} else {
// parse string as JSON, insert bool/number/object/etc. value
params.pushKV(name, ParseNonRFCJSONValue(value));
}
}
return params;
}
|
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <unordered_map>
// template <class Key, class T, class Hash = hash<Key>, class Pred = equal_to<Key>,
// class Alloc = allocator<pair<const Key, T>>>
// class unordered_map
// unordered_map(initializer_list<value_type> il, size_type n,
// const hasher& hf, const key_equal& eql);
#include <unordered_map>
#include <string>
#include <cassert>
#include <cfloat>
#include <cmath>
#include "../../../test_compare.h"
#include "../../../test_hash.h"
#include "test_allocator.h"
#include "min_allocator.h"
int main()
{
#ifndef _LIBCPP_HAS_NO_GENERALIZED_INITIALIZERS
{
typedef std::unordered_map<int, std::string,
test_hash<std::hash<int> >,
test_compare<std::equal_to<int> >,
test_allocator<std::pair<const int, std::string> >
> C;
typedef std::pair<int, std::string> P;
C c({
P(1, "one"),
P(2, "two"),
P(3, "three"),
P(4, "four"),
P(1, "four"),
P(2, "four"),
},
7,
test_hash<std::hash<int> >(8),
test_compare<std::equal_to<int> >(9)
);
assert(c.bucket_count() == 7);
assert(c.size() == 4);
assert(c.at(1) == "one");
assert(c.at(2) == "two");
assert(c.at(3) == "three");
assert(c.at(4) == "four");
assert(c.hash_function() == test_hash<std::hash<int> >(8));
assert(c.key_eq() == test_compare<std::equal_to<int> >(9));
assert(c.get_allocator() ==
(test_allocator<std::pair<const int, std::string> >()));
assert(!c.empty());
assert(std::distance(c.begin(), c.end()) == c.size());
assert(std::distance(c.cbegin(), c.cend()) == c.size());
assert(std::fabs(c.load_factor() - (float)c.size()/c.bucket_count()) < FLT_EPSILON);
assert(c.max_load_factor() == 1);
}
#if __cplusplus >= 201103L
{
typedef std::unordered_map<int, std::string,
test_hash<std::hash<int> >,
test_compare<std::equal_to<int> >,
min_allocator<std::pair<const int, std::string> >
> C;
typedef std::pair<int, std::string> P;
C c({
P(1, "one"),
P(2, "two"),
P(3, "three"),
P(4, "four"),
P(1, "four"),
P(2, "four"),
},
7,
test_hash<std::hash<int> >(8),
test_compare<std::equal_to<int> >(9)
);
assert(c.bucket_count() == 7);
assert(c.size() == 4);
assert(c.at(1) == "one");
assert(c.at(2) == "two");
assert(c.at(3) == "three");
assert(c.at(4) == "four");
assert(c.hash_function() == test_hash<std::hash<int> >(8));
assert(c.key_eq() == test_compare<std::equal_to<int> >(9));
assert(c.get_allocator() ==
(min_allocator<std::pair<const int, std::string> >()));
assert(!c.empty());
assert(std::distance(c.begin(), c.end()) == c.size());
assert(std::distance(c.cbegin(), c.cend()) == c.size());
assert(std::fabs(c.load_factor() - (float)c.size()/c.bucket_count()) < FLT_EPSILON);
assert(c.max_load_factor() == 1);
}
#endif
#endif // _LIBCPP_HAS_NO_GENERALIZED_INITIALIZERS
}
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <stddef.h>
void invalidate_local_ok(int** pp) {
int t = 0xdeadbeef;
*pp = &t; // <-- potential bug here since t goes out of scope
}
void access_out_of_scope_stack_ref_bad() {
int* p = NULL;
invalidate_local_ok(&p);
int k = *p; // accessing invalid
}
void no_access_out_of_scope_stack_ref_ok() {
int* p = NULL;
invalidate_local_ok(&p);
// p is not accessed, hence ok
}
|
/*
* Author: Yevgeniy Kiveisha <yevgeniy.kiveisha@intel.com>
* Copyright (c) 2014 Intel Corporation.
*
* 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 copies 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 all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 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.
*/
#pragma once
#include <string>
#include <mraa/aio.hpp>
#include <mraa/gpio.hpp>
#include <mraa/spi.hpp>
#define HIGH 1
#define LOW 0
namespace upm {
/**
* @brief MAX31723 Temperature Sensor library
* @defgroup max31723 libupm-max31723
* @ingroup maxim spi temp
*/
/**
* @library max31723
* @sensor max31723
* @comname MAX31723 Temperature Sensor
* @type temp
* @man maxim
* @con spi
*
* @brief API for the MAX31723 Temperature Sensor
*
* Maxim Integrated*
* [MAX31723](http://datasheets.maximintegrated.com/en/ds/MAX31722-MAX31723.pdf)
* is a low-voltage 3-wire/SPI temperature sensor controller. This module was
* tested on the Maxim Integrated [MAX31732PMB1 PMOD
* module](http://datasheets.maximintegrated.com/en/ds/MAX31723PMB1.pdf) from
* the analog PMOD kit.
*
* @snippet max31723.cxx Interesting
*/
class MAX31723 {
public:
static const uint8_t R_STS_READ_CMD = 0x00;
static const uint8_t R_STS_WRITE_CMD = 0x80;
static const uint8_t R_TEMPERATURE_LSB = 0x01;
static const uint8_t R_TEMPERATURE_MSB = 0x02;
static const uint8_t B_CONT_READING = 0x00;
/**
* Instantiates an MAX31723 object
*
* @param bus Number of the used bus
* @param devAddr Address of the used I2C device
*/
MAX31723 (int csn);
/**
* MAXDS3231M object destructor; basically, it closes the I2C connection.
* it is not needed anymore, as the connections will be closed when
* m_spi and m_csnPinCtx variables will go out of scope
* ~MAX31723 ();
**/
/**
* Gets the on-board temperature.
*/
short getTemperature ();
/**
* Returns the name of the component
*/
std::string name()
{
return m_name;
}
private:
std::string m_name;
mraa::Spi m_spi;
mraa::Gpio m_csnPinCtx;
uint8_t readRegister (uint8_t reg);
void writeRegister (uint8_t reg, uint8_t data);
/**
* Sets the chip select pin to LOW
*/
mraa::Result CSOn ();
/**
* Sets the chip select pin to HIGH
*/
mraa::Result CSOff ();
};
}
|
// Master Profile Manipulation
#include "stdafx.h"
#include "MasterProf.h"
#include "copyFile.h"
#include "DelMasterDlg.h"
#include "filename.h"
#include "filesrch.h"
#include "Identity.h"
#include "IniFile.h"
#include "MasterMgmtDlg.h"
#include "PreOutpost.h"
#include "ProgramFiles.h"
#include "SelectMasterDlg.h"
#include "MessageBox.h"
static TCchar* Section = _T("MetaProfiles");
MasterProf masterProf;
// Read .ini file for all meta profiles, checking that they are still available and correcting .ini file
// in the process
void MasterProf::readIniFile() {
int n;
String path;
int i;
bool missing = false;
masters.clear();
n = iniFile.readInt(Section, _T("nMetaProfiles"), 0);
for (i = 0; i < n; i++) {
if (!iniFile.readString(Section, getKey(i), path))
{missing = true; continue;}
if (path.empty() || !PathFileExists(path)) {missing = true; continue;}
Master& m = masters.nextData();
m.path = path; m.name = getMainName(path);
}
if (missing) setMetaProfiles();
}
// Write Meta Profiles back into ini file after deleting
void MasterProf::setMetaProfiles() {
int n = masters.end();
int i;
String metaProfile;
iniFile.deleteSection(Section);
iniFile.writeInt(Section, _T("nMetaProfiles"), n);
for (i = 0; i < n; i++) {iniFile.writeString(_T("MetaProfiles"), getKey(i), masters[i].path);}
}
// Produce a Property Name to be used in an ini file. Good for putting the Master Files in sort order
// for MetaProfile00 to MetaProfile99. Should be enough for this program...
String MasterProf::getKey(int i) {
String name = _T("MetaProfile"); if (i < 10) name += _T("0"); name += toString(i); return name;
}
Master* MasterProf::select() {
MPIter iter(*this);
Master* m;
SelectMasterDlg dlg;
dlg.allProfiles = 0;
if (masters.end() == 1) {allProfiles = false; return &masters[0];}
for (m = iter(); m; m = iter++) {dlg.addListBoxItem(m->name);}
if (dlg.DoModal() == IDOK) {
name = dlg.getListBoxSelection(); allProfiles = dlg.allProfiles;
for (m = iter(); m; m = iter++) if (m->name == name) return m;
}
return 0;
}
// Process identity for selected meta profile file, then either copy one Meta Profile or all Meta
// Profiles
bool MasterProf::process(Master* m) {
MPIter iter(*this);
if (!m) return false;
if (!idInfo(m->name, m->path, allProfiles)) return false;
if (allProfiles) {
for (m = iter(); m; m = iter++) {idInfo.process(m->name, m->path);}
}
else idInfo.process(m->name, m->path);
return true;
}
// Insertion sort new profile into metaProfilePath
bool MasterProf::insertNewProfile(String& newProfile) {
String name = getMainName(newProfile);
MPIter iter(*this);
Master* m;
String stg;
for (m = iter(); m; m = iter++) if (name == m->name) return false;
m = &masters.nextData(); m->path = newProfile; m->name = name;
qsort(&masters[0], &masters[masters.end()-1]); return true;
}
|
#ifndef EventGenerator_CosmicFromTH2_hh
#define EventGenerator_CosmicFromTH2_hh
//
// Cosmic ray muon generator using a TH2 as probability distribution
//
// $Id: CosmicDYB.hh,v 1.13 2014/03/22 21:40:43 ehrlich Exp $
// $Author: ehrlich $
// $Date: 2014/03/22 21:40:43 $
//
// Original author Ralf Ehrlich
//
#include <vector>
#include "EventGenerator/inc/GeneratorBase.hh"
#include "CLHEP/Random/RandFlat.h"
// Forward declarations.
class TH2;
class TFile;
namespace art{
class Run;
}
namespace mu2e {
// Forward declaratations.
class SimpleConfig;
class CosmicFromTH2: public GeneratorBase {
public:
CosmicFromTH2(CLHEP::HepRandomEngine& engine,
art::Run& run,
const SimpleConfig& config);
virtual ~CosmicFromTH2();
virtual void generate( GenParticleCollection& );
private:
TFile *_file;
TH2 *_histogram;
double _energy;
double _p;
double _time;
CLHEP::Hep3Vector _cosmicReferencePointInMu2e;
double _dx;
double _dy;
double _dz;
CLHEP::RandFlat _randFlat;
bool _createdProductionPlane;
}; // CosmicDYB
} // namespace mu2e
#endif /* EventGenerator_CosmicFromTH2_hh */
|
#include <sstream>
#include "exceptions.h"
#include "syntax.h"
static inline ValueType keyword_to_value_type(LexemeType lexeme)
{
switch (lexeme) {
case ltInt:
return vtInteger;
case ltString:
return vtString;
case ltBoolean:
return vtBoolean;
case ltReal:
return vtReal;
default:
return vtNone;
}
}
static inline ValueType constant_to_value_type(LexemeType lexeme)
{
switch (lexeme) {
case ltConstInt:
return vtInteger;
case ltConstString:
return vtString;
case ltConstBoolean:
return vtBoolean;
case ltConstReal:
return vtReal;
default:
return vtNone;
}
}
static inline std::string value_type_to_string(ValueType type)
{
switch (type) {
case vtInteger:
return "Integer";
case vtString:
return "String";
case vtBoolean:
return "Boolean";
case vtReal:
return "Real";
default:
return "None";
}
}
SyntaxAnalyzer::SyntaxAnalyzer(bool comparison_chains, bool lazy_evaluations):
comparison_chains(comparison_chains), lazy_evaluations(lazy_evaluations),
pos(0), cur_lexeme(NULL), cur_lexeme_type(ltNone) {}
void SyntaxAnalyzer::get_next_lexeme()
{
if (pos == lexemes.size()) {
cur_lexeme = NULL;
cur_lexeme_type = ltNone;
} else {
cur_lexeme = &lexemes[pos++];
cur_lexeme_type = cur_lexeme->get_type();
}
}
void SyntaxAnalyzer::check_lexeme(LexemeType lexeme, const std::string &error_message)
{
if (cur_lexeme_type != lexeme) {
throw_syntax_error(error_message);
} else {
get_next_lexeme();
}
}
void SyntaxAnalyzer::throw_syntax_error(const std::string &message)
{
std::stringstream stream;
stream << "Syntax error at ";
if (cur_lexeme != NULL) {
cur_lexeme->print(stream);
} else {
stream << "end of file";
}
if (message != "") {
stream << ": " << message;
}
throw SyntaxError(stream.str());
}
void SyntaxAnalyzer::throw_semantic_error(const Lexeme *where, const std::string &message)
{
std::stringstream stream;
stream << "Semantic error";
if (where != NULL) {
stream << " at ";
where->print(stream);
}
if (message != "") {
stream << ": " << message;
}
throw SemanticError(stream.str());
}
void SyntaxAnalyzer::throw_type_mismatch(const Lexeme *where, ValueType left, ValueType right)
{
throw_semantic_error(where, "type mismatch (" + value_type_to_string(left) +
" and " + value_type_to_string(right) + ")");
}
void SyntaxAnalyzer::gen_constant(ValueType type, const std::string &value)
{
ProgramNode result;
result.type = ntValue;
switch (type) {
case vtInteger:
result.data.value = new IntegerValue(value);
break;
case vtString:
result.data.value = new StringValue(value);
break;
case vtBoolean:
result.data.value = new BooleanValue(value);
break;
case vtReal:
result.data.value = new RealValue(value);
break;
default:
throw std::runtime_error("Unknown constant type");
}
program.push_back(result);
}
void SyntaxAnalyzer::gen_constant(Integer value)
{
ProgramNode result;
result.type = ntValue;
result.data.value = new IntegerValue(value);
program.push_back(result);
}
void SyntaxAnalyzer::gen_operation(Operation operation)
{
ProgramNode result;
result.type = ntOperation;
result.data.operation = operation;
program.push_back(result);
}
void SyntaxAnalyzer::gen_label(LabelID label)
{
labels.set_value(label, new IntegerValue(program.size()));
}
void SyntaxAnalyzer::gen_jump(LabelID label, JumpType type)
{
ProgramNode result;
result.type = ntValue;
switch (type) {
case jtUnconditional:
result.data.value = new BooleanValue(false);
program.push_back(result);
break;
case jtAtTrue:
gen_operation(opBoolNot);
break;
default:
;
}
labels.add_node(label, program.size());
result.data.value = NULL;
program.push_back(result);
gen_operation(opJump);
}
void SyntaxAnalyzer::state_program()
{
if (comparison_chains) {
variables.register_name("", vtNone); // 0th temp variable
}
check_lexeme(ltProgram, "program should starts with 'program' keyword");
check_lexeme(ltBlockOpen, "expected '{'");
state_descriptions();
state_operators(undefined_label, undefined_label);
check_lexeme(ltBlockClose, "expected '}'");
check_lexeme(ltNone, "unexpected continuation after program end");
labels.propagate(program);
}
void SyntaxAnalyzer::state_descriptions()
{
while (cur_lexeme_type >= ltTypesStart && cur_lexeme_type <= ltTypesEnd) {
ValueType variable_type = keyword_to_value_type(cur_lexeme_type);
get_next_lexeme();
state_description(variable_type);
check_lexeme(ltSemicolon, "expected ';'");
}
}
void SyntaxAnalyzer::state_description(ValueType variable_type)
{
state_variable(variable_type);
while (cur_lexeme_type == ltComma) {
get_next_lexeme();
state_variable(variable_type);
}
}
void SyntaxAnalyzer::state_variable(ValueType variable_type)
{
Lexeme *lexeme = cur_lexeme;
check_lexeme(ltIdentificator, "is not a valid identificator");
if (!variables.register_name(lexeme->get_value(), variable_type)) {
throw_semantic_error(lexeme, "variable with the same name has already defined");
}
VariableID id = variables.get_number(lexeme->get_value());
if (cur_lexeme_type == ltAssign) {
lexeme = cur_lexeme;
get_next_lexeme();
if (cur_lexeme_type >= ltConstantsStart && cur_lexeme_type <= ltConstantsEnd) {
ValueType constant_type = constant_to_value_type(cur_lexeme_type);
if (variable_type != constant_type) {
throw_type_mismatch(lexeme, variable_type, constant_type);
}
gen_constant(constant_type, cur_lexeme->get_value());
gen_constant(id);
gen_operation(opSaveVariable);
gen_operation(opClearStack);
get_next_lexeme();
} else {
throw_syntax_error("bad initialization");
}
}
}
void SyntaxAnalyzer::state_operators(LabelID cont_label, LabelID break_label)
{
while (cur_lexeme_type != ltBlockClose) {
state_operator(cont_label, break_label);
}
}
void SyntaxAnalyzer::state_operator(LabelID cont_label, LabelID break_label)
{
Lexeme *lexeme = cur_lexeme;
VariableID var;
LabelID then_end, else_end;
LabelID condition, loop_start, loop_end;
switch (cur_lexeme_type) {
case ltNone:
throw_syntax_error("expected '}'");
break;
case ltIf:
then_end = labels.new_label();
get_next_lexeme();
check_lexeme(ltBracketOpen, "expected '('");
if (state_expression().type != vtBoolean) {
throw_semantic_error(lexeme, "condition should be boolean");
}
check_lexeme(ltBracketClose, "expected ')'");
gen_jump(then_end, jtAtFalse);
state_operator(cont_label, break_label);
if (cur_lexeme_type == ltElse) {
get_next_lexeme();
else_end = labels.new_label();
gen_jump(else_end, jtUnconditional);
gen_label(then_end);
state_operator(cont_label, break_label);
gen_label(else_end);
} else {
gen_label(then_end);
}
break;
case ltWhile:
condition = labels.new_label();
loop_end = labels.new_label();
get_next_lexeme();
check_lexeme(ltBracketOpen, "expected '('");
gen_label(condition);
if (state_expression().type != vtBoolean) {
throw_semantic_error(lexeme, "condition should be boolean");
}
gen_jump(loop_end, jtAtFalse);
check_lexeme(ltBracketClose, "expected ')'");
state_operator(condition, loop_end);
gen_jump(condition, jtUnconditional);
gen_label(loop_end);
break;
case ltDo:
condition = labels.new_label();
loop_start = labels.new_label();
loop_end = labels.new_label();
get_next_lexeme();
gen_label(loop_start);
state_operator(condition, loop_end);
lexeme = cur_lexeme;
check_lexeme(ltWhile, "expected 'while' keyword");
check_lexeme(ltBracketOpen, "expected '('");
gen_label(condition);
if (state_expression().type != vtBoolean) {
throw_semantic_error(lexeme, "condition should be boolean");
}
gen_jump(loop_start, jtAtTrue);
check_lexeme(ltBracketClose, "expected ')'");
check_lexeme(ltSemicolon, "expected ';'");
gen_label(loop_end);
break;
case ltContinue:
get_next_lexeme();
check_lexeme(ltSemicolon, "expected ';'");
if (cont_label == undefined_label) {
throw_semantic_error(lexeme, "continue outside of the loop");
}
gen_jump(cont_label, jtUnconditional);
break;
case ltBreak:
get_next_lexeme();
check_lexeme(ltSemicolon, "expected ';'");
if (break_label == undefined_label) {
throw_semantic_error(lexeme, "break outside of the loop");
}
gen_jump(break_label, jtUnconditional);
break;
case ltRead:
get_next_lexeme();
check_lexeme(ltBracketOpen, "expected '('");
lexeme = cur_lexeme;
check_lexeme(ltIdentificator, "is not a valid identificator");
check_lexeme(ltBracketClose, "expected ')'");
check_lexeme(ltSemicolon, "expected ';'");
var = variables.get_number(lexeme->get_value());
if (var < 0) {
throw_semantic_error(lexeme, "variable is not defined");
}
gen_operation(opReadLn);
switch (variables.get_type(var)) {
case vtInteger:
gen_operation(opIntPlusUn);
break;
case vtReal:
gen_operation(opRealPlusUn);
break;
case vtBoolean:
throw_semantic_error(lexeme, "can't read boolean");
default:
break;
}
gen_constant(var);
gen_operation(opSaveVariable);
gen_operation(opClearStack);
break;
case ltWrite:
get_next_lexeme();
check_lexeme(ltBracketOpen, "expected '('");
state_expression();
gen_operation(opWrite);
while (cur_lexeme_type == ltComma) {
get_next_lexeme();
state_expression();
gen_operation(opWrite);
}
check_lexeme(ltBracketClose, "expected ')'");
gen_operation(opWriteLn);
check_lexeme(ltSemicolon, "expected ';'");
break;
case ltBlockOpen:
check_lexeme(ltBlockOpen, "expected '{'");
state_operators(cont_label, break_label);
check_lexeme(ltBlockClose, "expected '}'");
break;
default:
state_expression();
check_lexeme(ltSemicolon, "expected ';'");
gen_operation(opClearStack);
break;
}
}
ValueInfo SyntaxAnalyzer::state_expression()
{
Lexeme *lexeme;
ValueInfo cur, prev, first;
ProgramNodes variable_links;
first = cur = state_expression_or();
while (cur_lexeme_type == ltAssign) {
lexeme = cur_lexeme;
get_next_lexeme();
prev = cur;
if (!prev.is_var) {
throw_semantic_error(lexeme, "assignation to non-variable");
}
program.pop_back();
variable_links.push_back(program.back());
program.pop_back();
cur = state_expression_or();
if ((cur.type == vtString) ^ (prev.type == vtString) ||
(cur.type == vtBoolean) ^ (prev.type == vtBoolean)) {
throw_type_mismatch(lexeme, prev.type, cur.type);
}
}
while (!variable_links.empty()) {
program.push_back(variable_links.back());
variable_links.pop_back();
gen_operation(opSaveVariable);
}
return first;
}
ValueInfo SyntaxAnalyzer::state_expression_or()
{
Lexeme *lexeme;
ValueInfo cur, prev;
LabelID exp_end = undefined_label;
cur = state_expression_and();
if (lazy_evaluations && cur_lexeme_type == ltOr) {
exp_end = labels.new_label();
}
while (cur_lexeme_type == ltOr) {
if (lazy_evaluations) {
gen_operation(opDup);
gen_jump(exp_end, jtAtTrue);
}
lexeme = cur_lexeme;
get_next_lexeme();
prev = cur;
cur = state_expression_and();
cur.is_var = false;
if (cur.type != vtBoolean || prev.type != vtBoolean) {
throw_type_mismatch(lexeme, prev.type, cur.type);
}
gen_operation(opBoolOr);
}
if (exp_end != undefined_label) {
gen_label(exp_end);
}
return cur;
}
ValueInfo SyntaxAnalyzer::state_expression_and()
{
Lexeme *lexeme;
ValueInfo cur, prev;
LabelID exp_end = undefined_label;
cur = state_expression_cmp();
if (lazy_evaluations && cur_lexeme_type == ltAnd) {
exp_end = labels.new_label();
}
while (cur_lexeme_type == ltAnd) {
if (lazy_evaluations) {
gen_operation(opDup);
gen_jump(exp_end, jtAtFalse);
}
lexeme = cur_lexeme;
get_next_lexeme();
prev = cur;
cur = state_expression_cmp();
cur.is_var = false;
if (cur.type != vtBoolean || prev.type != vtBoolean) {
throw_type_mismatch(lexeme, prev.type, cur.type);
}
gen_operation(opBoolAnd);
}
if (exp_end != undefined_label) {
gen_label(exp_end);
}
return cur;
}
static inline bool is_comparer(LexemeType lexeme)
{
return lexeme >= ltComparersStart && lexeme <= ltComparersEnd;
}
ValueInfo SyntaxAnalyzer::state_expression_cmp()
{
Lexeme *lexeme;
ValueInfo cur, prev;
bool first_cmp = true;
cur = state_expression_sum();
while (is_comparer(cur_lexeme_type)) {
if (comparison_chains && !first_cmp) {
// load previous constant
gen_constant(0);
gen_operation(opLoadVariable);
}
lexeme = cur_lexeme;
get_next_lexeme();
prev = cur;
cur = state_expression_sum();
cur.is_var = false;
if (comparison_chains && is_comparer(cur_lexeme_type)) {
// save constant for next comparison
gen_constant(0);
gen_operation(opSaveVariable);
}
if (cur.type == vtString && prev.type == vtString) {
switch (lexeme->get_type()) {
case ltSm:
gen_operation(opStrSm);
break;
case ltGr:
gen_operation(opStrGr);
break;
case ltEq:
gen_operation(opStrEq);
break;
case ltNotEq:
gen_operation(opStrNotEq);
break;
default:
throw_type_mismatch(lexeme, prev.type, cur.type);
};
} else {
if (cur.type == vtString || prev.type == vtString ||
cur.type == vtBoolean || prev.type == vtBoolean) {
throw_type_mismatch(lexeme, prev.type, cur.type);
}
if (cur.type == vtReal || prev.type == vtReal) {
switch (lexeme->get_type()) {
case ltSm:
gen_operation(opRealSm);
break;
case ltGr:
gen_operation(opRealGr);
break;
case ltSmEq:
gen_operation(opRealSmEq);
break;
case ltGrEq:
gen_operation(opRealGrEq);
break;
case ltEq:
gen_operation(opRealEq);
break;
case ltNotEq:
gen_operation(opRealNotEq);
break;
default:
throw_type_mismatch(lexeme, prev.type, cur.type);
};
} else {
switch (lexeme->get_type()) {
case ltSm:
gen_operation(opIntSm);
break;
case ltGr:
gen_operation(opIntGr);
break;
case ltSmEq:
gen_operation(opIntSmEq);
break;
case ltGrEq:
gen_operation(opIntGrEq);
break;
case ltEq:
gen_operation(opIntEq);
break;
case ltNotEq:
gen_operation(opIntNotEq);
break;
default:
throw_type_mismatch(lexeme, prev.type, cur.type);
};
}
}
if (!comparison_chains) {
cur.type = vtBoolean;
continue;
}
if (!first_cmp) {
gen_operation(opBoolAnd);
}
first_cmp = false;
}
if (comparison_chains && !first_cmp) {
cur.type = vtBoolean;
}
return cur;
}
ValueInfo SyntaxAnalyzer::state_expression_sum()
{
Lexeme *lexeme;
ValueInfo cur, prev;
cur = state_expression_mul();
while (cur_lexeme_type == ltPlus || cur_lexeme_type == ltMinus) {
lexeme = cur_lexeme;
get_next_lexeme();
prev = cur;
cur = state_expression_mul();
cur.is_var = false;
if (lexeme->get_type() == ltPlus && cur.type == vtString && prev.type == vtString) {
gen_operation(opStrPlus);
cur.type = vtString;
continue;
}
if (cur.type == vtString || prev.type == vtString ||
cur.type == vtBoolean || prev.type == vtBoolean) {
throw_type_mismatch(lexeme, prev.type, cur.type);
}
if (cur.type == vtReal || prev.type == vtReal) {
gen_operation(lexeme->get_type() == ltPlus ? opRealPlus : opRealMinus);
cur.type = vtReal;
} else {
gen_operation(lexeme->get_type() == ltPlus ? opIntPlus : opIntMinus);
cur.type = vtInteger;
}
}
return cur;
}
ValueInfo SyntaxAnalyzer::state_expression_mul()
{
Lexeme *lexeme;
LexemeType lexeme_type;
ValueInfo cur, prev;
cur = state_expression_un();
while (cur_lexeme_type == ltMul || cur_lexeme_type == ltDiv || cur_lexeme_type == ltMod) {
lexeme = cur_lexeme;
lexeme_type = cur_lexeme_type;
get_next_lexeme();
prev = cur;
cur = state_expression_un();
cur.is_var = false;
if (cur.type == vtString || prev.type == vtString ||
cur.type == vtBoolean || prev.type == vtBoolean) {
throw_type_mismatch(lexeme, prev.type, cur.type);
}
if (cur.type == vtReal || prev.type == vtReal) {
if (lexeme_type == ltMul) {
gen_operation(opRealMul);
} else if (lexeme_type == ltDiv) {
gen_operation(opRealDiv);
} else if (lexeme_type == ltMod) {
throw_type_mismatch(lexeme, prev.type, cur.type);
}
cur.type = vtReal;
} else {
if (lexeme_type == ltMul) {
gen_operation(opIntMul);
} else if (lexeme_type == ltDiv) {
gen_operation(opIntDiv);
} else if (lexeme_type == ltMod) {
gen_operation(opIntMod);
}
cur.type = vtInteger;
}
}
return cur;
}
ValueInfo SyntaxAnalyzer::state_expression_un()
{
if (cur_lexeme_type >= ltUnaryOperationsStart && cur_lexeme_type <= ltUnaryOperationsEnd) {
Lexeme *lexeme = cur_lexeme;
LexemeType lexeme_type = cur_lexeme_type;
ValueInfo result;
bool correct = true;
get_next_lexeme();
result = state_expression_un();
result.is_var = false;
switch (result.type) {
case vtInteger:
if (lexeme_type == ltPlusUn) {
gen_operation(opIntPlusUn);
} else if (lexeme_type == ltMinusUn) {
gen_operation(opIntMinusUn);
} else {
correct = false;
}
break;
case vtString:
if (lexeme_type == ltPlusUn) {
gen_operation(opStrPlusUn);
} else {
correct = false;
}
break;
case vtBoolean:
if (lexeme_type == ltNot) {
gen_operation(opBoolNot);
} else {
correct = false;
}
break;
case vtReal:
if (lexeme_type == ltPlusUn) {
gen_operation(opRealPlusUn);
} else if (lexeme_type == ltMinusUn) {
gen_operation(opRealMinusUn);
} else {
correct = false;
}
break;
default:
correct = false;
break;
}
if (!correct) {
throw_semantic_error(lexeme, "type mismatch (" +
value_type_to_string(result.type) + ")");
}
return result;
} else {
return state_operand();
}
}
ValueInfo SyntaxAnalyzer::state_operand()
{
ValueInfo result;
if (cur_lexeme_type >= ltConstantsStart && cur_lexeme_type <= ltConstantsEnd) {
result.type = constant_to_value_type(cur_lexeme_type);
result.is_var = false;
gen_constant(result.type, cur_lexeme->get_value());
get_next_lexeme();
} else if (cur_lexeme_type == ltIdentificator) {
VariableID id = variables.get_number(cur_lexeme->get_value());
if (id < 0) {
throw_semantic_error(cur_lexeme, "variable is not defined");
}
result.type = variables.get_type(id);
result.is_var = true;
gen_constant(id);
gen_operation(opLoadVariable);
get_next_lexeme();
} else if (cur_lexeme_type == ltBracketOpen) {
get_next_lexeme();
result = state_expression();
result.is_var = false;
if (cur_lexeme_type == ltBracketClose) {
get_next_lexeme();
} else {
throw_syntax_error("expected ')'");
}
} else {
throw_syntax_error("expected operand");
}
return result;
}
Program *SyntaxAnalyzer::parse(const LexemeArray &array)
{
lexemes = array;
pos = 0;
get_next_lexeme();
program.clear();
variables.clear();
labels.clear();
state_program();
return new Program(program, variables.size());
}
|
/*
* Author: Thomas Ingleby <thomas.c.ingleby@intel.com>
* Copyright (c) 2014 Intel Corporation.
*
* 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 copies 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 all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 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 "lcm1602.hpp"
#include "upm_utilities.h"
int
main(int argc, char** argv)
{
//! [Interesting]
upm::Lcm1602 lcd(0, 0x27);
lcd.setCursor(0, 0);
lcd.write("Hello World");
//! [Interesting]
upm_delay(3);
lcd.setCursor(1, 2);
lcd.write("Hello World");
upm_delay(3);
lcd.setCursor(2, 4);
lcd.write("Hello World");
upm_delay(3);
lcd.setCursor(3, 6);
lcd.write("Hello World");
upm_delay(3);
return 0;
}
|
#include <cstdlib>
#include <iostream>
#include "aussiegochi.h"
void feedAussie(Aussiegochi& aus)
{
aus.hunger = aus.hunger - 3;
aus.happiness = aus.happiness + 2;
aus.sanity = aus.sanity + 3;
}
void waterAussie(Aussiegochi& aus)
{
aus.thirst = aus.thirst - 3;
aus.happiness = aus.happiness + 2;
aus.sanity = aus.sanity + 3;
}
void abuseAussie(Aussiegochi& aus)
{
aus.sanity = aus.sanity - 8;
aus.happiness = aus.happiness - 4;
}
void coddleAussie(Aussiegochi& aus)
{
aus.happiness = aus.happiness + 5;
aus.sanity = aus.sanity + 3;
}
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
string a,b;
int maru[1000];
int fg = 0;
cin >> a >> b;
int n1,n2,n;
n1 = a.size();
n2 = b.size();
if(n1 > n2)
n = n1;
else
n = n2;
if(n1 > n2)
{
for(int i = 0; i < n;i++)
{
if(a[i] == b[i])
{
maru[fg] = 1;
fg++;
}
else if(a[i] != b[i])
{
maru[fg] = 0;
fg++;
b.insert(i," ");
}
}
cout << a << endl;
cout << b << endl;
}
else if(n1 < n2)
{
for(int i = 0; i < n;i++)
{
if(b[i] == a[i])
{
maru[fg] = 1;
fg++;
}
else if(b[i] != a[i])
{
maru[fg] = 0;
fg++;
a.insert(i," ");
}
}
cout << a << endl;
cout << b << endl;
}
for(int i = 0; i < n; i++)
{
if(maru[i] == 1)
cout << "○";
else
cout << "✗";
}
cout << endl;
}
|
// pch.cpp: plik źródłowy odpowiadający wstępnie skompilowanemu nagłówkowi, niezbędny do powodzenia kompilacji
#include "pch.h"
// Ogólnie rzecz biorąc, zignoruj ten plik, ale miej go pod ręką, jeśli używasz wstępnie skompilowanych nagłówków.
|
/*
* Triplane Classic - a side-scrolling dogfighting game.
* Copyright (C) 1996,1997,2009 Dodekaedron Software Creations Oy
*
* This program 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 version.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
* tjt@users.sourceforge.net
*/
#include "world/tripaudio.h"
#include "settings.h"
#include "world/plane.h"
#include "triplane.h"
#include "util/wutil.h"
sb_mod_file *triplane_mod;
sb_mod_file *aces_mod;
sb_sample *sample_itexp[3];
sb_sample *sample_bomb[4];
sb_sample *sample_hitti;
sb_sample *sample_konsu[4];
sb_sample *sample_propelli;
sb_sample *sample_hit[4];
sb_sample *sample_aagun;
sb_sample *sample_splash[3];
sb_sample *sample_spcrash;
sb_sample *sample_hurr;
sb_sample *sample_itshot;
sb_sample *sample_crash[2];
sb_sample *sample_alku;
sb_sample *sample_die[9];
int alku_sample_over = 0;
int sfx_loaded = 0;
int music_loaded = 0;
void kkbase_sound(int type, int kkbase_x) {
if (config.ground_i_sounds && config.sound_on && config.sfx_on) {
if (type)
play_2d_sample(sample_itshot, player_x_8[solo_country], kkbase_x);
else
play_2d_sample(sample_aagun, player_x_8[solo_country], kkbase_x);
}
}
void itgun_sound(int itgun_x) {
if (config.ground_i_sounds && config.sound_on && config.sfx_on) {
play_2d_sample(sample_itexp[wrandom(3)], player_x_8[solo_country], itgun_x);
}
}
void load_all_samples(void) {
int l;
sample_itexp[0] = sample_load("Itexp1");
sample_itexp[0]->left_volume = SAMPLE_VOLUME;
sample_itexp[0]->right_volume = SAMPLE_VOLUME;
sample_itexp[1] = sample_load("Itexp2");
sample_itexp[1]->left_volume = SAMPLE_VOLUME;
sample_itexp[1]->right_volume = SAMPLE_VOLUME;
sample_itexp[2] = sample_load("Itexp3");
sample_itexp[2]->left_volume = SAMPLE_VOLUME;
sample_itexp[2]->right_volume = SAMPLE_VOLUME;
sample_bomb[1] = sample_load("Bomb1");
sample_bomb[1]->left_volume = SAMPLE_VOLUME;
sample_bomb[1]->right_volume = SAMPLE_VOLUME;
sample_bomb[2] = sample_load("Bomb2");
sample_bomb[2]->left_volume = SAMPLE_VOLUME;
sample_bomb[2]->right_volume = SAMPLE_VOLUME;
sample_bomb[3] = sample_load("Bomb3");
sample_bomb[3]->left_volume = SAMPLE_VOLUME;
sample_bomb[3]->right_volume = SAMPLE_VOLUME;
sample_konsu[1] = sample_load("Guns1");
sample_konsu[1]->left_volume = SAMPLE_VOLUME;
sample_konsu[1]->right_volume = SAMPLE_VOLUME;
sample_konsu[2] = sample_load("Guns2");
sample_konsu[2]->left_volume = SAMPLE_VOLUME;
sample_konsu[2]->right_volume = SAMPLE_VOLUME;
sample_konsu[3] = sample_load("Guns3");
sample_konsu[3]->left_volume = SAMPLE_VOLUME;
sample_konsu[3]->right_volume = SAMPLE_VOLUME;
sample_hit[0] = sample_load("Hit1");
sample_hit[0]->left_volume = SAMPLE_VOLUME;
sample_hit[0]->right_volume = SAMPLE_VOLUME;
sample_hit[1] = sample_load("Hit2");
sample_hit[1]->left_volume = SAMPLE_VOLUME;
sample_hit[1]->right_volume = SAMPLE_VOLUME;
sample_hit[2] = sample_load("Hit3");
sample_hit[2]->left_volume = SAMPLE_VOLUME;
sample_hit[2]->right_volume = SAMPLE_VOLUME;
sample_hit[3] = sample_load("Hit4");
sample_hit[3]->left_volume = SAMPLE_VOLUME;
sample_hit[3]->right_volume = SAMPLE_VOLUME;
sample_aagun = sample_load("Aagun");
sample_aagun->left_volume = SAMPLE_VOLUME;
sample_aagun->right_volume = SAMPLE_VOLUME;
sample_splash[0] = sample_load("Spla1");
sample_splash[0]->left_volume = SAMPLE_VOLUME;
sample_splash[0]->right_volume = SAMPLE_VOLUME;
sample_splash[1] = sample_load("Spla2");
sample_splash[1]->left_volume = SAMPLE_VOLUME;
sample_splash[1]->right_volume = SAMPLE_VOLUME;
sample_splash[2] = sample_load("Spla3");
sample_splash[2]->left_volume = SAMPLE_VOLUME;
sample_splash[2]->right_volume = SAMPLE_VOLUME;
sample_hurr = sample_load("Hurr");
sample_hurr->left_volume = SAMPLE_VOLUME;
sample_hurr->right_volume = SAMPLE_VOLUME;
sample_itshot = sample_load("Itshot");
sample_itshot->left_volume = SAMPLE_VOLUME;
sample_itshot->right_volume = SAMPLE_VOLUME;
sample_spcrash = sample_load("Spcra1");
sample_spcrash->left_volume = SAMPLE_VOLUME;
sample_spcrash->right_volume = SAMPLE_VOLUME;
sample_crash[0] = sample_load("Crash1");
sample_crash[0]->left_volume = SAMPLE_VOLUME;
sample_crash[0]->right_volume = SAMPLE_VOLUME;
sample_crash[1] = sample_load("Crash2");
sample_crash[1]->left_volume = SAMPLE_VOLUME;
sample_crash[1]->right_volume = SAMPLE_VOLUME;
sample_alku = sample_load("Alku");
sample_alku->left_volume = 32;
sample_alku->right_volume = 32;
sample_die[0] = sample_load("Die1");
sample_die[1] = sample_load("Die2");
sample_die[2] = sample_load("Die3");
sample_die[3] = sample_load("Die4");
sample_die[4] = sample_load("Die5");
sample_die[5] = sample_load("Die6");
sample_die[6] = sample_load("Die7");
sample_die[7] = sample_load("Die8");
sample_die[8] = sample_load("Die9");
for (l = 0; l < 9; l++) {
sample_die[l]->left_volume = SAMPLE_VOLUME - 8;
sample_die[l]->right_volume = SAMPLE_VOLUME - 8;
}
}
void load_sfx(void) {
sfx_loaded = 1;
load_all_samples();
}
void load_music(void) {
music_loaded = 1;
triplane_mod = sdl_load_mod_file("music1");
aces_mod = sdl_load_mod_file("maces");
}
void clear_sfx(void) {
int l;
sfx_loaded = 0;
sdl_free_sample(sample_itexp[0]);
sdl_free_sample(sample_itexp[1]);
sdl_free_sample(sample_itexp[2]);
sdl_free_sample(sample_bomb[1]);
sdl_free_sample(sample_bomb[2]);
sdl_free_sample(sample_bomb[3]);
sdl_free_sample(sample_konsu[1]);
sdl_free_sample(sample_konsu[2]);
sdl_free_sample(sample_konsu[3]);
sdl_free_sample(sample_hit[0]);
sdl_free_sample(sample_hit[1]);
sdl_free_sample(sample_hit[2]);
sdl_free_sample(sample_hit[3]);
sdl_free_sample(sample_aagun);
sdl_free_sample(sample_splash[0]);
sdl_free_sample(sample_splash[1]);
sdl_free_sample(sample_splash[2]);
sdl_free_sample(sample_hurr);
sdl_free_sample(sample_spcrash);
sdl_free_sample(sample_itshot);
sdl_free_sample(sample_crash[0]);
sdl_free_sample(sample_crash[1]);
sdl_free_sample(sample_alku);
for (l = 0; l < 9; l++) {
sdl_free_sample(sample_die[l]);
}
}
void clear_music(void) {
music_loaded = 0;
sdl_free_mod_file(triplane_mod);
sdl_free_mod_file(aces_mod);
}
|
/**
* @file
* @copyright defined in evt/LICENSE.txt
*/
#pragma once
#include <appbase/application.hpp>
#include <evt/chain_plugin/chain_plugin.hpp>
namespace fc {
class variant;
}
namespace evt {
using chain::transaction_id_type;
using std::shared_ptr;
using namespace appbase;
using chain::name;
using chain::uint128_t;
using fc::optional;
typedef shared_ptr<class bnet_plugin_impl> bnet_ptr;
typedef shared_ptr<const class bnet_plugin_impl> bnet_const_ptr;
class bnet_plugin : public plugin<bnet_plugin> {
public:
APPBASE_PLUGIN_REQUIRES((chain_plugin))
bnet_plugin();
virtual ~bnet_plugin();
virtual void set_program_options(options_description& cli, options_description& cfg) override;
void plugin_initialize(const variables_map& options);
void plugin_startup();
void plugin_shutdown();
private:
bnet_ptr my;
};
} // namespace evt
|
/*
* Copyright (c) 2017 Peter Conrad, and other contributors.
*
* The MIT License
*
* 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
* copies 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
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER 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 <boost/test/unit_test.hpp>
#include <graphene/chain/hardfork.hpp>
#include <graphene/protocol/market.hpp>
#include <graphene/chain/market_object.hpp>
#include "../common/database_fixture.hpp"
using namespace graphene::chain;
using namespace graphene::chain::test;
BOOST_FIXTURE_TEST_SUITE(market_tests, database_fixture)
/***
* Reproduce bitshares-core issue #338 #343 #453 #606 #625 #649
*/
BOOST_AUTO_TEST_CASE(issue_338_etc)
{ try {
generate_blocks(HARDFORK_615_TIME); // get around Graphene issue #615 feed expiration bug
generate_block();
set_expiration( db, trx );
ACTORS((buyer)(seller)(borrower)(borrower2)(borrower3)(feedproducer));
const auto& bitusd = create_bitasset("USDBIT", feedproducer_id);
const auto& core = asset_id_type()(db);
asset_id_type usd_id = bitusd.id;
asset_id_type core_id = core.id;
int64_t init_balance(1000000);
transfer(committee_account, buyer_id, asset(init_balance));
transfer(committee_account, borrower_id, asset(init_balance));
transfer(committee_account, borrower2_id, asset(init_balance));
transfer(committee_account, borrower3_id, asset(init_balance));
update_feed_producers( bitusd, {feedproducer.id} );
price_feed current_feed;
current_feed.maintenance_collateral_ratio = 1750;
current_feed.maximum_short_squeeze_ratio = 1100;
current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(5);
publish_feed( bitusd, feedproducer, current_feed );
// start out with 300% collateral, call price is 15/1.75 CORE/USD = 60/7
const call_order_object& call = *borrow( borrower, bitusd.amount(1000), asset(15000));
call_order_id_type call_id = call.id;
// create another position with 310% collateral, call price is 15.5/1.75 CORE/USD = 62/7
const call_order_object& call2 = *borrow( borrower2, bitusd.amount(1000), asset(15500));
call_order_id_type call2_id = call2.id;
// create yet another position with 320% collateral, call price is 16/1.75 CORE/USD = 64/7
const call_order_object& call3 = *borrow( borrower3, bitusd.amount(1000), asset(16000));
call_order_id_type call3_id = call3.id;
transfer(borrower, seller, bitusd.amount(1000));
BOOST_CHECK_EQUAL( 1000, call.debt.value );
BOOST_CHECK_EQUAL( 15000, call.collateral.value );
BOOST_CHECK_EQUAL( 1000, get_balance(seller, bitusd) );
BOOST_CHECK_EQUAL( 0, get_balance(seller, core) );
// adjust price feed to get call_order into margin call territory
current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(10);
publish_feed( bitusd, feedproducer, current_feed );
// settlement price = 1/10, mssp = 1/11
// This order slightly below the call price will not be matched #606
limit_order_id_type sell_low = create_sell_order(seller, bitusd.amount(7), core.amount(59))->id;
// This order above the MSSP will not be matched
limit_order_id_type sell_high = create_sell_order(seller, bitusd.amount(7), core.amount(78))->id;
// This would match but is blocked by sell_low?! #606
limit_order_id_type sell_med = create_sell_order(seller, bitusd.amount(7), core.amount(60))->id;
cancel_limit_order( sell_med(db) );
cancel_limit_order( sell_high(db) );
cancel_limit_order( sell_low(db) );
// current implementation: an incoming limit order will be filled at the
// requested price #338
BOOST_CHECK( !create_sell_order(seller, bitusd.amount(7), core.amount(60)) );
BOOST_CHECK_EQUAL( 993, get_balance(seller, bitusd) );
BOOST_CHECK_EQUAL( 60, get_balance(seller, core) );
BOOST_CHECK_EQUAL( 993, call.debt.value );
BOOST_CHECK_EQUAL( 14940, call.collateral.value );
limit_order_id_type buy_low = create_sell_order(buyer, asset(90), bitusd.amount(10))->id;
// margin call takes precedence
BOOST_CHECK( !create_sell_order(seller, bitusd.amount(7), core.amount(60)) );
BOOST_CHECK_EQUAL( 986, get_balance(seller, bitusd) );
BOOST_CHECK_EQUAL( 120, get_balance(seller, core) );
BOOST_CHECK_EQUAL( 986, call.debt.value );
BOOST_CHECK_EQUAL( 14880, call.collateral.value );
limit_order_id_type buy_med = create_sell_order(buyer, asset(105), bitusd.amount(10))->id;
// margin call takes precedence
BOOST_CHECK( !create_sell_order(seller, bitusd.amount(7), core.amount(70)) );
BOOST_CHECK_EQUAL( 979, get_balance(seller, bitusd) );
BOOST_CHECK_EQUAL( 190, get_balance(seller, core) );
BOOST_CHECK_EQUAL( 979, call.debt.value );
BOOST_CHECK_EQUAL( 14810, call.collateral.value );
limit_order_id_type buy_high = create_sell_order(buyer, asset(115), bitusd.amount(10))->id;
// margin call still has precedence (!) #625
BOOST_CHECK( !create_sell_order(seller, bitusd.amount(7), core.amount(77)) );
BOOST_CHECK_EQUAL( 972, get_balance(seller, bitusd) );
BOOST_CHECK_EQUAL( 267, get_balance(seller, core) );
BOOST_CHECK_EQUAL( 972, call.debt.value );
BOOST_CHECK_EQUAL( 14733, call.collateral.value );
cancel_limit_order( buy_high(db) );
cancel_limit_order( buy_med(db) );
cancel_limit_order( buy_low(db) );
// call with more usd
BOOST_CHECK( !create_sell_order(seller, bitusd.amount(700), core.amount(7700)) );
BOOST_CHECK_EQUAL( 272, get_balance(seller, bitusd) );
BOOST_CHECK_EQUAL( 7967, get_balance(seller, core) );
BOOST_CHECK_EQUAL( 272, call.debt.value );
BOOST_CHECK_EQUAL( 7033, call.collateral.value );
// at this moment, collateralization of call is 7033 / 272 = 25.8
// collateralization of call2 is 15500 / 1000 = 15.5
// collateralization of call3 is 16000 / 1000 = 16
// call more, still matches with the first call order #343
BOOST_CHECK( !create_sell_order(seller, bitusd.amount(10), core.amount(110)) );
BOOST_CHECK_EQUAL( 262, get_balance(seller, bitusd) );
BOOST_CHECK_EQUAL( 8077, get_balance(seller, core) );
BOOST_CHECK_EQUAL( 262, call.debt.value );
BOOST_CHECK_EQUAL( 6923, call.collateral.value );
// at this moment, collateralization of call is 6923 / 262 = 26.4
// collateralization of call2 is 15500 / 1000 = 15.5
// collateralization of call3 is 16000 / 1000 = 16
// force settle
force_settle( seller, bitusd.amount(10) );
BOOST_CHECK_EQUAL( 252, get_balance(seller, bitusd) );
BOOST_CHECK_EQUAL( 8077, get_balance(seller, core) );
BOOST_CHECK_EQUAL( 262, call.debt.value );
BOOST_CHECK_EQUAL( 6923, call.collateral.value );
// generate blocks to let the settle order execute (price feed will expire after it)
generate_blocks( HARDFORK_615_TIME + fc::hours(25) );
// call2 get settled #343
BOOST_CHECK_EQUAL( 252, get_balance(seller_id, usd_id) );
BOOST_CHECK_EQUAL( 8177, get_balance(seller_id, core_id) );
BOOST_CHECK_EQUAL( 262, call_id(db).debt.value );
BOOST_CHECK_EQUAL( 6923, call_id(db).collateral.value );
BOOST_CHECK_EQUAL( 990, call2_id(db).debt.value );
BOOST_CHECK_EQUAL( 15400, call2_id(db).collateral.value );
set_expiration( db, trx );
update_feed_producers( usd_id(db), {feedproducer_id} );
// at this moment, collateralization of call is 8177 / 252 = 32.4
// collateralization of call2 is 15400 / 990 = 15.5
// collateralization of call3 is 16000 / 1000 = 16
// adjust price feed to get call2 into black swan territory, but not the first call order
current_feed.settlement_price = asset(1, usd_id) / asset(20, core_id);
publish_feed( usd_id(db), feedproducer_id(db), current_feed );
// settlement price = 1/20, mssp = 1/22
// black swan event doesn't occur #649
BOOST_CHECK( !usd_id(db).bitasset_data(db).has_settlement() );
// generate a block
generate_block();
set_expiration( db, trx );
update_feed_producers( usd_id(db), {feedproducer_id} );
// adjust price feed back
current_feed.settlement_price = asset(1, usd_id) / asset(10, core_id);
publish_feed( usd_id(db), feedproducer_id(db), current_feed );
// settlement price = 1/10, mssp = 1/11
transfer(borrower2_id, seller_id, asset(1000, usd_id));
transfer(borrower3_id, seller_id, asset(1000, usd_id));
// Re-create sell_low, slightly below the call price, will not be matched, will expire soon
sell_low = create_sell_order(seller_id(db), asset(7, usd_id), asset(59), db.head_block_time()+fc::seconds(300) )->id;
// This would match but is blocked by sell_low, it has an amount same as call's debt which will be full filled later
sell_med = create_sell_order(seller_id(db), asset(262, usd_id), asset(2620))->id; // 1/10
// Another big order above sell_med, blocked
limit_order_id_type sell_med2 = create_sell_order(seller_id(db), asset(1200, usd_id), asset(12120))->id; // 1/10.1
// Another small order above sell_med2, blocked
limit_order_id_type sell_med3 = create_sell_order(seller_id(db), asset(120, usd_id), asset(1224))->id; // 1/10.2
// generate a block, sell_low will expire
BOOST_TEST_MESSAGE( "Expire sell_low" );
generate_blocks( HARDFORK_615_TIME + fc::hours(26) );
BOOST_CHECK( db.find<limit_order_object>( sell_low ) == nullptr );
// #453 multiple order matching issue occurs
BOOST_CHECK( db.find<limit_order_object>( sell_med ) == nullptr ); // sell_med get filled
BOOST_CHECK( db.find<limit_order_object>( sell_med2 ) != nullptr ); // sell_med2 is still there
BOOST_CHECK( db.find<limit_order_object>( sell_med3 ) == nullptr ); // sell_med3 get filled
BOOST_CHECK( db.find<call_order_object>( call_id ) == nullptr ); // the first call order get filled
BOOST_CHECK( db.find<call_order_object>( call2_id ) == nullptr ); // the second call order get filled
BOOST_CHECK( db.find<call_order_object>( call3_id ) != nullptr ); // the third call order is still there
} FC_LOG_AND_RETHROW() }
/***
* Fixed bitshares-core issue #338 #343 #606 #625 #649
*/
BOOST_AUTO_TEST_CASE(hardfork_core_338_test)
{ try {
auto mi = db.get_global_properties().parameters.maintenance_interval;
if(hf1270)
generate_blocks(HARDFORK_CORE_1270_TIME - mi);
else
generate_blocks(HARDFORK_CORE_343_TIME - mi);
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
set_expiration( db, trx );
ACTORS((buyer)(seller)(borrower)(borrower2)(borrower3)(feedproducer));
const auto& bitusd = create_bitasset("USDBIT", feedproducer_id);
const auto& core = asset_id_type()(db);
asset_id_type usd_id = bitusd.id;
asset_id_type core_id = core.id;
int64_t init_balance(1000000);
transfer(committee_account, buyer_id, asset(init_balance));
transfer(committee_account, borrower_id, asset(init_balance));
transfer(committee_account, borrower2_id, asset(init_balance));
transfer(committee_account, borrower3_id, asset(init_balance));
update_feed_producers( bitusd, {feedproducer.id} );
price_feed current_feed;
current_feed.maintenance_collateral_ratio = 1750;
current_feed.maximum_short_squeeze_ratio = 1100;
current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(5);
publish_feed( bitusd, feedproducer, current_feed );
// start out with 300% collateral, call price is 15/1.75 CORE/USD = 60/7
const call_order_object& call = *borrow( borrower, bitusd.amount(1000), asset(15000));
call_order_id_type call_id = call.id;
// create another position with 310% collateral, call price is 15.5/1.75 CORE/USD = 62/7
const call_order_object& call2 = *borrow( borrower2, bitusd.amount(1000), asset(15500));
call_order_id_type call2_id = call2.id;
// create yet another position with 320% collateral, call price is 16/1.75 CORE/USD = 64/7
const call_order_object& call3 = *borrow( borrower3, bitusd.amount(1000), asset(16000));
call_order_id_type call3_id = call3.id;
transfer(borrower, seller, bitusd.amount(1000));
transfer(borrower2, seller, bitusd.amount(1000));
transfer(borrower3, seller, bitusd.amount(1000));
BOOST_CHECK_EQUAL( 1000, call.debt.value );
BOOST_CHECK_EQUAL( 15000, call.collateral.value );
BOOST_CHECK_EQUAL( 1000, call2.debt.value );
BOOST_CHECK_EQUAL( 15500, call2.collateral.value );
BOOST_CHECK_EQUAL( 1000, call3.debt.value );
BOOST_CHECK_EQUAL( 16000, call3.collateral.value );
BOOST_CHECK_EQUAL( 3000, get_balance(seller, bitusd) );
BOOST_CHECK_EQUAL( 0, get_balance(seller, core) );
// adjust price feed to get call_order into margin call territory
current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(10);
publish_feed( bitusd, feedproducer, current_feed );
// settlement price = 1/10, mssp = 1/11
// This sell order above MSSP will not be matched with a call
BOOST_CHECK( create_sell_order(seller, bitusd.amount(7), core.amount(78)) != nullptr );
BOOST_CHECK_EQUAL( 2993, get_balance(seller, bitusd) );
BOOST_CHECK_EQUAL( 0, get_balance(seller, core) );
// This buy order is too low will not be matched with a sell order
limit_order_id_type buy_low = create_sell_order(buyer, asset(90), bitusd.amount(10))->id;
// This buy order at MSSP will be matched only if no margin call (margin call takes precedence)
limit_order_id_type buy_med = create_sell_order(buyer, asset(110), bitusd.amount(10))->id;
// This buy order above MSSP will be matched with a sell order (limit order with better price takes precedence)
limit_order_id_type buy_high = create_sell_order(buyer, asset(111), bitusd.amount(10))->id;
BOOST_CHECK_EQUAL( 0, get_balance(buyer, bitusd) );
BOOST_CHECK_EQUAL( init_balance - 90 - 110 - 111, get_balance(buyer, core) );
// This order slightly below the call price will be matched: #606 fixed
BOOST_CHECK( !create_sell_order(seller, bitusd.amount(700), core.amount(5900) ) );
// firstly it will match with buy_high, at buy_high's price: #625 fixed
BOOST_CHECK( !db.find<limit_order_object>( buy_high ) );
BOOST_CHECK_EQUAL( db.find<limit_order_object>( buy_med )->for_sale.value, 110 );
BOOST_CHECK_EQUAL( db.find<limit_order_object>( buy_low )->for_sale.value, 90 );
// buy_high pays 111 CORE, receives 10 USD goes to buyer's balance
BOOST_CHECK_EQUAL( 10, get_balance(buyer, bitusd) );
BOOST_CHECK_EQUAL( init_balance - 90 - 110 - 111, get_balance(buyer, core) );
// sell order pays 10 USD, receives 111 CORE, remaining 690 USD for sale, still at price 7/59
// then it will match with call, at mssp: 1/11 = 690/7590 : #338 fixed
BOOST_CHECK_EQUAL( 2293, get_balance(seller, bitusd) );
BOOST_CHECK_EQUAL( 7701, get_balance(seller, core) );
BOOST_CHECK_EQUAL( 310, call.debt.value );
BOOST_CHECK_EQUAL( 7410, call.collateral.value );
BOOST_CHECK_EQUAL( 1000, call2.debt.value );
BOOST_CHECK_EQUAL( 15500, call2.collateral.value );
BOOST_CHECK_EQUAL( 1000, call3.debt.value );
BOOST_CHECK_EQUAL( 16000, call3.collateral.value );
// call's call_price will be updated after the match, to 741/31/1.75 CORE/USD = 2964/217
// it's above settlement price (10/1) so won't be margin called again
if(!hf1270) // can use call price only if we are before hf1270
BOOST_CHECK( price(asset(2964),asset(217,usd_id)) == call.call_price );
// This would match with call before, but would match with call2 after #343 fixed
BOOST_CHECK( !create_sell_order(seller, bitusd.amount(700), core.amount(6000) ) );
BOOST_CHECK_EQUAL( db.find<limit_order_object>( buy_med )->for_sale.value, 110 );
BOOST_CHECK_EQUAL( db.find<limit_order_object>( buy_low )->for_sale.value, 90 );
// fill price would be mssp: 1/11 = 700/7700 : #338 fixed
BOOST_CHECK_EQUAL( 1593, get_balance(seller, bitusd) );
BOOST_CHECK_EQUAL( 15401, get_balance(seller, core) );
BOOST_CHECK_EQUAL( 310, call.debt.value );
BOOST_CHECK_EQUAL( 7410, call.collateral.value );
BOOST_CHECK_EQUAL( 300, call2.debt.value );
BOOST_CHECK_EQUAL( 7800, call2.collateral.value );
BOOST_CHECK_EQUAL( 1000, call3.debt.value );
BOOST_CHECK_EQUAL( 16000, call3.collateral.value );
// call2's call_price will be updated after the match, to 78/3/1.75 CORE/USD = 312/21
if(!hf1270) // can use call price only if we are before hf1270
BOOST_CHECK( price(asset(312),asset(21,usd_id)) == call2.call_price );
// it's above settlement price (10/1) so won't be margin called
// at this moment, collateralization of call is 7410 / 310 = 23.9
// collateralization of call2 is 7800 / 300 = 26
// collateralization of call3 is 16000 / 1000 = 16
// force settle
force_settle( seller, bitusd.amount(10) );
BOOST_CHECK_EQUAL( 1583, get_balance(seller, bitusd) );
BOOST_CHECK_EQUAL( 15401, get_balance(seller, core) );
BOOST_CHECK_EQUAL( 310, call.debt.value );
BOOST_CHECK_EQUAL( 7410, call.collateral.value );
BOOST_CHECK_EQUAL( 300, call2.debt.value );
BOOST_CHECK_EQUAL( 7800, call2.collateral.value );
BOOST_CHECK_EQUAL( 1000, call3.debt.value );
BOOST_CHECK_EQUAL( 16000, call3.collateral.value );
// generate blocks to let the settle order execute (price feed will expire after it)
generate_block();
generate_blocks( db.head_block_time() + fc::hours(24) );
// call3 get settled, at settlement price 1/10: #343 fixed
BOOST_CHECK_EQUAL( 1583, get_balance(seller_id, usd_id) );
BOOST_CHECK_EQUAL( 15501, get_balance(seller_id, core_id) );
BOOST_CHECK_EQUAL( 310, call_id(db).debt.value );
BOOST_CHECK_EQUAL( 7410, call_id(db).collateral.value );
BOOST_CHECK_EQUAL( 300, call2_id(db).debt.value );
BOOST_CHECK_EQUAL( 7800, call2_id(db).collateral.value );
BOOST_CHECK_EQUAL( 990, call3_id(db).debt.value );
BOOST_CHECK_EQUAL( 15900, call3_id(db).collateral.value );
set_expiration( db, trx );
update_feed_producers( usd_id(db), {feedproducer_id} );
// at this moment, collateralization of call is 7410 / 310 = 23.9
// collateralization of call2 is 7800 / 300 = 26
// collateralization of call3 is 15900 / 990 = 16.06
// adjust price feed to get call3 into black swan territory, but not the other call orders
// Note: after hard fork, black swan should occur when callateralization < mssp, but not at < feed
current_feed.settlement_price = asset(1, usd_id) / asset(16, core_id);
publish_feed( usd_id(db), feedproducer_id(db), current_feed );
// settlement price = 1/16, mssp = 10/176
// black swan event will occur: #649 fixed
BOOST_CHECK( usd_id(db).bitasset_data(db).has_settlement() );
// short positions will be closed
BOOST_CHECK( !db.find<call_order_object>( call_id ) );
BOOST_CHECK( !db.find<call_order_object>( call2_id ) );
BOOST_CHECK( !db.find<call_order_object>( call3_id ) );
// generate a block
generate_block();
} FC_LOG_AND_RETHROW() }
/***
* Fixed bitshares-core issue #453: multiple limit order filling issue
*/
BOOST_AUTO_TEST_CASE(hardfork_core_453_test)
{ try {
auto mi = db.get_global_properties().parameters.maintenance_interval;
if(hf1270)
generate_blocks(HARDFORK_CORE_1270_TIME - mi);
else
generate_blocks(HARDFORK_CORE_343_TIME - mi);
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
set_expiration( db, trx );
ACTORS((buyer)(seller)(borrower)(borrower2)(borrower3)(feedproducer));
const auto& bitusd = create_bitasset("USDBIT", feedproducer_id);
const auto& core = asset_id_type()(db);
asset_id_type usd_id = bitusd.id;
int64_t init_balance(1000000);
transfer(committee_account, buyer_id, asset(init_balance));
transfer(committee_account, borrower_id, asset(init_balance));
transfer(committee_account, borrower2_id, asset(init_balance));
transfer(committee_account, borrower3_id, asset(init_balance));
update_feed_producers( bitusd, {feedproducer.id} );
price_feed current_feed;
current_feed.maintenance_collateral_ratio = 1750;
current_feed.maximum_short_squeeze_ratio = 1100;
current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(5);
publish_feed( bitusd, feedproducer, current_feed );
// start out with 300% collateral, call price is 15/1.75 CORE/USD = 60/7
const call_order_object& call = *borrow( borrower, bitusd.amount(1000), asset(15000));
call_order_id_type call_id = call.id;
// create another position with 310% collateral, call price is 15.5/1.75 CORE/USD = 62/7
const call_order_object& call2 = *borrow( borrower2, bitusd.amount(1000), asset(15500));
call_order_id_type call2_id = call2.id;
// create yet another position with 320% collateral, call price is 16/1.75 CORE/USD = 64/7
const call_order_object& call3 = *borrow( borrower3, bitusd.amount(1000), asset(16000));
call_order_id_type call3_id = call3.id;
transfer(borrower, seller, bitusd.amount(1000));
transfer(borrower2, seller, bitusd.amount(1000));
transfer(borrower3, seller, bitusd.amount(1000));
BOOST_CHECK_EQUAL( 1000, call.debt.value );
BOOST_CHECK_EQUAL( 15000, call.collateral.value );
BOOST_CHECK_EQUAL( 1000, call2.debt.value );
BOOST_CHECK_EQUAL( 15500, call2.collateral.value );
BOOST_CHECK_EQUAL( 1000, call3.debt.value );
BOOST_CHECK_EQUAL( 16000, call3.collateral.value );
BOOST_CHECK_EQUAL( 3000, get_balance(seller, bitusd) );
BOOST_CHECK_EQUAL( 0, get_balance(seller, core) );
// no margin call so far
// This order would match call when it's margin called, it has an amount same as call's debt which will be full filled later
limit_order_id_type sell_med = create_sell_order(seller_id(db), asset(1000, usd_id), asset(10000))->id; // 1/10
// Another big order above sell_med, amount bigger than call2's debt
limit_order_id_type sell_med2 = create_sell_order(seller_id(db), asset(1200, usd_id), asset(12120))->id; // 1/10.1
// Another small order above sell_med2
limit_order_id_type sell_med3 = create_sell_order(seller_id(db), asset(120, usd_id), asset(1224))->id; // 1/10.2
// adjust price feed to get the call orders into margin call territory
current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(10);
publish_feed( bitusd, feedproducer, current_feed );
// settlement price = 1/10, mssp = 1/11
// Fixed #453 multiple order matching issue occurs
BOOST_CHECK( !db.find<limit_order_object>( sell_med ) ); // sell_med get filled
BOOST_CHECK( !db.find<limit_order_object>( sell_med2 ) ); // sell_med2 get filled
BOOST_CHECK( !db.find<limit_order_object>( sell_med3 ) ); // sell_med3 get filled
BOOST_CHECK( !db.find<call_order_object>( call_id ) ); // the first call order get filled
BOOST_CHECK( !db.find<call_order_object>( call2_id ) ); // the second call order get filled
BOOST_CHECK( db.find<call_order_object>( call3_id ) ); // the third call order is still there
// generate a block
generate_block();
} FC_LOG_AND_RETHROW() }
/***
* Tests (big) limit order matching logic after #625 got fixed
*/
BOOST_AUTO_TEST_CASE(hardfork_core_625_big_limit_order_test)
{ try {
auto mi = db.get_global_properties().parameters.maintenance_interval;
if(hf1270)
generate_blocks(HARDFORK_CORE_1270_TIME - mi);
else
generate_blocks(HARDFORK_CORE_625_TIME - mi);
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
set_expiration( db, trx );
ACTORS((buyer)(buyer2)(buyer3)(seller)(borrower)(borrower2)(borrower3)(feedproducer));
const auto& bitusd = create_bitasset("USDBIT", feedproducer_id);
const auto& core = asset_id_type()(db);
int64_t init_balance(1000000);
transfer(committee_account, buyer_id, asset(init_balance));
transfer(committee_account, buyer2_id, asset(init_balance));
transfer(committee_account, buyer3_id, asset(init_balance));
transfer(committee_account, borrower_id, asset(init_balance));
transfer(committee_account, borrower2_id, asset(init_balance));
transfer(committee_account, borrower3_id, asset(init_balance));
update_feed_producers( bitusd, {feedproducer.id} );
price_feed current_feed;
current_feed.maintenance_collateral_ratio = 1750;
current_feed.maximum_short_squeeze_ratio = 1100;
current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(5);
publish_feed( bitusd, feedproducer, current_feed );
// start out with 300% collateral, call price is 15/1.75 CORE/USD = 60/7
const call_order_object& call = *borrow( borrower, bitusd.amount(1000), asset(15000));
call_order_id_type call_id = call.id;
// create another position with 310% collateral, call price is 15.5/1.75 CORE/USD = 62/7
const call_order_object& call2 = *borrow( borrower2, bitusd.amount(1000), asset(15500));
call_order_id_type call2_id = call2.id;
// create yet another position with 500% collateral, call price is 25/1.75 CORE/USD = 100/7
const call_order_object& call3 = *borrow( borrower3, bitusd.amount(1000), asset(25000));
transfer(borrower, seller, bitusd.amount(1000));
transfer(borrower2, seller, bitusd.amount(1000));
transfer(borrower3, seller, bitusd.amount(1000));
BOOST_CHECK_EQUAL( 1000, call.debt.value );
BOOST_CHECK_EQUAL( 15000, call.collateral.value );
BOOST_CHECK_EQUAL( 1000, call2.debt.value );
BOOST_CHECK_EQUAL( 15500, call2.collateral.value );
BOOST_CHECK_EQUAL( 1000, call3.debt.value );
BOOST_CHECK_EQUAL( 25000, call3.collateral.value );
BOOST_CHECK_EQUAL( 3000, get_balance(seller, bitusd) );
BOOST_CHECK_EQUAL( 0, get_balance(seller, core) );
BOOST_CHECK_EQUAL( 3000, get_balance(seller, bitusd) );
BOOST_CHECK_EQUAL( init_balance - 15000, get_balance(borrower, core) );
BOOST_CHECK_EQUAL( init_balance - 15500, get_balance(borrower2, core) );
BOOST_CHECK_EQUAL( init_balance - 25000, get_balance(borrower3, core) );
BOOST_CHECK_EQUAL( 0, get_balance(borrower, bitusd) );
BOOST_CHECK_EQUAL( 0, get_balance(borrower2, bitusd) );
BOOST_CHECK_EQUAL( 0, get_balance(borrower3, bitusd) );
// adjust price feed to get call and call2 (but not call3) into margin call territory
current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(10);
publish_feed( bitusd, feedproducer, current_feed );
// settlement price = 1/10, mssp = 1/11
// This sell order above MSSP will not be matched with a call
limit_order_id_type sell_high = create_sell_order(seller, bitusd.amount(7), core.amount(78))->id;
BOOST_CHECK_EQUAL( db.find<limit_order_object>( sell_high )->for_sale.value, 7 );
BOOST_CHECK_EQUAL( 2993, get_balance(seller, bitusd) );
BOOST_CHECK_EQUAL( 0, get_balance(seller, core) );
// This buy order is too low will not be matched with a sell order
limit_order_id_type buy_low = create_sell_order(buyer, asset(80), bitusd.amount(10))->id;
// This buy order at MSSP will be matched only if no margin call (margin call takes precedence)
limit_order_id_type buy_med = create_sell_order(buyer2, asset(11000), bitusd.amount(1000))->id;
// This buy order above MSSP will be matched with a sell order (limit order with better price takes precedence)
limit_order_id_type buy_high = create_sell_order(buyer3, asset(111), bitusd.amount(10))->id;
BOOST_CHECK_EQUAL( 0, get_balance(buyer, bitusd) );
BOOST_CHECK_EQUAL( 0, get_balance(buyer2, bitusd) );
BOOST_CHECK_EQUAL( 0, get_balance(buyer3, bitusd) );
BOOST_CHECK_EQUAL( init_balance - 80, get_balance(buyer, core) );
BOOST_CHECK_EQUAL( init_balance - 11000, get_balance(buyer2, core) );
BOOST_CHECK_EQUAL( init_balance - 111, get_balance(buyer3, core) );
// Create a big sell order slightly below the call price, will be matched with several orders
BOOST_CHECK( !create_sell_order(seller, bitusd.amount(700*4), core.amount(5900*4) ) );
// firstly it will match with buy_high, at buy_high's price
BOOST_CHECK( !db.find<limit_order_object>( buy_high ) );
// buy_high pays 111 CORE, receives 10 USD goes to buyer3's balance
BOOST_CHECK_EQUAL( 10, get_balance(buyer3, bitusd) );
BOOST_CHECK_EQUAL( init_balance - 111, get_balance(buyer3, core) );
// then it will match with call, at mssp: 1/11 = 1000/11000
BOOST_CHECK( !db.find<call_order_object>( call_id ) );
// call pays 11000 CORE, receives 1000 USD to cover borrower's position, remaining CORE goes to borrower's balance
BOOST_CHECK_EQUAL( init_balance - 11000, get_balance(borrower, core) );
BOOST_CHECK_EQUAL( 0, get_balance(borrower, bitusd) );
// then it will match with call2, at mssp: 1/11 = 1000/11000
BOOST_CHECK( !db.find<call_order_object>( call2_id ) );
// call2 pays 11000 CORE, receives 1000 USD to cover borrower2's position, remaining CORE goes to borrower2's balance
BOOST_CHECK_EQUAL( init_balance - 11000, get_balance(borrower2, core) );
BOOST_CHECK_EQUAL( 0, get_balance(borrower2, bitusd) );
// then it will match with buy_med, at buy_med's price. Since buy_med is too big, it's partially filled.
// buy_med receives the remaining USD of sell order, minus market fees, goes to buyer2's balance
BOOST_CHECK_EQUAL( 783, get_balance(buyer2, bitusd) ); // 700*4-10-1000-1000=790, minus 1% market fee 790*100/10000=7
BOOST_CHECK_EQUAL( init_balance - 11000, get_balance(buyer2, core) );
// buy_med pays at 1/11 = 790/8690
BOOST_CHECK_EQUAL( db.find<limit_order_object>( buy_med )->for_sale.value, 11000-8690 );
// call3 is not in margin call territory so won't be matched
BOOST_CHECK_EQUAL( 1000, call3.debt.value );
BOOST_CHECK_EQUAL( 25000, call3.collateral.value );
// buy_low's price is too low that won't be matched
BOOST_CHECK_EQUAL( db.find<limit_order_object>( buy_low )->for_sale.value, 80 );
// check seller balance
BOOST_CHECK_EQUAL( 193, get_balance(seller, bitusd) ); // 3000 - 7 - 700*4
BOOST_CHECK_EQUAL( 30801, get_balance(seller, core) ); // 111 + 11000 + 11000 + 8690
// Cancel buy_med
cancel_limit_order( buy_med(db) );
BOOST_CHECK( !db.find<limit_order_object>( buy_med ) );
BOOST_CHECK_EQUAL( 783, get_balance(buyer2, bitusd) );
BOOST_CHECK_EQUAL( init_balance - 8690, get_balance(buyer2, core) );
// Create another sell order slightly below the call price, won't fill
limit_order_id_type sell_med = create_sell_order( seller, bitusd.amount(7), core.amount(59) )->id;
BOOST_CHECK_EQUAL( db.find<limit_order_object>( sell_med )->for_sale.value, 7 );
// check seller balance
BOOST_CHECK_EQUAL( 193-7, get_balance(seller, bitusd) );
BOOST_CHECK_EQUAL( 30801, get_balance(seller, core) );
// call3 is not in margin call territory so won't be matched
BOOST_CHECK_EQUAL( 1000, call3.debt.value );
BOOST_CHECK_EQUAL( 25000, call3.collateral.value );
// buy_low's price is too low that won't be matched
BOOST_CHECK_EQUAL( db.find<limit_order_object>( buy_low )->for_sale.value, 80 );
// generate a block
generate_block();
} FC_LOG_AND_RETHROW() }
/***
* Fixed bitshares-core issue #453 #606: multiple order matching without black swan, multiple bitassets
*/
BOOST_AUTO_TEST_CASE(hard_fork_453_cross_test)
{ try { // create orders before hard fork, which will be matched on hard fork
auto mi = db.get_global_properties().parameters.maintenance_interval;
generate_blocks(HARDFORK_CORE_453_TIME - mi); // assume all hard forks occur at same time
generate_block();
set_expiration( db, trx );
ACTORS((buyer)(seller)(borrower)(borrower2)(borrower3)(feedproducer));
const auto& bitusd = create_bitasset("USDBIT", feedproducer_id);
const auto& biteur = create_bitasset("EURBIT", feedproducer_id);
const auto& bitcny = create_bitasset("CNYBIT", feedproducer_id);
const auto& core = asset_id_type()(db);
asset_id_type usd_id = bitusd.id;
asset_id_type eur_id = biteur.id;
asset_id_type cny_id = bitcny.id;
asset_id_type core_id = core.id;
int64_t init_balance(1000000);
transfer(committee_account, buyer_id, asset(init_balance));
transfer(committee_account, borrower_id, asset(init_balance));
transfer(committee_account, borrower2_id, asset(init_balance));
transfer(committee_account, borrower3_id, asset(init_balance));
update_feed_producers( bitusd, {feedproducer.id} );
update_feed_producers( biteur, {feedproducer.id} );
update_feed_producers( bitcny, {feedproducer.id} );
price_feed current_feed;
current_feed.maintenance_collateral_ratio = 1750;
current_feed.maximum_short_squeeze_ratio = 1100;
current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(5);
publish_feed( bitusd, feedproducer, current_feed );
current_feed.settlement_price = biteur.amount( 1 ) / core.amount(5);
publish_feed( biteur, feedproducer, current_feed );
current_feed.settlement_price = bitcny.amount( 1 ) / core.amount(5);
publish_feed( bitcny, feedproducer, current_feed );
// start out with 300% collateral, call price is 15/1.75 CORE/USD = 60/7
const call_order_object& call_usd = *borrow( borrower, bitusd.amount(1000), asset(15000));
call_order_id_type call_usd_id = call_usd.id;
const call_order_object& call_eur = *borrow( borrower, biteur.amount(1000), asset(15000));
call_order_id_type call_eur_id = call_eur.id;
const call_order_object& call_cny = *borrow( borrower, bitcny.amount(1000), asset(15000));
call_order_id_type call_cny_id = call_cny.id;
// create another position with 310% collateral, call price is 15.5/1.75 CORE/USD = 62/7
const call_order_object& call_usd2 = *borrow( borrower2, bitusd.amount(1000), asset(15500));
call_order_id_type call_usd2_id = call_usd2.id;
const call_order_object& call_eur2 = *borrow( borrower2, biteur.amount(1000), asset(15500));
call_order_id_type call_eur2_id = call_eur2.id;
const call_order_object& call_cny2 = *borrow( borrower2, bitcny.amount(1000), asset(15500));
call_order_id_type call_cny2_id = call_cny2.id;
// create yet another position with 320% collateral, call price is 16/1.75 CORE/USD = 64/7
const call_order_object& call_usd3 = *borrow( borrower3, bitusd.amount(1000), asset(16000));
call_order_id_type call_usd3_id = call_usd3.id;
const call_order_object& call_eur3 = *borrow( borrower3, biteur.amount(1000), asset(16000));
call_order_id_type call_eur3_id = call_eur3.id;
const call_order_object& call_cny3 = *borrow( borrower3, bitcny.amount(1000), asset(16000));
call_order_id_type call_cny3_id = call_cny3.id;
transfer(borrower, seller, bitusd.amount(1000));
transfer(borrower2, seller, bitusd.amount(1000));
transfer(borrower3, seller, bitusd.amount(1000));
transfer(borrower, seller, biteur.amount(1000));
transfer(borrower2, seller, biteur.amount(1000));
transfer(borrower3, seller, biteur.amount(1000));
transfer(borrower, seller, bitcny.amount(1000));
transfer(borrower2, seller, bitcny.amount(1000));
transfer(borrower3, seller, bitcny.amount(1000));
BOOST_CHECK_EQUAL( 1000, call_usd.debt.value );
BOOST_CHECK_EQUAL( 15000, call_usd.collateral.value );
BOOST_CHECK_EQUAL( 1000, call_usd2.debt.value );
BOOST_CHECK_EQUAL( 15500, call_usd2.collateral.value );
BOOST_CHECK_EQUAL( 1000, call_usd3.debt.value );
BOOST_CHECK_EQUAL( 16000, call_usd3.collateral.value );
BOOST_CHECK_EQUAL( 3000, get_balance(seller, bitusd) );
BOOST_CHECK_EQUAL( 1000, call_eur.debt.value );
BOOST_CHECK_EQUAL( 15000, call_eur.collateral.value );
BOOST_CHECK_EQUAL( 1000, call_eur2.debt.value );
BOOST_CHECK_EQUAL( 15500, call_eur2.collateral.value );
BOOST_CHECK_EQUAL( 1000, call_eur3.debt.value );
BOOST_CHECK_EQUAL( 16000, call_eur3.collateral.value );
BOOST_CHECK_EQUAL( 3000, get_balance(seller, biteur) );
BOOST_CHECK_EQUAL( 1000, call_cny.debt.value );
BOOST_CHECK_EQUAL( 15000, call_cny.collateral.value );
BOOST_CHECK_EQUAL( 1000, call_cny2.debt.value );
BOOST_CHECK_EQUAL( 15500, call_cny2.collateral.value );
BOOST_CHECK_EQUAL( 1000, call_cny3.debt.value );
BOOST_CHECK_EQUAL( 16000, call_cny3.collateral.value );
BOOST_CHECK_EQUAL( 3000, get_balance(seller, bitcny) );
BOOST_CHECK_EQUAL( 0, get_balance(seller, core) );
// adjust price feed to get call_order into margin call territory
current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(10);
publish_feed( bitusd, feedproducer, current_feed );
current_feed.settlement_price = biteur.amount( 1 ) / core.amount(10);
publish_feed( biteur, feedproducer, current_feed );
current_feed.settlement_price = bitcny.amount( 1 ) / core.amount(10);
publish_feed( bitcny, feedproducer, current_feed );
// settlement price = 1/10, mssp = 1/11
// This order below the call price will not be matched before hard fork: 1/8 #606
limit_order_id_type sell_usd_low = create_sell_order(seller, bitusd.amount(1000), core.amount(7000))->id;
// This is a big order, price below the call price will not be matched before hard fork: 1007/9056 = 1/8 #606
limit_order_id_type sell_usd_low2 = create_sell_order(seller, bitusd.amount(1007), core.amount(8056))->id;
// This order above the MSSP will not be matched before hard fork
limit_order_id_type sell_usd_high = create_sell_order(seller, bitusd.amount(7), core.amount(78))->id;
// This would match but is blocked by sell_low?! #606
limit_order_id_type sell_usd_med = create_sell_order(seller, bitusd.amount(700), core.amount(6400))->id;
// This would match but is blocked by sell_low?! #606
limit_order_id_type sell_usd_med2 = create_sell_order(seller, bitusd.amount(7), core.amount(65))->id;
// This order below the call price will not be matched before hard fork: 1/8 #606
limit_order_id_type sell_eur_low = create_sell_order(seller, biteur.amount(1000), core.amount(7000))->id;
// This is a big order, price below the call price will not be matched before hard fork: 1007/9056 = 1/8 #606
limit_order_id_type sell_eur_low2 = create_sell_order(seller, biteur.amount(1007), core.amount(8056))->id;
// This order above the MSSP will not be matched before hard fork
limit_order_id_type sell_eur_high = create_sell_order(seller, biteur.amount(7), core.amount(78))->id;
// This would match but is blocked by sell_low?! #606
limit_order_id_type sell_eur_med = create_sell_order(seller, biteur.amount(700), core.amount(6400))->id;
// This would match but is blocked by sell_low?! #606
limit_order_id_type sell_eur_med2 = create_sell_order(seller, biteur.amount(7), core.amount(65))->id;
// This order below the call price will not be matched before hard fork: 1/8 #606
limit_order_id_type sell_cny_low = create_sell_order(seller, bitcny.amount(1000), core.amount(7000))->id;
// This is a big order, price below the call price will not be matched before hard fork: 1007/9056 = 1/8 #606
limit_order_id_type sell_cny_low2 = create_sell_order(seller, bitcny.amount(1007), core.amount(8056))->id;
// This order above the MSSP will not be matched before hard fork
limit_order_id_type sell_cny_high = create_sell_order(seller, bitcny.amount(7), core.amount(78))->id;
// This would match but is blocked by sell_low?! #606
limit_order_id_type sell_cny_med = create_sell_order(seller, bitcny.amount(700), core.amount(6400))->id;
// This would match but is blocked by sell_low?! #606
limit_order_id_type sell_cny_med2 = create_sell_order(seller, bitcny.amount(7), core.amount(65))->id;
BOOST_CHECK_EQUAL( 3000-1000-1007-7-700-7, get_balance(seller_id, usd_id) );
BOOST_CHECK_EQUAL( 3000-1000-1007-7-700-7, get_balance(seller_id, eur_id) );
BOOST_CHECK_EQUAL( 3000-1000-1007-7-700-7, get_balance(seller_id, cny_id) );
BOOST_CHECK_EQUAL( 0, get_balance(seller, core) );
// generate a block to include operations above
generate_block();
// go over the hard fork, make sure feed doesn't expire
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
// sell_low and call should get matched first
BOOST_CHECK( !db.find<limit_order_object>( sell_usd_low ) );
BOOST_CHECK( !db.find<call_order_object>( call_usd_id ) );
// sell_low2 and call2 should get matched
BOOST_CHECK( !db.find<call_order_object>( call_usd2_id ) );
// sell_low2 and call3 should get matched: fixed #453
BOOST_CHECK( !db.find<limit_order_object>( sell_usd_low2 ) );
// sell_med and call3 should get matched
BOOST_CHECK( !db.find<limit_order_object>( sell_usd_med ) );
// call3 now is not at margin call state, so sell_med2 won't get matched
BOOST_CHECK_EQUAL( db.find<limit_order_object>( sell_usd_med2 )->for_sale.value, 7 );
// sell_high should still be there, didn't match anything
BOOST_CHECK_EQUAL( db.find<limit_order_object>( sell_usd_high )->for_sale.value, 7 );
// sell_low and call should get matched first
BOOST_CHECK( !db.find<limit_order_object>( sell_eur_low ) );
BOOST_CHECK( !db.find<call_order_object>( call_eur_id ) );
// sell_low2 and call2 should get matched
BOOST_CHECK( !db.find<call_order_object>( call_eur2_id ) );
// sell_low2 and call3 should get matched: fixed #453
BOOST_CHECK( !db.find<limit_order_object>( sell_eur_low2 ) );
// sell_med and call3 should get matched
BOOST_CHECK( !db.find<limit_order_object>( sell_eur_med ) );
// call3 now is not at margin call state, so sell_med2 won't get matched
BOOST_CHECK_EQUAL( db.find<limit_order_object>( sell_eur_med2 )->for_sale.value, 7 );
// sell_high should still be there, didn't match anything
BOOST_CHECK_EQUAL( db.find<limit_order_object>( sell_eur_high )->for_sale.value, 7 );
// sell_low and call should get matched first
BOOST_CHECK( !db.find<limit_order_object>( sell_cny_low ) );
BOOST_CHECK( !db.find<call_order_object>( call_cny_id ) );
// sell_low2 and call2 should get matched
BOOST_CHECK( !db.find<call_order_object>( call_cny2_id ) );
// sell_low2 and call3 should get matched: fixed #453
BOOST_CHECK( !db.find<limit_order_object>( sell_cny_low2 ) );
// sell_med and call3 should get matched
BOOST_CHECK( !db.find<limit_order_object>( sell_cny_med ) );
// call3 now is not at margin call state, so sell_med2 won't get matched
BOOST_CHECK_EQUAL( db.find<limit_order_object>( sell_cny_med2 )->for_sale.value, 7 );
// sell_high should still be there, didn't match anything
BOOST_CHECK_EQUAL( db.find<limit_order_object>( sell_cny_high )->for_sale.value, 7 );
// all match price would be limit order price
BOOST_CHECK_EQUAL( 3000-1000-1007-7-700-7, get_balance(seller_id, usd_id) );
BOOST_CHECK_EQUAL( 3000-1000-1007-7-700-7, get_balance(seller_id, eur_id) );
BOOST_CHECK_EQUAL( 3000-1000-1007-7-700-7, get_balance(seller_id, cny_id) );
BOOST_CHECK_EQUAL( (7000+8056+6400)*3, get_balance(seller_id, core_id) );
BOOST_CHECK_EQUAL( 1000-7-700, call_usd3_id(db).debt.value );
BOOST_CHECK_EQUAL( 16000-56-6400, call_usd3_id(db).collateral.value );
BOOST_CHECK_EQUAL( 1000-7-700, call_eur3_id(db).debt.value );
BOOST_CHECK_EQUAL( 16000-56-6400, call_eur3_id(db).collateral.value );
BOOST_CHECK_EQUAL( 1000-7-700, call_cny3_id(db).debt.value );
BOOST_CHECK_EQUAL( 16000-56-6400, call_cny3_id(db).collateral.value );
// call3's call_price should be updated: 9544/293/1.75 = 9544*4 / 293*7 = 38176/2051 CORE/USD
BOOST_CHECK( price(asset(38176),asset(2051,usd_id)) == call_usd3_id(db).call_price );
BOOST_CHECK( price(asset(38176),asset(2051,eur_id)) == call_eur3_id(db).call_price );
BOOST_CHECK( price(asset(38176),asset(2051,cny_id)) == call_cny3_id(db).call_price );
generate_block();
} FC_LOG_AND_RETHROW() }
/***
* Fixed bitshares-core issue #338 #453 #606: multiple order matching with black swan
*/
BOOST_AUTO_TEST_CASE(hard_fork_338_cross_test)
{ try { // create orders before hard fork, which will be matched on hard fork
auto mi = db.get_global_properties().parameters.maintenance_interval;
generate_blocks(HARDFORK_CORE_338_TIME - mi); // assume all hard forks occur at same time
generate_block();
set_expiration( db, trx );
ACTORS((buyer)(seller)(borrower)(borrower2)(borrower3)(borrower4)(feedproducer));
const auto& bitusd = create_bitasset("USDBIT", feedproducer_id);
const auto& core = asset_id_type()(db);
asset_id_type usd_id = bitusd.id;
asset_id_type core_id = core.id;
int64_t init_balance(1000000);
transfer(committee_account, buyer_id, asset(init_balance));
transfer(committee_account, borrower_id, asset(init_balance));
transfer(committee_account, borrower2_id, asset(init_balance));
transfer(committee_account, borrower3_id, asset(init_balance));
transfer(committee_account, borrower4_id, asset(init_balance));
update_feed_producers( bitusd, {feedproducer.id} );
price_feed current_feed;
current_feed.maintenance_collateral_ratio = 1750;
current_feed.maximum_short_squeeze_ratio = 1100;
current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(5);
publish_feed( bitusd, feedproducer, current_feed );
// start out with 300% collateral, call price is 15/1.75 CORE/USD = 60/7
const call_order_object& call = *borrow( borrower, bitusd.amount(1000), asset(15000));
call_order_id_type call_id = call.id;
// create another position with 310% collateral, call price is 15.5/1.75 CORE/USD = 62/7
const call_order_object& call2 = *borrow( borrower2, bitusd.amount(1000), asset(15500));
call_order_id_type call2_id = call2.id;
// create yet another position with 320% collateral, call price is 16/1.75 CORE/USD = 64/7
const call_order_object& call3 = *borrow( borrower3, bitusd.amount(1000), asset(16000));
call_order_id_type call3_id = call3.id;
// create yet another position with 400% collateral, call price is 20/1.75 CORE/USD = 80/7
const call_order_object& call4 = *borrow( borrower4, bitusd.amount(1000), asset(20000));
call_order_id_type call4_id = call4.id;
transfer(borrower, seller, bitusd.amount(1000));
transfer(borrower2, seller, bitusd.amount(1000));
transfer(borrower3, seller, bitusd.amount(1000));
BOOST_CHECK_EQUAL( 1000, call.debt.value );
BOOST_CHECK_EQUAL( 15000, call.collateral.value );
BOOST_CHECK_EQUAL( 1000, call2.debt.value );
BOOST_CHECK_EQUAL( 15500, call2.collateral.value );
BOOST_CHECK_EQUAL( 1000, call3.debt.value );
BOOST_CHECK_EQUAL( 16000, call3.collateral.value );
BOOST_CHECK_EQUAL( 3000, get_balance(seller, bitusd) );
BOOST_CHECK_EQUAL( 0, get_balance(seller, core) );
// adjust price feed to get call_order into margin call territory
current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(10);
publish_feed( bitusd, feedproducer, current_feed );
// settlement price = 1/10, mssp = 1/11
// This order below the call price will not be matched before hard fork: 1/8 #606
limit_order_id_type sell_low = create_sell_order(seller, bitusd.amount(1000), core.amount(7000))->id;
// This is a big order, price below the call price will not be matched before hard fork: 1007/9056 = 1/8 #606
limit_order_id_type sell_low2 = create_sell_order(seller, bitusd.amount(1007), core.amount(8056))->id;
// This would match but is blocked by sell_low?! #606
limit_order_id_type sell_med = create_sell_order(seller, bitusd.amount(7), core.amount(64))->id;
// adjust price feed to get call_order into black swan territory
current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(16);
publish_feed( bitusd, feedproducer, current_feed );
// settlement price = 1/16, mssp = 10/176
// due to sell_low, black swan won't occur
BOOST_CHECK( !usd_id(db).bitasset_data(db).has_settlement() );
BOOST_CHECK_EQUAL( 3000-1000-1007-7, get_balance(seller_id, usd_id) );
BOOST_CHECK_EQUAL( 0, get_balance(seller, core) );
// generate a block to include operations above
generate_block();
// go over the hard fork, make sure feed doesn't expire
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
// sell_low and call should get matched first
BOOST_CHECK( !db.find<limit_order_object>( sell_low ) );
BOOST_CHECK( !db.find<call_order_object>( call_id ) );
// sell_low2 and call2 should get matched
BOOST_CHECK( !db.find<call_order_object>( call2_id ) );
// sell_low2 and call3 should get matched: fixed #453
BOOST_CHECK( !db.find<limit_order_object>( sell_low2 ) );
// sell_med and call3 should get matched
BOOST_CHECK( !db.find<limit_order_object>( sell_med ) );
// at this moment,
// collateralization of call3 is (16000-56-64) / (1000-7-7) = 15880/986 = 16.1, it's > 16 but < 17.6
// although there is no sell order, it should trigger a black swan event right away,
// because after hard fork new limit order won't trigger black swan event
BOOST_CHECK( usd_id(db).bitasset_data(db).has_settlement() );
BOOST_CHECK( !db.find<call_order_object>( call3_id ) );
BOOST_CHECK( !db.find<call_order_object>( call4_id ) );
// since 16.1 > 16, global settlement should at feed price 16/1
// so settlement fund should be 986*16 + 1000*16
BOOST_CHECK_EQUAL( 1986*16, usd_id(db).bitasset_data(db).settlement_fund.value );
// global settlement price should be 16/1, since no rounding here
BOOST_CHECK( price(asset(1,usd_id),asset(16) ) == usd_id(db).bitasset_data(db).settlement_price );
BOOST_CHECK_EQUAL( 3000-1000-1007-7, get_balance(seller_id, usd_id) );
BOOST_CHECK_EQUAL( 7000+8056+64, get_balance(seller_id, core_id) );
BOOST_CHECK_EQUAL( 0, get_balance(borrower3_id, usd_id) );
BOOST_CHECK_EQUAL( init_balance-16000+15880-986*16, get_balance(borrower3_id, core_id) );
BOOST_CHECK_EQUAL( 1000, get_balance(borrower4_id, usd_id) );
BOOST_CHECK_EQUAL( init_balance-1000*16, get_balance(borrower4_id, core_id) );
generate_block();
} FC_LOG_AND_RETHROW() }
/***
* Fixed bitshares-core issue #649: Black swan detection fetch call order by call_price but not collateral ratio
*/
BOOST_AUTO_TEST_CASE(hard_fork_649_cross_test)
{ try { // create orders before hard fork, which will be matched on hard fork
auto mi = db.get_global_properties().parameters.maintenance_interval;
generate_blocks(HARDFORK_CORE_343_TIME - mi); // assume all hard forks occur at same time
generate_block();
set_expiration( db, trx );
ACTORS((buyer)(seller)(borrower)(borrower2)(borrower3)(borrower4)(feedproducer));
const auto& bitusd = create_bitasset("USDBIT", feedproducer_id);
const auto& core = asset_id_type()(db);
asset_id_type usd_id = bitusd.id;
asset_id_type core_id = core.id;
int64_t init_balance(1000000);
transfer(committee_account, buyer_id, asset(init_balance));
transfer(committee_account, borrower_id, asset(init_balance));
transfer(committee_account, borrower2_id, asset(init_balance));
transfer(committee_account, borrower3_id, asset(init_balance));
transfer(committee_account, borrower4_id, asset(init_balance));
update_feed_producers( bitusd, {feedproducer.id} );
price_feed current_feed;
current_feed.maintenance_collateral_ratio = 1750;
current_feed.maximum_short_squeeze_ratio = 1100;
current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(5);
publish_feed( bitusd, feedproducer, current_feed );
// start out with 300% collateral, call price is 15/1.75 CORE/USD = 60/7
const call_order_object& call = *borrow( borrower, bitusd.amount(1000), asset(15000));
call_order_id_type call_id = call.id;
// create another position with 310% collateral, call price is 15.5/1.75 CORE/USD = 62/7
const call_order_object& call2 = *borrow( borrower2, bitusd.amount(1000), asset(15500));
call_order_id_type call2_id = call2.id;
// create yet another position with 320% collateral, call price is 16/1.75 CORE/USD = 64/7
const call_order_object& call3 = *borrow( borrower3, bitusd.amount(1000), asset(16000));
call_order_id_type call3_id = call3.id;
transfer(borrower, seller, bitusd.amount(1000));
transfer(borrower2, seller, bitusd.amount(1000));
transfer(borrower3, seller, bitusd.amount(1000));
BOOST_CHECK_EQUAL( 1000, call.debt.value );
BOOST_CHECK_EQUAL( 15000, call.collateral.value );
BOOST_CHECK_EQUAL( 1000, call2.debt.value );
BOOST_CHECK_EQUAL( 15500, call2.collateral.value );
BOOST_CHECK_EQUAL( 1000, call3.debt.value );
BOOST_CHECK_EQUAL( 16000, call3.collateral.value );
BOOST_CHECK_EQUAL( 3000, get_balance(seller, bitusd) );
BOOST_CHECK_EQUAL( 0, get_balance(seller, core) );
// adjust price feed to get call_order into margin call territory
current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(10);
publish_feed( bitusd, feedproducer, current_feed );
// settlement price = 1/10, mssp = 1/11
// This would match with call at price 707/6464
BOOST_CHECK( !create_sell_order(seller, bitusd.amount(707), core.amount(6464)) );
BOOST_CHECK_EQUAL( 3000-707, get_balance(seller_id, usd_id) );
BOOST_CHECK_EQUAL( 6464, get_balance(seller_id, core_id) );
BOOST_CHECK_EQUAL( 293, call.debt.value );
BOOST_CHECK_EQUAL( 8536, call.collateral.value );
// at this moment,
// collateralization of call is 8536 / 293 = 29.1
// collateralization of call2 is 15500 / 1000 = 15.5
// collateralization of call3 is 16000 / 1000 = 16
generate_block();
set_expiration( db, trx );
update_feed_producers( usd_id(db), {feedproducer_id} );
// adjust price feed to get call_order into black swan territory
current_feed.settlement_price = price(asset(1,usd_id) / asset(20));
publish_feed( usd_id(db), feedproducer_id(db), current_feed );
// settlement price = 1/20, mssp = 1/22
// due to #649, black swan won't occur
BOOST_CHECK( !usd_id(db).bitasset_data(db).has_settlement() );
// generate a block to include operations above
generate_block();
BOOST_CHECK( !usd_id(db).bitasset_data(db).has_settlement() );
// go over the hard fork, make sure feed doesn't expire
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
// a black swan event should occur
BOOST_CHECK( usd_id(db).bitasset_data(db).has_settlement() );
BOOST_CHECK( !db.find<call_order_object>( call_id ) );
BOOST_CHECK( !db.find<call_order_object>( call2_id ) );
BOOST_CHECK( !db.find<call_order_object>( call3_id ) );
// since least collateral ratio 15.5 < 20, global settlement should execute at price = least collateral ratio 15.5/1
// so settlement fund should be 15500 + 15500 + round_up(15.5 * 293)
BOOST_CHECK_EQUAL( 15500*2 + (293 * 155 + 9) / 10, usd_id(db).bitasset_data(db).settlement_fund.value );
// global settlement price should be settlement_fund/(2000+293), but not 15.5/1 due to rounding
BOOST_CHECK( price(asset(2293,usd_id),asset(15500*2+(293*155+9)/10) ) == usd_id(db).bitasset_data(db).settlement_price );
BOOST_CHECK_EQUAL( 3000-707, get_balance(seller_id, usd_id) );
BOOST_CHECK_EQUAL( 6464, get_balance(seller_id, core_id) );
BOOST_CHECK_EQUAL( 0, get_balance(borrower_id, usd_id) );
BOOST_CHECK_EQUAL( init_balance-6464-(293*155+9)/10, get_balance(borrower_id, core_id) );
BOOST_CHECK_EQUAL( 0, get_balance(borrower2_id, usd_id) );
BOOST_CHECK_EQUAL( init_balance-15500, get_balance(borrower2_id, core_id) );
BOOST_CHECK_EQUAL( 0, get_balance(borrower3_id, usd_id) );
BOOST_CHECK_EQUAL( init_balance-15500, get_balance(borrower3_id, core_id) );
generate_block();
} FC_LOG_AND_RETHROW() }
/***
* Fixed bitshares-core issue #343: change sorting of call orders when matching against limit order
*/
BOOST_AUTO_TEST_CASE(hard_fork_343_cross_test)
{ try { // create orders before hard fork, which will be matched on hard fork
auto mi = db.get_global_properties().parameters.maintenance_interval;
generate_blocks(HARDFORK_CORE_343_TIME - mi); // assume all hard forks occur at same time
generate_block();
set_expiration( db, trx );
ACTORS((buyer)(seller)(borrower)(borrower2)(borrower3)(borrower4)(feedproducer));
const auto& bitusd = create_bitasset("USDBIT", feedproducer_id);
const auto& core = asset_id_type()(db);
asset_id_type usd_id = bitusd.id;
asset_id_type core_id = core.id;
int64_t init_balance(1000000);
transfer(committee_account, buyer_id, asset(init_balance));
transfer(committee_account, borrower_id, asset(init_balance));
transfer(committee_account, borrower2_id, asset(init_balance));
transfer(committee_account, borrower3_id, asset(init_balance));
transfer(committee_account, borrower4_id, asset(init_balance));
update_feed_producers( bitusd, {feedproducer.id} );
price_feed current_feed;
current_feed.maintenance_collateral_ratio = 1750;
current_feed.maximum_short_squeeze_ratio = 1100;
current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(5);
publish_feed( bitusd, feedproducer, current_feed );
// start out with 300% collateral, call price is 15/1.75 CORE/USD = 60/7
const call_order_object& call = *borrow( borrower, bitusd.amount(1000), asset(15000));
call_order_id_type call_id = call.id;
// create another position with 310% collateral, call price is 15.5/1.75 CORE/USD = 62/7
const call_order_object& call2 = *borrow( borrower2, bitusd.amount(1000), asset(15500));
call_order_id_type call2_id = call2.id;
// create yet another position with 350% collateral, call price is 17.5/1.75 CORE/USD = 77/7
const call_order_object& call3 = *borrow( borrower3, bitusd.amount(1000), asset(17500));
call_order_id_type call3_id = call3.id;
transfer(borrower, seller, bitusd.amount(1000));
transfer(borrower2, seller, bitusd.amount(1000));
transfer(borrower3, seller, bitusd.amount(1000));
BOOST_CHECK_EQUAL( 1000, call.debt.value );
BOOST_CHECK_EQUAL( 15000, call.collateral.value );
BOOST_CHECK_EQUAL( 1000, call2.debt.value );
BOOST_CHECK_EQUAL( 15500, call2.collateral.value );
BOOST_CHECK_EQUAL( 1000, call3.debt.value );
BOOST_CHECK_EQUAL( 17500, call3.collateral.value );
BOOST_CHECK_EQUAL( 3000, get_balance(seller, bitusd) );
BOOST_CHECK_EQUAL( 0, get_balance(seller, core) );
// adjust price feed to get call_order into margin call territory
current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(10);
publish_feed( bitusd, feedproducer, current_feed );
// settlement price = 1/10, mssp = 1/11
// This would match with call at price 700/6400
BOOST_CHECK( !create_sell_order(seller, bitusd.amount(700), core.amount(6400)) );
BOOST_CHECK_EQUAL( 3000-700, get_balance(seller_id, usd_id) );
BOOST_CHECK_EQUAL( 6400, get_balance(seller_id, core_id) );
BOOST_CHECK_EQUAL( 300, call.debt.value );
BOOST_CHECK_EQUAL( 8600, call.collateral.value );
// at this moment,
// collateralization of call is 8600 / 300 = 28.67
// collateralization of call2 is 15500 / 1000 = 15.5
// collateralization of call3 is 17500 / 1000 = 17.5
// generate a block to include operations above
generate_block();
// go over the hard fork, make sure feed doesn't expire
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
set_expiration( db, trx );
// This will match with call2 at price 7/77 (#343 fixed)
BOOST_CHECK( !create_sell_order(seller_id(db), asset(7*50,usd_id), asset(65*50)) );
BOOST_CHECK_EQUAL( 3000-700-7*50, get_balance(seller_id, usd_id) );
BOOST_CHECK_EQUAL( 6400+77*50, get_balance(seller_id, core_id) );
BOOST_CHECK_EQUAL( 300, call_id(db).debt.value );
BOOST_CHECK_EQUAL( 8600, call_id(db).collateral.value );
BOOST_CHECK_EQUAL( 1000-7*50, call2_id(db).debt.value );
BOOST_CHECK_EQUAL( 15500-77*50, call2_id(db).collateral.value );
BOOST_CHECK_EQUAL( 1000, call3_id(db).debt.value );
BOOST_CHECK_EQUAL( 17500, call3_id(db).collateral.value );
// at this moment,
// collateralization of call is 8600 / 300 = 28.67
// collateralization of call2 is 11650 / 650 = 17.9
// collateralization of call3 is 17500 / 1000 = 17.5
// This will match with call3 at price 7/77 (#343 fixed)
BOOST_CHECK( !create_sell_order(seller_id(db), asset(7,usd_id), asset(65)) );
BOOST_CHECK_EQUAL( 3000-700-7*50-7, get_balance(seller_id, usd_id) );
BOOST_CHECK_EQUAL( 6400+77*50+77, get_balance(seller_id, core_id) );
BOOST_CHECK_EQUAL( 300, call_id(db).debt.value );
BOOST_CHECK_EQUAL( 8600, call_id(db).collateral.value );
BOOST_CHECK_EQUAL( 1000-7*50, call2_id(db).debt.value );
BOOST_CHECK_EQUAL( 15500-77*50, call2_id(db).collateral.value );
BOOST_CHECK_EQUAL( 1000-7, call3_id(db).debt.value );
BOOST_CHECK_EQUAL( 17500-77, call3_id(db).collateral.value );
// at this moment,
// collateralization of call is 8600 / 300 = 28.67
// collateralization of call2 is 11650 / 650 = 17.9
// collateralization of call3 is 17423 / 993 = 17.55
// no more margin call now
BOOST_CHECK( create_sell_order(seller_id(db), asset(7,usd_id), asset(65)) );
generate_block();
} FC_LOG_AND_RETHROW() }
/***
* BSIP38 "target_collateral_ratio" test: matching a taker limit order with multiple maker call orders
*/
BOOST_AUTO_TEST_CASE(target_cr_test_limit_call)
{ try {
auto mi = db.get_global_properties().parameters.maintenance_interval;
if(hf1270)
generate_blocks(HARDFORK_CORE_1270_TIME - mi);
else
generate_blocks(HARDFORK_CORE_834_TIME - mi);
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
set_expiration( db, trx );
ACTORS((buyer)(buyer2)(buyer3)(seller)(borrower)(borrower2)(borrower3)(feedproducer));
const auto& bitusd = create_bitasset("USDBIT", feedproducer_id);
const auto& core = asset_id_type()(db);
int64_t init_balance(1000000);
transfer(committee_account, buyer_id, asset(init_balance));
transfer(committee_account, buyer2_id, asset(init_balance));
transfer(committee_account, buyer3_id, asset(init_balance));
transfer(committee_account, borrower_id, asset(init_balance));
transfer(committee_account, borrower2_id, asset(init_balance));
transfer(committee_account, borrower3_id, asset(init_balance));
update_feed_producers( bitusd, {feedproducer.id} );
price_feed current_feed;
current_feed.maintenance_collateral_ratio = 1750;
current_feed.maximum_short_squeeze_ratio = 1100;
current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(5);
publish_feed( bitusd, feedproducer, current_feed );
// start out with 300% collateral, call price is 15/1.75 CORE/USD = 60/7, tcr 170% is lower than 175%
const call_order_object& call = *borrow( borrower, bitusd.amount(1000), asset(15000), 1700);
call_order_id_type call_id = call.id;
// create another position with 310% collateral, call price is 15.5/1.75 CORE/USD = 62/7, tcr 200% is higher than 175%
const call_order_object& call2 = *borrow( borrower2, bitusd.amount(1000), asset(15500), 2000);
call_order_id_type call2_id = call2.id;
// create yet another position with 500% collateral, call price is 25/1.75 CORE/USD = 100/7, no tcr
const call_order_object& call3 = *borrow( borrower3, bitusd.amount(1000), asset(25000));
transfer(borrower, seller, bitusd.amount(1000));
transfer(borrower2, seller, bitusd.amount(1000));
transfer(borrower3, seller, bitusd.amount(1000));
BOOST_CHECK_EQUAL( 1000, call.debt.value );
BOOST_CHECK_EQUAL( 15000, call.collateral.value );
BOOST_CHECK_EQUAL( 1000, call2.debt.value );
BOOST_CHECK_EQUAL( 15500, call2.collateral.value );
BOOST_CHECK_EQUAL( 1000, call3.debt.value );
BOOST_CHECK_EQUAL( 25000, call3.collateral.value );
BOOST_CHECK_EQUAL( 3000, get_balance(seller, bitusd) );
BOOST_CHECK_EQUAL( 0, get_balance(seller, core) );
BOOST_CHECK_EQUAL( 3000, get_balance(seller, bitusd) );
BOOST_CHECK_EQUAL( init_balance - 15000, get_balance(borrower, core) );
BOOST_CHECK_EQUAL( init_balance - 15500, get_balance(borrower2, core) );
BOOST_CHECK_EQUAL( init_balance - 25000, get_balance(borrower3, core) );
BOOST_CHECK_EQUAL( 0, get_balance(borrower, bitusd) );
BOOST_CHECK_EQUAL( 0, get_balance(borrower2, bitusd) );
BOOST_CHECK_EQUAL( 0, get_balance(borrower3, bitusd) );
// adjust price feed to get call and call2 (but not call3) into margin call territory
current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(10);
publish_feed( bitusd, feedproducer, current_feed );
// settlement price = 1/10, mssp = 1/11
// This sell order above MSSP will not be matched with a call
limit_order_id_type sell_high = create_sell_order(seller, bitusd.amount(7), core.amount(78))->id;
BOOST_CHECK_EQUAL( db.find<limit_order_object>( sell_high )->for_sale.value, 7 );
BOOST_CHECK_EQUAL( 2993, get_balance(seller, bitusd) );
BOOST_CHECK_EQUAL( 0, get_balance(seller, core) );
// This buy order is too low will not be matched with a sell order
limit_order_id_type buy_low = create_sell_order(buyer, asset(80), bitusd.amount(10))->id;
// This buy order at MSSP will be matched only if no margin call (margin call takes precedence)
limit_order_id_type buy_med = create_sell_order(buyer2, asset(33000), bitusd.amount(3000))->id;
// This buy order above MSSP will be matched with a sell order (limit order with better price takes precedence)
limit_order_id_type buy_high = create_sell_order(buyer3, asset(111), bitusd.amount(10))->id;
BOOST_CHECK_EQUAL( 0, get_balance(buyer, bitusd) );
BOOST_CHECK_EQUAL( 0, get_balance(buyer2, bitusd) );
BOOST_CHECK_EQUAL( 0, get_balance(buyer3, bitusd) );
BOOST_CHECK_EQUAL( init_balance - 80, get_balance(buyer, core) );
BOOST_CHECK_EQUAL( init_balance - 33000, get_balance(buyer2, core) );
BOOST_CHECK_EQUAL( init_balance - 111, get_balance(buyer3, core) );
// call and call2's CR is quite high, and debt amount is quite a lot, assume neither of them will be completely filled
price match_price( bitusd.amount(1) / core.amount(11) );
share_type call_to_cover = call_id(db).get_max_debt_to_cover(match_price,current_feed.settlement_price,1750);
share_type call2_to_cover = call2_id(db).get_max_debt_to_cover(match_price,current_feed.settlement_price,1750);
BOOST_CHECK_LT( call_to_cover.value, call_id(db).debt.value );
BOOST_CHECK_LT( call2_to_cover.value, call2_id(db).debt.value );
// even though call2 has a higher CR, since call's TCR is less than call2's TCR, so we expect call will cover less when called
BOOST_CHECK_LT( call_to_cover.value, call2_to_cover.value );
// Create a big sell order slightly below the call price, will be matched with several orders
BOOST_CHECK( !create_sell_order(seller, bitusd.amount(700*4), core.amount(5900*4) ) );
// firstly it will match with buy_high, at buy_high's price
BOOST_CHECK( !db.find<limit_order_object>( buy_high ) );
// buy_high pays 111 CORE, receives 10 USD goes to buyer3's balance
BOOST_CHECK_EQUAL( 10, get_balance(buyer3, bitusd) );
BOOST_CHECK_EQUAL( init_balance - 111, get_balance(buyer3, core) );
// then it will match with call, at mssp: 1/11 = 1000/11000
const call_order_object* tmp_call = db.find<call_order_object>( call_id );
BOOST_CHECK( tmp_call != nullptr );
// call will receive call_to_cover, pay 11*call_to_cover
share_type call_to_pay = call_to_cover * 11;
BOOST_CHECK_EQUAL( 1000 - call_to_cover.value, call.debt.value );
BOOST_CHECK_EQUAL( 15000 - call_to_pay.value, call.collateral.value );
// new collateral ratio should be higher than mcr as well as tcr
BOOST_CHECK( call.debt.value * 10 * 1750 < call.collateral.value * 1000 );
idump( (call) );
// borrower's balance doesn't change
BOOST_CHECK_EQUAL( init_balance - 15000, get_balance(borrower, core) );
BOOST_CHECK_EQUAL( 0, get_balance(borrower, bitusd) );
// the limit order then will match with call2, at mssp: 1/11 = 1000/11000
const call_order_object* tmp_call2 = db.find<call_order_object>( call2_id );
BOOST_CHECK( tmp_call2 != nullptr );
// call2 will receive call2_to_cover, pay 11*call2_to_cover
share_type call2_to_pay = call2_to_cover * 11;
BOOST_CHECK_EQUAL( 1000 - call2_to_cover.value, call2.debt.value );
BOOST_CHECK_EQUAL( 15500 - call2_to_pay.value, call2.collateral.value );
// new collateral ratio should be higher than mcr as well as tcr
BOOST_CHECK( call2.debt.value * 10 * 2000 < call2.collateral.value * 1000 );
idump( (call2) );
// borrower2's balance doesn't change
BOOST_CHECK_EQUAL( init_balance - 15500, get_balance(borrower2, core) );
BOOST_CHECK_EQUAL( 0, get_balance(borrower2, bitusd) );
// then it will match with buy_med, at buy_med's price. Since buy_med is too big, it's partially filled.
// buy_med receives the remaining USD of sell order, minus market fees, goes to buyer2's balance
share_type buy_med_get = 700*4 - 10 - call_to_cover - call2_to_cover;
share_type buy_med_pay = buy_med_get * 11; // buy_med pays at 1/11
buy_med_get -= (buy_med_get/100); // minus 1% market fee
BOOST_CHECK_EQUAL( buy_med_get.value, get_balance(buyer2, bitusd) );
BOOST_CHECK_EQUAL( init_balance - 33000, get_balance(buyer2, core) );
BOOST_CHECK_EQUAL( db.find<limit_order_object>( buy_med )->for_sale.value, 33000-buy_med_pay.value );
// call3 is not in margin call territory so won't be matched
BOOST_CHECK_EQUAL( 1000, call3.debt.value );
BOOST_CHECK_EQUAL( 25000, call3.collateral.value );
// buy_low's price is too low that won't be matched
BOOST_CHECK_EQUAL( db.find<limit_order_object>( buy_low )->for_sale.value, 80 );
// check seller balance
BOOST_CHECK_EQUAL( 193, get_balance(seller, bitusd) ); // 3000 - 7 - 700*4
BOOST_CHECK_EQUAL( 30801, get_balance(seller, core) ); // 111 + (700*4-10)*11
// Cancel buy_med
cancel_limit_order( buy_med(db) );
BOOST_CHECK( !db.find<limit_order_object>( buy_med ) );
BOOST_CHECK_EQUAL( buy_med_get.value, get_balance(buyer2, bitusd) );
BOOST_CHECK_EQUAL( init_balance - buy_med_pay.value, get_balance(buyer2, core) );
// Create another sell order slightly below the call price, won't fill
limit_order_id_type sell_med = create_sell_order( seller, bitusd.amount(7), core.amount(59) )->id;
BOOST_CHECK_EQUAL( db.find<limit_order_object>( sell_med )->for_sale.value, 7 );
// check seller balance
BOOST_CHECK_EQUAL( 193-7, get_balance(seller, bitusd) );
BOOST_CHECK_EQUAL( 30801, get_balance(seller, core) );
// call3 is not in margin call territory so won't be matched
BOOST_CHECK_EQUAL( 1000, call3.debt.value );
BOOST_CHECK_EQUAL( 25000, call3.collateral.value );
// buy_low's price is too low that won't be matched
BOOST_CHECK_EQUAL( db.find<limit_order_object>( buy_low )->for_sale.value, 80 );
// generate a block
generate_block();
} FC_LOG_AND_RETHROW() }
/***
* BSIP38 "target_collateral_ratio" test: matching a maker limit order with multiple taker call orders
*/
BOOST_AUTO_TEST_CASE(target_cr_test_call_limit)
{ try {
auto mi = db.get_global_properties().parameters.maintenance_interval;
if(hf1270)
generate_blocks(HARDFORK_CORE_1270_TIME - mi);
else
generate_blocks(HARDFORK_CORE_834_TIME - mi);
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
set_expiration( db, trx );
ACTORS((buyer)(seller)(borrower)(borrower2)(borrower3)(feedproducer));
const auto& bitusd = create_bitasset("USDBIT", feedproducer_id);
const auto& core = asset_id_type()(db);
int64_t init_balance(1000000);
transfer(committee_account, buyer_id, asset(init_balance));
transfer(committee_account, borrower_id, asset(init_balance));
transfer(committee_account, borrower2_id, asset(init_balance));
transfer(committee_account, borrower3_id, asset(init_balance));
update_feed_producers( bitusd, {feedproducer.id} );
price_feed current_feed;
current_feed.maintenance_collateral_ratio = 1750;
current_feed.maximum_short_squeeze_ratio = 1100;
current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(5);
publish_feed( bitusd, feedproducer, current_feed );
// start out with 300% collateral, call price is 15/1.75 CORE/USD = 60/7, tcr 170% is lower than 175%
const call_order_object& call = *borrow( borrower, bitusd.amount(1000), asset(15000), 1700);
call_order_id_type call_id = call.id;
// create another position with 310% collateral, call price is 15.5/1.75 CORE/USD = 62/7, tcr 200% is higher than 175%
const call_order_object& call2 = *borrow( borrower2, bitusd.amount(1000), asset(15500), 2000);
call_order_id_type call2_id = call2.id;
// create yet another position with 500% collateral, call price is 25/1.75 CORE/USD = 100/7, no tcr
const call_order_object& call3 = *borrow( borrower3, bitusd.amount(1000), asset(25000));
transfer(borrower, seller, bitusd.amount(1000));
transfer(borrower2, seller, bitusd.amount(1000));
transfer(borrower3, seller, bitusd.amount(1000));
BOOST_CHECK_EQUAL( 1000, call.debt.value );
BOOST_CHECK_EQUAL( 15000, call.collateral.value );
BOOST_CHECK_EQUAL( 1000, call2.debt.value );
BOOST_CHECK_EQUAL( 15500, call2.collateral.value );
BOOST_CHECK_EQUAL( 1000, call3.debt.value );
BOOST_CHECK_EQUAL( 25000, call3.collateral.value );
BOOST_CHECK_EQUAL( 3000, get_balance(seller, bitusd) );
BOOST_CHECK_EQUAL( 0, get_balance(seller, core) );
BOOST_CHECK_EQUAL( 3000, get_balance(seller, bitusd) );
BOOST_CHECK_EQUAL( init_balance - 15000, get_balance(borrower, core) );
BOOST_CHECK_EQUAL( init_balance - 15500, get_balance(borrower2, core) );
BOOST_CHECK_EQUAL( init_balance - 25000, get_balance(borrower3, core) );
BOOST_CHECK_EQUAL( 0, get_balance(borrower, bitusd) );
BOOST_CHECK_EQUAL( 0, get_balance(borrower2, bitusd) );
BOOST_CHECK_EQUAL( 0, get_balance(borrower3, bitusd) );
// This sell order above MSSP will not be matched with a call
limit_order_id_type sell_high = create_sell_order(seller, bitusd.amount(7), core.amount(78))->id;
BOOST_CHECK_EQUAL( db.find<limit_order_object>( sell_high )->for_sale.value, 7 );
BOOST_CHECK_EQUAL( 2993, get_balance(seller, bitusd) );
BOOST_CHECK_EQUAL( 0, get_balance(seller, core) );
// This buy order is too low will not be matched with a sell order
limit_order_id_type buy_low = create_sell_order(buyer, asset(80), bitusd.amount(10))->id;
BOOST_CHECK_EQUAL( 0, get_balance(buyer, bitusd) );
BOOST_CHECK_EQUAL( init_balance - 80, get_balance(buyer, core) );
// Create a sell order which will be matched with several call orders later, price 1/9
limit_order_id_type sell_id = create_sell_order(seller, bitusd.amount(500), core.amount(4500) )->id;
BOOST_CHECK_EQUAL( db.find<limit_order_object>( sell_id )->for_sale.value, 500 );
// prepare price feed to get call and call2 (but not call3) into margin call territory
current_feed.settlement_price = bitusd.amount( 1 ) / core.amount(10);
// call and call2's CR is quite high, and debt amount is quite a lot, assume neither of them will be completely filled
price match_price = sell_id(db).sell_price;
share_type call_to_cover = call_id(db).get_max_debt_to_cover(match_price,current_feed.settlement_price,1750);
share_type call2_to_cover = call2_id(db).get_max_debt_to_cover(match_price,current_feed.settlement_price,1750);
BOOST_CHECK_LT( call_to_cover.value, call_id(db).debt.value );
BOOST_CHECK_LT( call2_to_cover.value, call2_id(db).debt.value );
// even though call2 has a higher CR, since call's TCR is less than call2's TCR, so we expect call will cover less when called
BOOST_CHECK_LT( call_to_cover.value, call2_to_cover.value );
// adjust price feed to get call and call2 (but not call3) into margin call territory
publish_feed( bitusd, feedproducer, current_feed );
// settlement price = 1/10, mssp = 1/11
// firstly the limit order will match with call, at limit order's price: 1/9
const call_order_object* tmp_call = db.find<call_order_object>( call_id );
BOOST_CHECK( tmp_call != nullptr );
// call will receive call_to_cover, pay 9*call_to_cover
share_type call_to_pay = call_to_cover * 9;
BOOST_CHECK_EQUAL( 1000 - call_to_cover.value, call.debt.value );
BOOST_CHECK_EQUAL( 15000 - call_to_pay.value, call.collateral.value );
// new collateral ratio should be higher than mcr as well as tcr
BOOST_CHECK( call.debt.value * 10 * 1750 < call.collateral.value * 1000 );
idump( (call) );
// borrower's balance doesn't change
BOOST_CHECK_EQUAL( init_balance - 15000, get_balance(borrower, core) );
BOOST_CHECK_EQUAL( 0, get_balance(borrower, bitusd) );
// the limit order then will match with call2, at limit order's price: 1/9
const call_order_object* tmp_call2 = db.find<call_order_object>( call2_id );
BOOST_CHECK( tmp_call2 != nullptr );
// if the limit is big enough, call2 will receive call2_to_cover, pay 11*call2_to_cover
// however it's not the case, so call2 will receive less
call2_to_cover = 500 - call_to_cover;
share_type call2_to_pay = call2_to_cover * 9;
BOOST_CHECK_EQUAL( 1000 - call2_to_cover.value, call2.debt.value );
BOOST_CHECK_EQUAL( 15500 - call2_to_pay.value, call2.collateral.value );
idump( (call2) );
// borrower2's balance doesn't change
BOOST_CHECK_EQUAL( init_balance - 15500, get_balance(borrower2, core) );
BOOST_CHECK_EQUAL( 0, get_balance(borrower2, bitusd) );
// call3 is not in margin call territory so won't be matched
BOOST_CHECK_EQUAL( 1000, call3.debt.value );
BOOST_CHECK_EQUAL( 25000, call3.collateral.value );
// sell_id is completely filled
BOOST_CHECK( !db.find<limit_order_object>( sell_id ) );
// check seller balance
BOOST_CHECK_EQUAL( 2493, get_balance(seller, bitusd) ); // 3000 - 7 - 500
BOOST_CHECK_EQUAL( 4500, get_balance(seller, core) ); // 500*9
// buy_low's price is too low that won't be matched
BOOST_CHECK_EQUAL( db.find<limit_order_object>( buy_low )->for_sale.value, 80 );
// generate a block
generate_block();
} FC_LOG_AND_RETHROW() }
BOOST_AUTO_TEST_CASE(mcr_bug_increase_before1270)
{ try {
auto mi = db.get_global_properties().parameters.maintenance_interval;
generate_blocks(HARDFORK_CORE_453_TIME - mi);
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
generate_block();
set_expiration( db, trx );
ACTORS((seller)(borrower)(borrower2)(feedproducer));
const auto& bitusd = create_bitasset("USDBIT", feedproducer_id);
const auto& core = asset_id_type()(db);
int64_t init_balance(1000000);
transfer(committee_account, borrower_id, asset(init_balance));
transfer(committee_account, borrower2_id, asset(init_balance));
update_feed_producers( bitusd, {feedproducer.id} );
price_feed current_feed;
current_feed.settlement_price = bitusd.amount( 100 ) / core.amount(100);
current_feed.maintenance_collateral_ratio = 1750;
current_feed.maximum_short_squeeze_ratio = 1100;
publish_feed( bitusd, feedproducer, current_feed );
const call_order_object& b1 = *borrow( borrower, bitusd.amount(1000), asset(1800));
auto b1_id = b1.id;
const call_order_object& b2 = *borrow( borrower2, bitusd.amount(1000), asset(2000) );
auto b2_id = b2.id;
BOOST_CHECK_EQUAL( get_balance( borrower, bitusd ), 1000 );
BOOST_CHECK_EQUAL( get_balance( borrower2, bitusd ), 1000 );
BOOST_CHECK_EQUAL( get_balance( borrower , core ), init_balance - 1800 );
BOOST_CHECK_EQUAL( get_balance( borrower2, core ), init_balance - 2000 );
// move order to margin call territory with mcr only
current_feed.maintenance_collateral_ratio = 2000;
publish_feed( bitusd, feedproducer, current_feed );
BOOST_CHECK_EQUAL( get_balance( borrower, bitusd ), 1000 );
BOOST_CHECK_EQUAL( get_balance( borrower2, bitusd ), 1000 );
BOOST_CHECK_EQUAL( get_balance( borrower , core ), 998200 );
BOOST_CHECK_EQUAL( get_balance( borrower2, core ), 998000 );
BOOST_CHECK( db.find<call_order_object>( b1_id ) );
BOOST_CHECK( db.find<call_order_object>( b2_id ) );
// attempt to trade the margin call
create_sell_order( borrower2, bitusd.amount(1000), core.amount(1100) );
BOOST_CHECK_EQUAL( get_balance( borrower, bitusd ), 1000 );
BOOST_CHECK_EQUAL( get_balance( borrower2, bitusd ), 0 );
BOOST_CHECK_EQUAL( get_balance( borrower , core ), 998200 );
BOOST_CHECK_EQUAL( get_balance( borrower2, core ), 998000 );
print_market(bitusd.symbol, core.symbol);
// both calls are still there, no margin call, mcr bug
BOOST_CHECK( db.find<call_order_object>( b1_id ) );
BOOST_CHECK( db.find<call_order_object>( b2_id ) );
} FC_LOG_AND_RETHROW() }
BOOST_AUTO_TEST_CASE(mcr_bug_increase_after1270)
{ try {
auto mi = db.get_global_properties().parameters.maintenance_interval;
generate_blocks(HARDFORK_CORE_1270_TIME - mi);
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
generate_block();
set_expiration( db, trx );
ACTORS((seller)(borrower)(borrower2)(feedproducer));
const auto& bitusd = create_bitasset("USDBIT", feedproducer_id);
const auto& core = asset_id_type()(db);
int64_t init_balance(1000000);
transfer(committee_account, borrower_id, asset(init_balance));
transfer(committee_account, borrower2_id, asset(init_balance));
update_feed_producers( bitusd, {feedproducer.id} );
price_feed current_feed;
current_feed.settlement_price = bitusd.amount( 100 ) / core.amount(100);
current_feed.maintenance_collateral_ratio = 1750;
current_feed.maximum_short_squeeze_ratio = 1100;
publish_feed( bitusd, feedproducer, current_feed );
const call_order_object& b1 = *borrow( borrower, bitusd.amount(1000), asset(1800));
auto b1_id = b1.id;
const call_order_object& b2 = *borrow( borrower2, bitusd.amount(1000), asset(2000) );
auto b2_id = b2.id;
BOOST_CHECK_EQUAL( get_balance( borrower, bitusd ), 1000 );
BOOST_CHECK_EQUAL( get_balance( borrower2, bitusd ), 1000 );
BOOST_CHECK_EQUAL( get_balance( borrower , core ), init_balance - 1800 );
BOOST_CHECK_EQUAL( get_balance( borrower2, core ), init_balance - 2000 );
// move order to margin call territory with mcr only
current_feed.maintenance_collateral_ratio = 2000;
publish_feed( bitusd, feedproducer, current_feed );
BOOST_CHECK_EQUAL( get_balance( borrower, bitusd ), 1000 );
BOOST_CHECK_EQUAL( get_balance( borrower2, bitusd ), 1000 );
BOOST_CHECK_EQUAL( get_balance( borrower , core ), 998200 );
BOOST_CHECK_EQUAL( get_balance( borrower2, core ), 998000 );
BOOST_CHECK( db.find<call_order_object>( b1_id ) );
BOOST_CHECK( db.find<call_order_object>( b2_id ) );
// attempt to trade the margin call
create_sell_order( borrower2, bitusd.amount(1000), core.amount(1100) );
BOOST_CHECK_EQUAL( get_balance( borrower, bitusd ), 1000 );
BOOST_CHECK_EQUAL( get_balance( borrower2, bitusd ), 0 );
BOOST_CHECK_EQUAL( get_balance( borrower , core ), 998900 );
BOOST_CHECK_EQUAL( get_balance( borrower2, core ), 999100 );
print_market(bitusd.symbol, core.symbol);
// b1 is margin called
BOOST_CHECK( ! db.find<call_order_object>( b1_id ) );
BOOST_CHECK( db.find<call_order_object>( b2_id ) );
} FC_LOG_AND_RETHROW() }
BOOST_AUTO_TEST_CASE(mcr_bug_decrease_before1270)
{ try {
auto mi = db.get_global_properties().parameters.maintenance_interval;
generate_blocks(HARDFORK_CORE_453_TIME - mi);
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
generate_block();
set_expiration( db, trx );
ACTORS((seller)(borrower)(borrower2)(feedproducer));
const auto& bitusd = create_bitasset("USDBIT", feedproducer_id);
const auto& core = asset_id_type()(db);
int64_t init_balance(1000000);
transfer(committee_account, borrower_id, asset(init_balance));
transfer(committee_account, borrower2_id, asset(init_balance));
update_feed_producers( bitusd, {feedproducer.id} );
price_feed current_feed;
current_feed.settlement_price = bitusd.amount( 100 ) / core.amount(100);
current_feed.maintenance_collateral_ratio = 1750;
current_feed.maximum_short_squeeze_ratio = 1100;
publish_feed( bitusd, feedproducer, current_feed );
const call_order_object& b1 = *borrow( borrower, bitusd.amount(1000), asset(1800));
auto b1_id = b1.id;
const call_order_object& b2 = *borrow( borrower2, bitusd.amount(1000), asset(2000) );
auto b2_id = b2.id;
BOOST_CHECK_EQUAL( get_balance( borrower, bitusd ), 1000 );
BOOST_CHECK_EQUAL( get_balance( borrower2, bitusd ), 1000 );
BOOST_CHECK_EQUAL( get_balance( borrower , core ), init_balance - 1800 );
BOOST_CHECK_EQUAL( get_balance( borrower2, core ), init_balance - 2000 );
// move order to margin call territory with the feed
current_feed.settlement_price = bitusd.amount( 100 ) / core.amount(150);
publish_feed( bitusd, feedproducer, current_feed );
// getting out of margin call territory with mcr change
current_feed.maintenance_collateral_ratio = 1100;
publish_feed( bitusd, feedproducer, current_feed );
BOOST_CHECK_EQUAL( get_balance( borrower, bitusd ), 1000 );
BOOST_CHECK_EQUAL( get_balance( borrower2, bitusd ), 1000 );
BOOST_CHECK_EQUAL( get_balance( borrower , core ), 998200 );
BOOST_CHECK_EQUAL( get_balance( borrower2, core ), 998000 );
BOOST_CHECK( db.find<call_order_object>( b1_id ) );
BOOST_CHECK( db.find<call_order_object>( b2_id ) );
// attempt to trade the margin call
create_sell_order( borrower2, bitusd.amount(1000), core.amount(1100) );
BOOST_CHECK_EQUAL( get_balance( borrower, bitusd ), 1000 );
BOOST_CHECK_EQUAL( get_balance( borrower2, bitusd ), 0 );
BOOST_CHECK_EQUAL( get_balance( borrower , core ), 998350 );
BOOST_CHECK_EQUAL( get_balance( borrower2, core ), 999650 );
print_market(bitusd.symbol, core.symbol);
// margin call at b1, mcr bug
BOOST_CHECK( !db.find<call_order_object>( b1_id ) );
BOOST_CHECK( db.find<call_order_object>( b2_id ) );
} FC_LOG_AND_RETHROW() }
BOOST_AUTO_TEST_CASE(mcr_bug_decrease_after1270)
{ try {
auto mi = db.get_global_properties().parameters.maintenance_interval;
generate_blocks(HARDFORK_CORE_1270_TIME - mi);
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
generate_block();
set_expiration( db, trx );
ACTORS((seller)(borrower)(borrower2)(feedproducer));
const auto& bitusd = create_bitasset("USDBIT", feedproducer_id);
const auto& core = asset_id_type()(db);
int64_t init_balance(1000000);
transfer(committee_account, borrower_id, asset(init_balance));
transfer(committee_account, borrower2_id, asset(init_balance));
update_feed_producers( bitusd, {feedproducer.id} );
price_feed current_feed;
current_feed.settlement_price = bitusd.amount( 100 ) / core.amount(100);
current_feed.maintenance_collateral_ratio = 1750;
current_feed.maximum_short_squeeze_ratio = 1100;
publish_feed( bitusd, feedproducer, current_feed );
const call_order_object& b1 = *borrow( borrower, bitusd.amount(1000), asset(1800));
auto b1_id = b1.id;
const call_order_object& b2 = *borrow( borrower2, bitusd.amount(1000), asset(2000) );
auto b2_id = b2.id;
BOOST_CHECK_EQUAL( get_balance( borrower, bitusd ), 1000 );
BOOST_CHECK_EQUAL( get_balance( borrower2, bitusd ), 1000 );
BOOST_CHECK_EQUAL( get_balance( borrower , core ), init_balance - 1800 );
BOOST_CHECK_EQUAL( get_balance( borrower2, core ), init_balance - 2000 );
// move order to margin call territory with the feed
current_feed.settlement_price = bitusd.amount( 100 ) / core.amount(150);
publish_feed( bitusd, feedproducer, current_feed );
// getting out of margin call territory with mcr decrease
current_feed.maintenance_collateral_ratio = 1100;
publish_feed( bitusd, feedproducer, current_feed );
BOOST_CHECK_EQUAL( get_balance( borrower, bitusd ), 1000 );
BOOST_CHECK_EQUAL( get_balance( borrower2, bitusd ), 1000 );
BOOST_CHECK_EQUAL( get_balance( borrower , core ), 998200 );
BOOST_CHECK_EQUAL( get_balance( borrower2, core ), 998000 );
BOOST_CHECK( db.find<call_order_object>( b1_id ) );
BOOST_CHECK( db.find<call_order_object>( b2_id ) );
// attempt to trade the margin call
create_sell_order( borrower2, bitusd.amount(1000), core.amount(1100) );
BOOST_CHECK_EQUAL( get_balance( borrower, bitusd ), 1000 );
BOOST_CHECK_EQUAL( get_balance( borrower2, bitusd ), 0 );
BOOST_CHECK_EQUAL( get_balance( borrower , core ), 998200 );
BOOST_CHECK_EQUAL( get_balance( borrower2, core ), 998000 );
print_market(bitusd.symbol, core.symbol);
// both calls are there, no margin call, good
BOOST_CHECK( db.find<call_order_object>( b1_id ) );
BOOST_CHECK( db.find<call_order_object>( b2_id ) );
} FC_LOG_AND_RETHROW() }
BOOST_AUTO_TEST_CASE(mcr_bug_cross1270)
{ try {
INVOKE(mcr_bug_increase_before1270);
auto mi = db.get_global_properties().parameters.maintenance_interval;
generate_blocks(HARDFORK_CORE_1270_TIME - mi);
const asset_object& core = get_asset(GRAPHENE_SYMBOL);
const asset_object& bitusd = get_asset("USDBIT");
const asset_id_type bitusd_id = bitusd.id;
const account_object& feedproducer = get_account("feedproducer");
// feed is expired
auto mcr = (*bitusd_id(db).bitasset_data_id)(db).current_feed.maintenance_collateral_ratio;
BOOST_CHECK_EQUAL(mcr, GRAPHENE_DEFAULT_MAINTENANCE_COLLATERAL_RATIO);
// make new feed
price_feed current_feed;
current_feed.settlement_price = bitusd.amount( 100 ) / core.amount(100);
current_feed.maintenance_collateral_ratio = 2000;
current_feed.maximum_short_squeeze_ratio = 1100;
publish_feed( bitusd, feedproducer, current_feed );
mcr = (*bitusd_id(db).bitasset_data_id)(db).current_feed.maintenance_collateral_ratio;
BOOST_CHECK_EQUAL(mcr, 2000);
// pass hardfork
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
generate_block();
// feed is still valid
mcr = (*bitusd_id(db).bitasset_data_id)(db).current_feed.maintenance_collateral_ratio;
BOOST_CHECK_EQUAL(mcr, 2000);
// margin call is traded
print_market(asset_id_type(1)(db).symbol, asset_id_type()(db).symbol);
// call b1 not there anymore
BOOST_CHECK( !db.find<call_order_object>( call_order_id_type() ) );
BOOST_CHECK( db.find<call_order_object>( call_order_id_type(1) ) );
} FC_LOG_AND_RETHROW() }
BOOST_AUTO_TEST_CASE(hardfork_core_338_test_after_hf1270)
{ try {
hf1270 = true;
INVOKE(hardfork_core_338_test);
} FC_LOG_AND_RETHROW() }
BOOST_AUTO_TEST_CASE(hardfork_core_453_test_after_hf1270)
{ try {
hf1270 = true;
INVOKE(hardfork_core_453_test);
} FC_LOG_AND_RETHROW() }
BOOST_AUTO_TEST_CASE(hardfork_core_625_big_limit_order_test_after_hf1270)
{ try {
hf1270 = true;
INVOKE(hardfork_core_625_big_limit_order_test);
} FC_LOG_AND_RETHROW() }
BOOST_AUTO_TEST_CASE(target_cr_test_limit_call_after_hf1270)
{ try {
hf1270 = true;
INVOKE(target_cr_test_limit_call);
} FC_LOG_AND_RETHROW() }
BOOST_AUTO_TEST_CASE(target_cr_test_call_limit_after_hf1270)
{ try {
hf1270 = true;
INVOKE(target_cr_test_call_limit);
} FC_LOG_AND_RETHROW() }
BOOST_AUTO_TEST_SUITE_END()
|
#include <stan/math/mix/scal.hpp>
#include <gtest/gtest.h>
#include <test/unit/math/rev/scal/fun/util.hpp>
#include <test/unit/math/mix/scal/fun/nan_util.hpp>
TEST(AgradFwdCos, FvarVar_1stDeriv) {
using stan::math::fvar;
using stan::math::var;
using std::cos;
using std::sin;
fvar<var> x(1.5, 1.3);
fvar<var> a = cos(x);
EXPECT_FLOAT_EQ(cos(1.5), a.val_.val());
EXPECT_FLOAT_EQ(1.3 * -sin(1.5), a.d_.val());
AVEC y = createAVEC(x.val_);
VEC g;
a.val_.grad(y, g);
EXPECT_FLOAT_EQ(-sin(1.5), g[0]);
}
TEST(AgradFwdCos, FvarVar_2ndDeriv) {
using stan::math::fvar;
using stan::math::var;
using std::cos;
using std::sin;
fvar<var> x(1.5, 1.3);
fvar<var> a = cos(x);
AVEC y = createAVEC(x.val_);
VEC g;
a.d_.grad(y, g);
EXPECT_FLOAT_EQ(-1.3 * cos(1.5), g[0]);
}
TEST(AgradFwdCos, FvarFvarVar_1stDeriv) {
using stan::math::fvar;
using stan::math::var;
using std::cos;
using std::sin;
fvar<fvar<var> > x;
x.val_.val_ = 1.5;
x.val_.d_ = 2.0;
fvar<fvar<var> > a = cos(x);
EXPECT_FLOAT_EQ(cos(1.5), a.val_.val_.val());
EXPECT_FLOAT_EQ(-2.0 * sin(1.5), a.val_.d_.val());
EXPECT_FLOAT_EQ(0, a.d_.val_.val());
EXPECT_FLOAT_EQ(0, a.d_.d_.val());
AVEC p = createAVEC(x.val_.val_);
VEC g;
a.val_.val_.grad(p, g);
EXPECT_FLOAT_EQ(-sin(1.5), g[0]);
fvar<fvar<var> > y;
y.val_.val_ = 1.5;
y.d_.val_ = 2.0;
fvar<fvar<var> > b = cos(y);
EXPECT_FLOAT_EQ(cos(1.5), b.val_.val_.val());
EXPECT_FLOAT_EQ(0, b.val_.d_.val());
EXPECT_FLOAT_EQ(-2.0 * sin(1.5), b.d_.val_.val());
EXPECT_FLOAT_EQ(0, b.d_.d_.val());
AVEC q = createAVEC(y.val_.val_);
VEC r;
b.val_.val_.grad(q, r);
EXPECT_FLOAT_EQ(-sin(1.5), r[0]);
}
TEST(AgradFwdCos, FvarFvarVar_2ndDeriv) {
using stan::math::fvar;
using stan::math::var;
using std::cos;
using std::sin;
fvar<fvar<var> > x;
x.val_.val_ = 1.5;
x.val_.d_ = 2.0;
fvar<fvar<var> > a = cos(x);
AVEC p = createAVEC(x.val_.val_);
VEC g;
a.val_.d_.grad(p, g);
EXPECT_FLOAT_EQ(-2.0 * cos(1.5), g[0]);
fvar<fvar<var> > y;
y.val_.val_ = 1.5;
y.d_.val_ = 2.0;
fvar<fvar<var> > b = cos(y);
AVEC q = createAVEC(y.val_.val_);
VEC r;
b.d_.val_.grad(q, r);
EXPECT_FLOAT_EQ(-2.0 * cos(1.5), r[0]);
}
TEST(AgradFwdCos, FvarFvarVar_3rdDeriv) {
using stan::math::fvar;
using stan::math::var;
using std::cos;
using std::sin;
fvar<fvar<var> > x;
x.val_.val_ = 1.5;
x.val_.d_ = 1.0;
x.d_.val_ = 1.0;
fvar<fvar<var> > a = cos(x);
AVEC p = createAVEC(x.val_.val_);
VEC g;
a.d_.d_.grad(p, g);
EXPECT_FLOAT_EQ(0.99749498660405443094172337114149, g[0]);
}
struct cos_fun {
template <typename T0>
inline T0 operator()(const T0& arg1) const {
return cos(arg1);
}
};
TEST(AgradFwdCos, cos_NaN) {
cos_fun cos_;
test_nan_mix(cos_, false);
}
|
#include <Renderer/Mesh.hpp>
#include <Renderer/Renderer.hpp>
#include <Renderer/Mesh3D.hpp>
namespace V3D
{
SHOWCASE_API Mesh::Mesh(Renderer& renderer, Mesh3D& mesh_data)
{
handle = mesh_create(renderer.handle, mesh_data.handle);
}
SHOWCASE_API void Mesh::destroy() const
{
mesh_destroy(handle);
}
SHOWCASE_API void Mesh::releaseResources() const
{
mesh_release_resources(handle);
}
SHOWCASE_API void Mesh::drop() const
{
mesh_destroy(handle);
mesh_release_resources(handle);
}
SHOWCASE_API void Mesh::drawIndexed() const
{
mesh_draw_indexed(handle);
}
SHOWCASE_API void Mesh::drawInstanced(u32 instanceCount) const
{
mesh_draw_instanced(handle, instanceCount);
}
SHOWCASE_API void Mesh::drawNonIndexed() const
{
mesh_draw(handle);
}
SHOWCASE_API void Mesh::drawIndexedInstanced(u32 instanceCount) const
{
mesh_draw_indexed_instanced(handle, instanceCount);
}
}
|
/* ----------------------------------------------------------------------
* gtiff.cpp()
* ----------------------------------------------------------------------
* Read and write a small set of tiff file formats.
*
* TODO: Merge xtiff and gtiff classes. Interface to libtiff.
* Valeriy: gtiff will be removed later. Now it is used for "cone" functions only.
* ----------------------------------------------------------------------
*/
#include "defs.h"
gtiff::gtiff(){
file_size = 0;
sprintf(err_message,"no errors");
vect = NULL;
ff = NULL;
StripOffsets = NULL;
StripByteCounts = NULL;
isII = true;
ImageWidth=0;
ImageLength=0;
BitsPerSample=16;
SamplesPerPixel = 1;
Compression=1;
PhotometricInterpretation=1;
OffsetStripOffsets=0;
RowsPerStrip=1;
OffsetStripByteCounts=0;
OffsetXResolution=0;
OffsetYResolution=0;
XResolution[0]=1;
XResolution[1]=1;
YResolution[0]=1;
YResolution[1]=1;
ResolutionUnit=1;
SampleFormat=1;
num_entries = 13;
}
bool gtiff::find_next_ifd(Ipp32u *off){
Ipp16u num_of_dir;
read_short(&num_of_dir);
num_entries+= Ipp32u (num_of_dir);
for(Ipp16u i=0;i<num_of_dir;i++)
read_entry();
read_long(off);
return true;
}
bool gtiff::ffind_next_ifd(Ipp32u *off){
Ipp16u num_of_dir;
fread_short(&num_of_dir);
num_entries += Ipp32u (num_of_dir);
for(Ipp16u i=0;i<num_of_dir;i++)
fread_entry();
fread_long(off);
return true;
}
void gtiff::setError(char *err_string){
sprintf(err_message,err_string);
printf("Error: %s.\n",err_message);
}
bool gtiff::getInfo(char *fileName, unsigned int *nx, unsigned int *ny, unsigned int *nb){
if(ff != NULL){
setError("another file is open");
return false;
}
ff = fopen(fileName,"rb");
if(ff == NULL){
setError("can not open the file");
return false;
}
long new_file_size;
fseek(ff, 0, SEEK_END);
new_file_size = ftell(ff);
if(new_file_size <=10){
sprintf(err_message,"file size (%li)",new_file_size);
return false;
}
if(vect != NULL || new_file_size != file_size){
ippsFree(vect); vect = NULL;
file_size = new_file_size;
}
vect = ippsMalloc_8u(file_size);
fseek(ff,0,SEEK_SET);
fread(vect,sizeof(Ipp8u),file_size,ff);
if(!fillTags()){
ippsFree(vect); vect = NULL;
return false;
}
*nx = ImageWidth;
*ny = ImageLength;
*nb = BitsPerSample;
return true;
}
bool gtiff::fread_short(Ipp16u *a){
fread(a,sizeof(Ipp16u),1,ff);
//*a = *((Ipp16u*)(vect+cur_pos));
if(isII == false)ippsSwapBytes_16u_I(a,1);
cur_pos+=2;
return true;
}
bool gtiff::read_short(Ipp16u *a){
*a = *((Ipp16u*)(vect+cur_pos));
if(isII == false)ippsSwapBytes_16u_I(a,1);
cur_pos+=2;
return true;
}
bool gtiff::fread_long(Ipp32u *a){
fread(a,sizeof(Ipp32u),1,ff);
// *a = *((Ipp32u*)(vect+cur_pos));
if(isII == false)ippsSwapBytes_32u_I(a,1);
cur_pos+=4;
return true;
}
bool gtiff::read_long(Ipp32u *a){
*a = *((Ipp32u*)(vect+cur_pos));
if(isII == false)ippsSwapBytes_32u_I(a,1);
cur_pos+=4;
return true;
}
bool gtiff::fillTags(){
if(vect[0] != vect[1]){
sprintf(ctemp,"this is not TIFF, first two byte are %i, %i",vect[0],vect[1]);
setError(ctemp);
return false;
}
if(vect[0] == 73){
isII = true;
}else if(vect[1] == 77){
isII = false;
}else{
sprintf(ctemp,"this is not TIFF, first two byte are %i, %i",vect[0],vect[1]);
setError(ctemp);
return false;
}
cur_pos = 2;
unsigned short sh;
read_short(&sh);
if(sh != 42){
sprintf(ctemp,"this is not TIFF, 3rd and 4th bytes give %i",sh);
setError(ctemp);
}
Ipp32u off;
read_long(&off);
cur_pos = off;
do{
find_next_ifd(&off);
}while(off >0);
StripByteCountsPerSample=BitsPerSample/8;
if(StripOffsets != NULL){
ippsFree(StripOffsets); StripOffsets = NULL;
}
if(StripByteCounts != NULL){
ippsFree(StripByteCounts); StripByteCounts = NULL;
}
StripOffsets = ippsMalloc_32u(StripsPerImage);
StripByteCounts = ippsMalloc_32u(StripsPerImage);
if(StripsPerImage == 1){
StripOffsets[0] = OffsetStripOffsets;
StripByteCounts[0] = StripByteCountsPerSample*ImageWidth*ImageLength;
}else{
cur_pos = OffsetStripOffsets;
for(Ipp32u i=0;i<StripsPerImage;i++)
read_long(StripOffsets + i);
cur_pos = OffsetStripByteCounts;
for(Ipp32u i=0;i<StripsPerImage;i++){
read_long(StripByteCounts +i);
}
}
return true;
}
bool gtiff::ffillTags(){
Ipp8u v0, v1;
v0 = (Ipp8u)fgetc(ff);
v1 = (Ipp8u)fgetc(ff);
if(v0 != v1){
sprintf(ctemp,"this is not TIFF, first two byte are %i, %i",v0,v1);
setError(ctemp);
return false;
}
if(v0 == 73){
isII = true;
}else if(v1 == 77){
isII = false;
}else{
sprintf(ctemp,"this is not TIFF, first two byte are %i, %i",v0,v1);
setError(ctemp);
return false;
}
cur_pos = 2;
unsigned short sh;
fread_short(&sh);
if(sh != 42){
sprintf(ctemp,"this is not TIFF, 3rd and 4th bytes give %i",sh);
setError(ctemp);
}
Ipp32u off;
fread_long(&off);
cur_pos = off;
do{
ffind_next_ifd(&off);
}while(off >0);
StripByteCountsPerSample=BitsPerSample/8;
StripOffsets = ippsMalloc_32u(StripsPerImage);
StripByteCounts = ippsMalloc_32u(StripsPerImage);
if(StripsPerImage == 1){
StripOffsets[0] = OffsetStripOffsets;
StripByteCounts[0] = StripByteCountsPerSample*ImageWidth*ImageLength;
}else{
cur_pos = OffsetStripOffsets;
for(Ipp32u i=0;i<StripsPerImage;i++)
fread_long(StripOffsets + i);
cur_pos = OffsetStripByteCounts;
for(Ipp32u i=0;i<StripsPerImage;i++){
fread_long(StripByteCounts +i);
}
}
return true;
}
bool gtiff::read_entry(){
Ipp16u tag, type;
Ipp32u count, value;
read_short(&tag);
read_short(&type);
read_long(&count);
read_long(&value);
// printf("Tag: %i, type: %i, count: %i, value: %i\n",tag,type,count,value);
switch(tag){
case 256:
ImageWidth=value;
if(ImageWidth >65536) ImageWidth/=65536;
break;
case 257:
ImageLength =value;
if(ImageLength >65536) ImageLength/=65536;
break;
case 258:
if(value > 256){
BitsPerSample=value/65536;
}else{
BitsPerSample=value;
}
break;
case 259:
Compression=value;
break;
case 262:
PhotometricInterpretation=value;
break;
case 273:
StripsPerImage=count;
OffsetStripOffsets=value;
break;
case 278:
RowsPerStrip=value;
break;
case 279:
OffsetStripByteCounts=value;
break;
case 282:
OffsetXResolution=value;
break;
case 283:
OffsetYResolution=value;
break;
case 296:
ResolutionUnit=value;
break;
default:
break;
}
return true;
}
bool gtiff::fread_entry(){
Ipp16u tag, type;
Ipp32u count, value;
fread_short(&tag);
fread_short(&type);
fread_long(&count);
fread_long(&value);
// printf("Tag: %i, type: %i, count: %i, value: %i\n",tag,type,count,value);
switch(tag){
case 256:
ImageWidth=value;
if(ImageWidth >65536) ImageWidth/=65536;
break;
case 257:
ImageLength =value;
if(ImageLength >65536) ImageLength/=65536;
break;
case 258:
if(value > 256){
BitsPerSample=value/65536;
}else{
BitsPerSample=value;
}
break;
case 259:
Compression=value;
break;
case 262:
PhotometricInterpretation=value;
break;
case 273:
StripsPerImage=count;
OffsetStripOffsets=value;
break;
case 278:
RowsPerStrip=value;
break;
case 279:
OffsetStripByteCounts=value;
break;
case 282:
OffsetXResolution=value;
break;
case 283:
OffsetYResolution=value;
break;
case 296:
ResolutionUnit=value;
break;
default:
break;
}
return true;
}
gtiff::~gtiff(){
if(ff != NULL) fclose(ff);
if(StripOffsets != NULL){
ippsFree(StripOffsets); StripOffsets = NULL;
}
if(StripByteCounts != NULL){
ippsFree(StripByteCounts); StripByteCounts = NULL;
}
if(vect != NULL){
ippsFree(vect); vect = NULL;
}
}
bool gtiff::read_float(char *fileName, Ipp32f *vec){
int nt, buff_size, iup, rem_buff_size;
if(ff != NULL)fclose(ff);
ff = fopen(fileName,"rb");
if(ff == NULL){
setError("can not open the file");
return false;
}
long new_file_size;
fseek(ff, 0, SEEK_END);
new_file_size = ftell(ff);
if(new_file_size <=10){
sprintf(err_message,"file size (%li)",new_file_size);
return false;
}
if(vect != NULL || new_file_size != file_size){
ippsFree(vect); vect = NULL;
file_size = new_file_size;
}
vect = ippsMalloc_8u(file_size);
fseek(ff,0,SEEK_SET);
fread(vect,sizeof(Ipp8u),file_size,ff);
if(!fillTags()){
ippsFree(vect); vect = NULL;
return false;
}
nt=ImageWidth*ImageLength;
buff_size=8*StripByteCounts[0]/BitsPerSample;
iup = (int)StripsPerImage;
if(iup == 1) buff_size = 8*this->OffsetStripByteCounts/BitsPerSample;
rem_buff_size = nt%buff_size;
if(rem_buff_size == 0){
rem_buff_size = buff_size;
if(nt>buff_size)iup--;
}
switch(BitsPerSample){
case 8:
for(int i=0;i<iup-1;i++){
ippsConvert_8u32f(vect+StripOffsets[i], vec+i*buff_size, buff_size);
}
ippsConvert_8u32f(vect+StripOffsets[iup-1], vec+(iup-1)*buff_size, rem_buff_size);
break;
case 16:
for(int i=0;i<iup-1;i++){
if(!isII)ippsSwapBytes_16u_I((Ipp16u*)(vect+StripOffsets[i]), buff_size);
ippsConvert_16u32f((Ipp16u*)(vect+StripOffsets[i]), vec+i*buff_size, buff_size);
}
if(!isII)ippsSwapBytes_16u_I((Ipp16u*)(vect+StripOffsets[iup-1]), buff_size);
ippsConvert_16u32f((Ipp16u*)(vect+StripOffsets[iup-1]), vec+(iup-1)*buff_size, rem_buff_size);
break;
case 32:
for(int i=0;i<iup-1;i++){
if(!isII)ippsSwapBytes_32u_I((Ipp32u*)(vect+StripOffsets[i]), buff_size);
ippsCopy_32f((Ipp32f*)(vect+StripOffsets[i]), vec+i*buff_size, buff_size);
}
if(!isII)ippsSwapBytes_32u_I((Ipp32u*)(vect+StripOffsets[iup-1]), buff_size);
ippsCopy_32f((Ipp32f*)(vect+StripOffsets[iup-1]), vec+(iup-1)*buff_size, rem_buff_size);
break;
default:
ippsZero_32f(vec,nt);
break;
}
return true;
}
bool gtiff::read_chunk(char *fileName, Ipp8u *vec, int rmin, int rmax){
if(ff != NULL)fclose(ff);
ff = fopen(fileName,"rb");
if(ff == NULL){
setError("can not open the file");
return false;
}
if(!ffillTags()){
return false;
}
int rs, s1, s2, r1, r2, nbytes;
nbytes = BitsPerSample/8;
rs = StripByteCounts[0]/(nbytes*ImageWidth);
r1 = rmin%rs;
s1 = rmin/rs;
r2 = rmax%rs;
s2 = rmax/rs;
int k;
fseek(ff,StripOffsets[s1]+r1*nbytes*ImageWidth,SEEK_SET);
if(s1<s2){
fread(vec,sizeof(Ipp8u),nbytes*ImageWidth*(rs-r1),ff);
k = rs-r1;
for(int i=s1+1;i<s2;i++){
fseek(ff,StripOffsets[i],SEEK_SET);
fread(vec+k*nbytes*ImageWidth,sizeof(Ipp8u),nbytes*ImageWidth*rs,ff);
k+=rs;
}
fseek(ff,StripOffsets[s2],SEEK_SET);
fread(vec+k*nbytes*ImageWidth,sizeof(Ipp8u),nbytes*ImageWidth*(r2+1),ff);
}else{
fread(vec,sizeof(Ipp8u),nbytes*ImageWidth*(r2-r1+1),ff);
}
if(!isII){
if(BitsPerSample == 16){
ippsSwapBytes_16u_I((Ipp16u*)vec, (rmax-rmin+1)*ImageWidth);
}else if(BitsPerSample == 32){
ippsSwapBytes_32u_I((Ipp32u*)vec, (rmax-rmin+1)*ImageWidth);
}
}
return true;
}
bool gtiff::read_int_16u(char *fileName, Ipp16u *vec){
int nt, buff_size, iup, rem_buff_size;
if(ff != NULL)fclose(ff);
ff = fopen(fileName,"rb");
if(ff == NULL){
setError("can not open the file");
return false;
}
long new_file_size;
fseek(ff, 0, SEEK_END);
new_file_size = ftell(ff);
if(new_file_size <=10){
sprintf(err_message,"file size (%li)",new_file_size);
return false;
}
if(vect != NULL || new_file_size != file_size){
ippsFree(vect); vect = NULL;
file_size = new_file_size;
}
vect = ippsMalloc_8u(file_size);
fseek(ff,0,SEEK_SET);
fread(vect,sizeof(Ipp8u),file_size,ff);
if(!fillTags()){
ippsFree(vect); vect = NULL;
return false;
}
nt=ImageWidth*ImageLength;
buff_size=8*StripByteCounts[0]/BitsPerSample;
iup = (int)StripsPerImage;
rem_buff_size = nt%buff_size;
if(rem_buff_size == 0){
rem_buff_size = buff_size;
if(nt>buff_size)iup--;
}
switch(BitsPerSample){
case 8:
for(int i=0;i<iup-1;i++){
ippsConvert_8s16s((Ipp8s*)(vect+StripOffsets[i]), (Ipp16s*)(vec+i*buff_size), buff_size);
}
ippsConvert_8s16s((Ipp8s*)(vect+StripOffsets[iup-1]), (Ipp16s*)(vec+(iup-1)*buff_size), rem_buff_size);
break;
case 16:
for(int i=0;i<iup-1;i++){
if(!isII)ippsSwapBytes_16u_I((Ipp16u*)(vect+StripOffsets[i]), buff_size);
ippsCopy_8u(vect+StripOffsets[i], (Ipp8u*)(vec+i*buff_size), 2*buff_size);
}
if(!isII)ippsSwapBytes_16u_I((Ipp16u*)(vect+StripOffsets[iup-1]), buff_size);
ippsCopy_8u(vect+StripOffsets[iup-1], (Ipp8u*)(vec+(iup-1)*buff_size), 2*rem_buff_size);
break;
default:
ippsZero_8u((Ipp8u*)vec,2*nt);
break;
}
return true;
}
bool gtiff::read_int_8u(char *fileName, Ipp8u *vec){
int nt, buff_size, iup, rem_buff_size;
if(ff != NULL)fclose(ff);
ff = fopen(fileName,"rb");
if(ff == NULL){
setError("can not open the file");
return false;
}
long new_file_size;
fseek(ff, 0, SEEK_END);
new_file_size = ftell(ff);
if(new_file_size <=10){
sprintf(err_message,"file size (%li)",new_file_size);
return false;
}
if(vect != NULL || new_file_size != file_size){
ippsFree(vect); vect = NULL;
file_size = new_file_size;
}
vect = ippsMalloc_8u(file_size);
fseek(ff,0,SEEK_SET);
fread(vect,sizeof(Ipp8u),file_size,ff);
if(!fillTags()){
ippsFree(vect); vect = NULL;
return false;
}
nt=ImageWidth*ImageLength;
buff_size=8*StripByteCounts[0]/BitsPerSample;
iup = (int)StripsPerImage;
rem_buff_size = nt%buff_size;
if(rem_buff_size == 0){
rem_buff_size = buff_size;
if(nt>buff_size)iup--;
}
switch(BitsPerSample){
case 8:
for(int i=0;i<iup-1;i++){
ippsCopy_8u(vect+StripOffsets[i], vec+i*buff_size, buff_size);
}
ippsCopy_8u(vect+StripOffsets[iup-1], vec+(iup-1)*buff_size, rem_buff_size);
break;
default:
ippsZero_8u(vec,nt);
break;
}
return true;
}
bool gtiff::print_short(Ipp16u a){
*(Ipp16u*)(vect+cur_pos) = a;
if(isII == false)ippsSwapBytes_16u_I((Ipp16u*)(vect+cur_pos),1);
cur_pos+=2;
return true;
}
bool gtiff::print_long(Ipp32u a){
*(Ipp32u*)(vect+cur_pos) = a;
if(isII == false)ippsSwapBytes_32u_I((Ipp32u*)(vect+cur_pos),1);
cur_pos+=4;
return true;
}
bool gtiff::print_ifd(Ipp16u tag, Ipp16u type, Ipp32u count, Ipp32u value){
print_short(tag);
print_short(type);
print_long(count);
print_long(value);
return true;
}
bool gtiff::fillTemplate(){
if(isII){
vect[0] = 73;
vect[1] = 73;
}else{
vect[0] = 77;
vect[1] = 77;
}
cur_pos = 2;
print_short(42);
print_long(8);
print_short(Ipp16u(num_entries));
StripsPerImage=1;
RowsPerStrip = ImageLength;
StripByteCountsPerSample=BitsPerSample/8;
StripOffsets=ippsMalloc_32u(StripsPerImage);
StripByteCounts=ippsMalloc_32u(StripsPerImage);
Ipp32u StripOffsets_min=14+12*num_entries+16;
if(SamplesPerPixel>2){
StripOffsets_min+=(2*(SamplesPerPixel-1));
}
StripOffsets[0]=StripOffsets_min;
StripByteCounts[0]=StripByteCountsPerSample*ImageWidth*ImageLength;
OffsetStripOffsets=StripOffsets[0];
OffsetStripByteCounts=StripByteCounts[0];
OffsetXResolution=14+12*num_entries;
OffsetYResolution=OffsetXResolution+8;
OffsetBitsPerSample = OffsetXResolution+16;
ResolutionUnit=1;
print_ifd(256,3,1,ImageWidth);
print_ifd(257,3,1,ImageLength);
if(SamplesPerPixel == 1){
print_ifd(258,3,1,BitsPerSample);
}else{
print_ifd(258,3,SamplesPerPixel,OffsetBitsPerSample);
}
print_ifd(259,3,1,Compression);
print_ifd(262,3,1,PhotometricInterpretation);
print_ifd(273,4,StripsPerImage,StripOffsets[0]);
print_ifd(277,3,1,SamplesPerPixel);
print_ifd(278,3,1,RowsPerStrip);
print_ifd(279,4,StripsPerImage,StripByteCounts[0]);
print_ifd(282,5,1,OffsetXResolution);
print_ifd(283,5,1,OffsetYResolution);
print_ifd(296,3,1,ResolutionUnit);
print_ifd(339,3,1,SampleFormat);
print_long(0);
print_long(XResolution[0]);
print_long(XResolution[1]);
print_long(YResolution[0]);
print_long(YResolution[1]);
if(SamplesPerPixel>2){
for(Ipp32u i=0; i<SamplesPerPixel; i++){
print_short((Ipp16u)BitsPerSample);
}
}
return true;
}
bool gtiff::print_float(char *fileName, Ipp32f *vec, unsigned int nx, unsigned int ny, unsigned int bits){
ff = fopen(fileName,"wb");
int nt = nx * ny;
if(ff == NULL){
setError("can not open the file");
return false;
}
int memsize;
int nb;
switch(bits){
case 8:
BitsPerSample = 8;
break;
case 16:
BitsPerSample = 16;
break;
case 32:
BitsPerSample = 32;
SampleFormat=3;
break;
default:
setError("wrong number of BitsPerSample");
return false;
}
nb = BitsPerSample/8;
//num_entries = 12;
memsize = 30+12*num_entries+nb*nt;
if(!(ImageWidth == nx && ImageLength == ny)){
if(vect != NULL) ippsFree(vect);
ImageWidth = nx;
ImageLength = ny;
vect = ippsMalloc_8u(memsize);
if(vect == NULL){
setError("can not allocate memory");
return false;
}
}
cur_pos = 0;
fillTemplate();
switch(bits){
case 8:
ippsConvert_32f8u_Sfs(vec, vect+cur_pos, nt, ippRndNear, 0);
break;
case 16:
ippsConvert_32f16u_Sfs(vec, (Ipp16u*)(vect+cur_pos), nt, ippRndNear, 0);
break;
case 32:
ippsCopy_32f(vec, (Ipp32f*)(vect+cur_pos),nt);
break;
}
fwrite(vect,sizeof(Ipp8u),memsize,ff);
fclose(ff);
ff = NULL;
return true;
}
bool gtiff::print_int_16u(char *fileName, Ipp16u *vec, unsigned int nx, unsigned int ny){
ff = fopen(fileName,"wb");
int nt = nx * ny;
if(ff == NULL){
setError("can not open the file");
return false;
}
int memsize;
int nbytes;
BitsPerSample = 16;
nbytes = BitsPerSample/8;
//num_entries = 12;
memsize = 30+12*num_entries+nbytes*nt;
if(!(ImageWidth == nx && ImageLength == ny)){
if(vect != NULL) ippsFree(vect);
ImageWidth = nx;
ImageLength = ny;
vect = ippsMalloc_8u(memsize);
if(vect == NULL){
setError("can not allocate memory");
return false;
}
}
cur_pos = 0;
fillTemplate();
ippsCopy_8u((Ipp8u*)vec, vect+cur_pos, nbytes*nt);
fwrite(vect,sizeof(Ipp8u),memsize,ff);
fclose(ff);
ff = NULL;
return true;
}
bool gtiff::print_int_32u(char *fileName, Ipp32u *vec, unsigned int nx, unsigned int ny){
ff = fopen(fileName,"wb");
int nt = nx * ny;
if(ff == NULL){
setError("can not open the file");
return false;
}
int memsize;
int nbytes;
BitsPerSample = 32;
nbytes = BitsPerSample/8;
//num_entries = 12;
memsize = 30+12*num_entries+nbytes*nt;
if(!(ImageWidth == nx && ImageLength == ny)){
if(vect != NULL) ippsFree(vect);
ImageWidth = nx;
ImageLength = ny;
vect = ippsMalloc_8u(memsize);
if(vect == NULL){
setError("can not allocate memory");
return false;
}
}
cur_pos = 0;
fillTemplate();
ippsCopy_8u((Ipp8u*)vec, vect+cur_pos, nbytes*nt);
fwrite(vect,sizeof(Ipp8u),memsize,ff);
fclose(ff);
ff = NULL;
return true;
}
bool gtiff::print_int_8u(char *fileName, Ipp8u *vec, unsigned int nx, unsigned int ny){
ff = fopen(fileName,"wb");
int nt = nx * ny;
if(ff == NULL){
setError("can not open the file");
return false;
}
int memsize;
int nbytes;
BitsPerSample = 8;
nbytes = BitsPerSample/8;
//num_entries = 12;
memsize = 30+12*num_entries+nbytes*nt;
if(!(ImageWidth == nx && ImageLength == ny)){
if(vect != NULL) ippsFree(vect);
ImageWidth = nx;
ImageLength = ny;
vect = ippsMalloc_8u(memsize);
if(vect == NULL){
setError("can not allocate memory");
return false;
}
}
cur_pos = 0;
fillTemplate();
ippsCopy_8u(vec, vect+cur_pos, nbytes*nt);
fwrite(vect,sizeof(Ipp8u),memsize,ff);
fclose(ff);
ff = NULL;
return true;
}
bool gtiff::print_rgb_8u(char *fileName, Ipp8u *vec, unsigned int nx, unsigned int ny){
ff = fopen(fileName,"wb");
int nt = nx * ny;
if(ff == NULL){
setError("can not open the file");
return false;
}
int memsize;
int nbytes;
PhotometricInterpretation=2;
BitsPerSample = 8;
SamplesPerPixel = 3;
nbytes = SamplesPerPixel*BitsPerSample/8;
//num_entries = 13;
memsize = 36+12*num_entries+nbytes*nt;
if(!(ImageWidth == nx && ImageLength == ny)){
if(vect != NULL) ippsFree(vect);
ImageWidth = nx;
ImageLength = ny;
vect = ippsMalloc_8u(memsize);
if(vect == NULL){
setError("can not allocate memory");
return false;
}
}
cur_pos = 0;
fillTemplate();
ippsCopy_8u(vec, vect+cur_pos, nbytes*nt);
fwrite(vect,sizeof(Ipp8u),memsize,ff);
fclose(ff);
ff = NULL;
return true;
}
bool gtiff::print_float_16u(char *fileName, Ipp32f *vec, unsigned int nx, unsigned int ny, float vmin, float vmax){
int nt = nx * ny;
float ratio = 65535.0f/(vmax-vmin);
ippsSubC_32f_I(vmin,vec,nt);
ippsMulC_32f_I(ratio,vec,nt);
return print_float_16u(fileName, vec, nx, ny);
}
bool gtiff::print_float_8u(char *fileName, Ipp32f *vec, unsigned int nx, unsigned int ny, float vmin, float vmax){
int nt = nx * ny;
float ratio = 255.0f/(vmax-vmin);
ippsSubC_32f_I(vmin,vec,nt);
ippsMulC_32f_I(ratio,vec,nt);
return print_float_8u(fileName, vec, nx, ny);
}
bool gtiff::print_float_32f(char *fileName, Ipp32f *vec, unsigned int nx, unsigned int ny, float vmin, float vmax){
int nt = nx * ny;
ippsThreshold_LTValGTVal_32f_I(vec,nt,vmin,vmin,vmax,vmax);
return print_float_32f(fileName, vec, nx, ny);
}
bool gtiff::print_float_8u(char *fileName, Ipp32f *vec, unsigned int nx, unsigned int ny){
return print_float(fileName, vec, nx, ny, 8);
}
bool gtiff::print_float_16u(char *fileName, Ipp32f *vec, unsigned int nx, unsigned int ny){
return print_float(fileName, vec, nx, ny, 16);
}
bool gtiff::print_float_32f(char *fileName, Ipp32f *vec, unsigned int nx, unsigned int ny){
return print_float(fileName, vec, nx, ny, 32);
}
|
// Solved 2021-04-11 17:01
// Runtime: 0 ms (100.00%)
// Memory Usage: 14.1 MB (92.24%)
class Solution {
public:
int trap(vector<int> &height) {
if (height.empty()) return 0;
int l = 0, r = height.size() - 1,
lmax = height[l], rmax = height[r],
res = 0;
while (l < r) {
// the amount of water trapped at each index
// depends only on its height and min(lmax, rmax)
if (height[l] < height[r]) {
// here we use the fact that height[r] <= rmax
// height[l] < height[r] <= rmax
if (height[l] >= lmax) {
// update lmax; no water will be trapped here
// as height[l] >= lmax >= min(lmax, rmax)
lmax = height[l];
} else {
// l would have stopped at lmax if lmax > rmax
res += lmax - height[l];
}
++l;
} else {
// height[r] <= height[l] <= lmax
if (height[r] >= rmax) {
// height[r] >= rmax >= min(lmax, rmax)
rmax = height[r];
} else {
// r would have stopped at rmax if rmax > lmax
res += rmax - height[r];
}
--r;
}
}
return res;
}
};
|
#pragma once
// interfaces
#include "io/OutputStream.hpp"
// implementations
#include "io/DataMatrix.hpp"
#include "io/FileOutputStream.hpp"
#include "io/FlatOutputStream.hpp"
#include "io/MapOutputStream.hpp"
|
// Copyright (c) 2009-2012 CIYAM Pty. Ltd. ACN 093 704 539
// Copyright (c) 2012-2018 CIYAM Developers
//
// Distributed under the MIT/X11 software license, please refer to the file license.txt
// in the root project directory or http://www.opensource.org/licenses/mit-license.php.
#ifdef PRECOMPILE_H
# include "precompile.h"
#endif
#pragma hdrstop
#ifndef HAS_PRECOMPILED_STD_HEADERS
# include <set>
# include <vector>
# include <string>
# include <fstream>
# include <iostream>
#endif
using namespace std;
const char* const c_title = "GENDEPS v0.1e";
const char* const c_usage = "Usage: gendeps [-i<include_paths>] [-o<object_path>] [-x<dependency ext>] <src_file>";
const char* const c_lit_include = "include";
set< string > include_names;
set< string > include_paths;
void transform_path_separators( string& path, char from = '/', char to = '\\' )
{
for( size_t i = 0; i < path.size( ); i++ )
{
if( path[ i ] == from )
path[ i ] = to;
}
}
bool get_include_name( const string& line, string& include )
{
size_t pos;
bool okay = true;
for( pos = 0; pos < line.size( ); pos++ )
{
if( line[ pos ] != ' ' )
break;
}
if( pos == line.size( ) || line[ pos ] != '#' )
okay = false;
if( okay )
{
for( pos = pos + 1; pos < line.size( ); pos++ )
{
if( line[ pos ] != ' ' )
break;
}
if( pos == line.size( ) )
okay = false;
if( okay )
{
string next( line.substr( pos ) );
// IMPORTANT: Remove C/C++ comments and trailing whitespace...
size_t pos_1 = next.find( "//" );
size_t pos_2 = next.find( "/*" );
pos = min( pos_1, pos_2 );
if( pos != string::npos )
{
while( pos > 0 && next[ pos - 1 ] == ' ' )
--pos;
next.erase( pos );
}
if( next.size( ) > string( c_lit_include ).size( ) )
{
if( next.substr( 0, string( c_lit_include ).size( ) ) != string( c_lit_include ) )
okay = false;
}
if( okay )
{
next.erase( 0, string( c_lit_include ).size( ) );
pos = 0;
while( next[ pos ] == ' ' )
++pos;
next = next.substr( pos );
if( next.size( ) < 3 || next[ 0 ] != '"' || next[ next.size( ) - 1 ] != '"' )
{
okay = false;
if( next.size( ) > 3 && ( next[ 0 ] != '<' || next[ next.size( ) - 1 ] != '>' ) )
{
cerr << "Error: Found unexpected string '" << next << "' parsing include line." << endl;
exit( 1 );
}
}
else
include = next.substr( 1, next.size( ) - 2 );
}
}
}
return okay;
}
void add_include_names( const string& file_name, bool is_root_file = true )
{
string path;
ifstream inpf( file_name.c_str( ) );
if( is_root_file && !inpf )
{
cerr << "Error: Unable to open source file '" << file_name << "' for input." << endl;
exit( 1 );
}
if( !is_root_file )
{
set< string >::iterator i;
for( i = include_paths.begin( ); i != include_paths.end( ); ++i )
{
string str( *i );
str += '\\';
str += file_name;
inpf.clear( );
inpf.open( str.c_str( ), ios::in );
if( inpf )
{
path = *i;
break;
}
}
if( !inpf )
{
cerr << "Error: Unable to open source file '" << file_name << "' for input." << endl;
exit( 1 );
}
string str( path );
if( !str.empty( ) )
str += '\\';
str += file_name;
transform_path_separators( str );
if( include_names.find( str ) != include_names.end( ) )
return;
include_names.insert( str );
size_t pos = str.find_last_of( '\\' );
if( pos != string::npos )
{
string current = str.substr( 0, pos );
if( include_paths.find( current ) == include_paths.end( ) )
include_paths.insert( current );
}
}
string line, include;
while( getline( inpf, line ) )
{
if( get_include_name( line, include ) )
add_include_names( include, false );
}
}
int main( int argc, char* argv[ ] )
{
bool has_object_path = false;
string src_file_name, dependency_file_extension( "obj" );
string object_file_path;
if( argc < 2 || argc > 5 )
{
cout << c_title << '\n' << c_usage << endl;
return 0;
}
int argnum = 1;
while( argnum < argc - 1 )
{
string opt( argv[ argnum++ ] );
if( opt.size( ) < 2
|| ( opt.substr( 0, 2 ) != "-i" && opt.substr( 0, 2 ) != "/i"
&& opt.substr( 0, 2 ) != "-o" && opt.substr( 0, 2 ) != "/o"
&& opt.substr( 0, 2 ) != "-x" && opt.substr( 0, 2 ) != "/x" ) )
{
cerr << "Error: Unknown option '" << opt << "'." << endl;
return 1;
}
bool is_object_path = false;
bool is_include_path = false;
if( opt.substr( 0, 2 ) == "-o" || opt.substr( 0, 2 ) == "/o" )
is_object_path = true;
else if( opt.substr( 0, 2 ) == "-i" || opt.substr( 0, 2 ) == "/i" )
is_include_path = true;
opt.erase( 0, 2 );
if( is_object_path )
{
object_file_path = opt;
has_object_path = true;
transform_path_separators( object_file_path );
if( !object_file_path.empty( ) && object_file_path[ object_file_path.size( ) - 1 ] != '\\' )
object_file_path += '\\';
}
else if( is_include_path )
{
size_t pos = opt.find( ';' );
while( true )
{
include_paths.insert( opt.substr( 0, pos ) );
if( pos == string::npos )
break;
opt.erase( 0, pos + 1 );
pos = opt.find( ';' );
}
}
else
dependency_file_extension = opt;
}
src_file_name = argv[ argnum ];
size_t pos = src_file_name.find_last_of( '.' );
if( pos == string::npos )
{
cerr << "Error: Didn't find file extension in '" << src_file_name << "'." << endl;
return 1;
}
string object_file( src_file_name.substr( 0, pos ) );
if( has_object_path )
{
transform_path_separators( object_file );
pos = object_file.find_last_of( '\\' );
if( pos != string::npos )
object_file.erase( 0, pos + 1 );
object_file = object_file_path + object_file;
}
add_include_names( src_file_name );
object_file = object_file + '.' + dependency_file_extension;
cout << object_file << ":\\\n" << ' ' << src_file_name;
set< string >::iterator i;
for( i = include_names.begin( ); i != include_names.end( ); i++ )
cout << "\\\n " << *i;
cout << endl;
return 0;
}
|
/* The copyright in this software is being made available under the BSD
* License, included below. This software may be subject to other third party
* and contributor rights, including patent rights, and no such rights are
* granted under this license.
*
* Copyright (c) 2010-2019, ITU/ISO/IEC
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
/** \file DecCu.cpp
\brief CU decoder class
*/
#include "DecCu.h"
#include "CommonLib/CrossCompPrediction.h"
#include "CommonLib/InterPrediction.h"
#include "CommonLib/IntraPrediction.h"
#include "CommonLib/Picture.h"
#include "CommonLib/UnitTools.h"
#include "CommonLib/dtrace_buffer.h"
#if RExt__DECODER_DEBUG_TOOL_STATISTICS
#include "CommonLib/CodingStatistics.h"
#endif
#if K0149_BLOCK_STATISTICS
#include "CommonLib/ChromaFormat.h"
#include "CommonLib/dtrace_blockstatistics.h"
#endif
//! \ingroup DecoderLib
//! \{
// ====================================================================================================================
// Constructor / destructor / create / destroy
// ====================================================================================================================
DecCu::DecCu()
{
m_tmpStorageLCU = NULL;
}
DecCu::~DecCu()
{
}
void DecCu::init( TrQuant* pcTrQuant, IntraPrediction* pcIntra, InterPrediction* pcInter)
{
m_pcTrQuant = pcTrQuant;
m_pcIntraPred = pcIntra;
m_pcInterPred = pcInter;
}
void DecCu::initDecCuReshaper (Reshape* pcReshape, ChromaFormat chromaFormatIDC)
{
m_pcReshape = pcReshape;
if (m_tmpStorageLCU == NULL)
{
m_tmpStorageLCU = new PelStorage;
m_tmpStorageLCU->create(UnitArea(chromaFormatIDC, Area(0, 0, MAX_CU_SIZE, MAX_CU_SIZE)));
}
}
void DecCu::destoryDecCuReshaprBuf()
{
if (m_tmpStorageLCU)
{
m_tmpStorageLCU->destroy();
delete m_tmpStorageLCU;
m_tmpStorageLCU = NULL;
}
}
// ====================================================================================================================
// Public member functions
// ====================================================================================================================
void DecCu::decompressCtu( CodingStructure& cs, const UnitArea& ctuArea )
{
const int maxNumChannelType = cs.pcv->chrFormat != CHROMA_400 && CS::isDualITree( cs ) ? 2 : 1;
if (!cs.pcv->isEncoder)
{
m_shareStateDec = NO_SHARE;
}
bool sharePrepareCondition = ((!cs.pcv->isEncoder) && (!(cs.slice->isIntra()) || cs.slice->getSPS()->getIBCFlag()));
#if JVET_O1170_CHECK_BV_AT_DECODER
if (cs.resetIBCBuffer)
{
m_pcInterPred->resetIBCBuffer(cs.pcv->chrFormat, cs.slice->getSPS()->getMaxCUHeight());
cs.resetIBCBuffer = false;
}
#endif
for( int ch = 0; ch < maxNumChannelType; ch++ )
{
const ChannelType chType = ChannelType( ch );
Position prevTmpPos;
prevTmpPos.x = -1; prevTmpPos.y = -1;
for( auto &currCU : cs.traverseCUs( CS::getArea( cs, ctuArea, chType ), chType ) )
{
#if JVET_O1170_CHECK_BV_AT_DECODER
if(currCU.Y().valid())
{
const int vSize = cs.slice->getSPS()->getMaxCUHeight() > 64 ? 64 : cs.slice->getSPS()->getMaxCUHeight();
if((currCU.Y().x % vSize) == 0 && (currCU.Y().y % vSize) == 0)
{
m_pcInterPred->resetVPDUforIBC(cs.pcv->chrFormat, cs.slice->getSPS()->getMaxCUHeight(), vSize, currCU.Y().x, currCU.Y().y);
}
}
#endif
if(sharePrepareCondition)
{
if ((currCU.shareParentPos.x >= 0) && (!(currCU.shareParentPos.x == prevTmpPos.x && currCU.shareParentPos.y == prevTmpPos.y)))
{
m_shareStateDec = GEN_ON_SHARED_BOUND;
#if !JVET_O0078_SINGLE_HMVPLUT
cs.motionLut.lutShareIbc = cs.motionLut.lutIbc;
#endif
}
if (currCU.shareParentPos.x < 0)
{
m_shareStateDec = 0;
}
prevTmpPos = currCU.shareParentPos;
}
#if JVET_O0119_BASE_PALETTE_444
if (currCU.predMode != MODE_INTRA && currCU.predMode != MODE_PLT && currCU.Y().valid())
#else
if (currCU.predMode != MODE_INTRA && currCU.Y().valid())
#endif
{
xDeriveCUMV(currCU);
}
switch( currCU.predMode )
{
case MODE_INTER:
case MODE_IBC:
xReconInter( currCU );
break;
#if JVET_O0119_BASE_PALETTE_444
case MODE_PLT:
#endif
case MODE_INTRA:
xReconIntraQT( currCU );
break;
default:
THROW( "Invalid prediction mode" );
break;
}
#if !JVET_O0525_REMOVE_PCM
if( CU::isLosslessCoded( currCU ) && !currCU.ipcm )
#else
if( CU::isLosslessCoded( currCU ) )
#endif
{
xFillPCMBuffer( currCU );
}
#if JVET_O1170_IBC_VIRTUAL_BUFFER
m_pcInterPred->xFillIBCBuffer(currCU);
#endif
DTRACE_BLOCK_REC( cs.picture->getRecoBuf( currCU ), currCU, currCU.predMode );
}
}
#if K0149_BLOCK_STATISTICS
getAndStoreBlockStatistics(cs, ctuArea);
#endif
}
// ====================================================================================================================
// Protected member functions
// ====================================================================================================================
void DecCu::xIntraRecBlk( TransformUnit& tu, const ComponentID compID )
{
if( !tu.blocks[ compID ].valid() )
{
return;
}
CodingStructure &cs = *tu.cs;
const CompArea &area = tu.blocks[compID];
const ChannelType chType = toChannelType( compID );
PelBuf piPred = cs.getPredBuf( area );
const PredictionUnit &pu = *tu.cs->getPU( area.pos(), chType );
const uint32_t uiChFinalMode = PU::getFinalIntraMode( pu, chType );
#if JVET_O0502_ISP_CLEANUP
PelBuf pReco = cs.getRecoBuf(area);
#endif
//===== init availability pattern =====
#if JVET_O0502_ISP_CLEANUP
#if JVET_O0106_ISP_4xN_PREDREG_FOR_1xN_2xN
bool predRegDiffFromTB = CU::isPredRegDiffFromTB(*tu.cu, compID);
bool firstTBInPredReg = CU::isFirstTBInPredReg(*tu.cu, compID, area);
CompArea areaPredReg(COMPONENT_Y, tu.chromaFormat, area);
#endif
if (tu.cu->ispMode && isLuma(compID))
{
#if JVET_O0106_ISP_4xN_PREDREG_FOR_1xN_2xN
if (predRegDiffFromTB)
{
if (firstTBInPredReg)
{
CU::adjustPredArea(areaPredReg);
m_pcIntraPred->initIntraPatternChTypeISP(*tu.cu, areaPredReg, pReco);
}
}
else
#endif
{
m_pcIntraPred->initIntraPatternChTypeISP(*tu.cu, area, pReco);
}
}
else
{
m_pcIntraPred->initIntraPatternChType(*tu.cu, area);
}
#else
#if JVET_O0106_ISP_4xN_PREDREG_FOR_1xN_2xN
bool predRegDiffFromTB = CU::isPredRegDiffFromTB(*tu.cu, compID);
bool firstTBInPredReg = CU::isFirstTBInPredReg (*tu.cu, compID, area);
CompArea areaPredReg(COMPONENT_Y, tu.chromaFormat, area);
if (predRegDiffFromTB)
{
if (firstTBInPredReg)
{
CU::adjustPredArea(areaPredReg);
m_pcIntraPred->initIntraPatternChType(*tu.cu, areaPredReg);
}
}
else
#endif
m_pcIntraPred->initIntraPatternChType(*tu.cu, area);
#endif
//===== get prediction signal =====
if( compID != COMPONENT_Y && PU::isLMCMode( uiChFinalMode ) )
{
const PredictionUnit& pu = *tu.cu->firstPU;
m_pcIntraPred->xGetLumaRecPixels( pu, area );
m_pcIntraPred->predIntraChromaLM( compID, piPred, pu, area, uiChFinalMode );
}
else
{
if( PU::isMIP( pu, chType ) )
{
m_pcIntraPred->initIntraMip( pu );
m_pcIntraPred->predIntraMip( compID, piPred, pu );
}
else
{
#if JVET_O0106_ISP_4xN_PREDREG_FOR_1xN_2xN
if (predRegDiffFromTB)
{
if (firstTBInPredReg)
{
PelBuf piPredReg = cs.getPredBuf(areaPredReg);
m_pcIntraPred->predIntraAng(compID, piPredReg, pu);
}
}
else
#endif
m_pcIntraPred->predIntraAng(compID, piPred, pu);
}
}
const Slice &slice = *cs.slice;
bool flag = slice.getLmcsEnabledFlag() && (slice.isIntra() || (!slice.isIntra() && m_pcReshape->getCTUFlag()));
if (flag && slice.getLmcsChromaResidualScaleFlag() && (compID != COMPONENT_Y) && (tu.cbf[COMPONENT_Cb] || tu.cbf[COMPONENT_Cr]))
{
const Area area = tu.Y().valid() ? tu.Y() : Area(recalcPosition(tu.chromaFormat, tu.chType, CHANNEL_TYPE_LUMA, tu.blocks[tu.chType].pos()), recalcSize(tu.chromaFormat, tu.chType, CHANNEL_TYPE_LUMA, tu.blocks[tu.chType].size()));
const CompArea &areaY = CompArea(COMPONENT_Y, tu.chromaFormat, area);
#if JVET_O1109_UNFIY_CRS
int adj = m_pcReshape->calculateChromaAdjVpduNei(tu, areaY);
#else
PelBuf piPredY;
piPredY = cs.picture->getPredBuf(areaY);
const Pel avgLuma = piPredY.computeAvg();
int adj = m_pcReshape->calculateChromaAdj(avgLuma);
#endif
tu.setChromaAdj(adj);
}
//===== inverse transform =====
PelBuf piResi = cs.getResiBuf( area );
const QpParam cQP( tu, compID );
#if JVET_O0105_ICT
if( tu.jointCbCr && isChroma(compID) )
{
if( compID == COMPONENT_Cb )
{
PelBuf resiCr = cs.getResiBuf( tu.blocks[ COMPONENT_Cr ] );
if( tu.jointCbCr >> 1 )
{
m_pcTrQuant->invTransformNxN( tu, COMPONENT_Cb, piResi, cQP );
}
else
{
const QpParam qpCr( tu, COMPONENT_Cr );
m_pcTrQuant->invTransformNxN( tu, COMPONENT_Cr, resiCr, qpCr );
}
m_pcTrQuant->invTransformICT( tu, piResi, resiCr );
}
}
else
#else
// Joint chroma residual mode: Cr uses negative of the signalled Cb residual
if ( tu.jointCbCr && compID == COMPONENT_Cr )
piResi.copyAndNegate( cs.getResiBuf( tu.blocks[COMPONENT_Cb] ) );
else
#endif
if( TU::getCbf( tu, compID ) )
{
m_pcTrQuant->invTransformNxN( tu, compID, piResi, cQP );
}
else
{
piResi.fill( 0 );
}
//===== reconstruction =====
flag = flag && (tu.blocks[compID].width*tu.blocks[compID].height > 4);
#if JVET_O0105_ICT
if (flag && (TU::getCbf(tu, compID) || tu.jointCbCr) && isChroma(compID) && slice.getLmcsChromaResidualScaleFlag())
{
#else
if (flag && TU::getCbf(tu, compID) && isChroma(compID) && slice.getLmcsChromaResidualScaleFlag())
{
if ( !(tu.jointCbCr && compID == COMPONENT_Cr) ) // // Joint chroma residual mode: chroma scaling took place already when doing Cb
#endif
piResi.scaleSignal(tu.getChromaAdj(), 0, tu.cu->cs->slice->clpRng(compID));
}
if( isChroma(compID) && tu.compAlpha[compID] != 0 )
{
CrossComponentPrediction::crossComponentPrediction( tu, compID, cs.getResiBuf( tu.Y() ), piResi, piResi, true );
}
#if !JVET_O0502_ISP_CLEANUP
PelBuf pReco = cs.getRecoBuf( area );
#endif
if( !tu.cu->ispMode || !isLuma( compID ) )
{
cs.setDecomp( area );
}
else if( tu.cu->ispMode && isLuma( compID ) && CU::isISPFirst( *tu.cu, tu.blocks[compID], compID ) )
{
cs.setDecomp( tu.cu->blocks[compID] );
}
#if REUSE_CU_RESULTS
CompArea tmpArea(COMPONENT_Y, area.chromaFormat, Position(0, 0), area.size());
PelBuf tmpPred;
#endif
if (slice.getLmcsEnabledFlag() && (m_pcReshape->getCTUFlag() || slice.isIntra()) && compID == COMPONENT_Y)
{
#if REUSE_CU_RESULTS
{
tmpPred = m_tmpStorageLCU->getBuf(tmpArea);
tmpPred.copyFrom(piPred);
}
#endif
}
#if KEEP_PRED_AND_RESI_SIGNALS
pReco.reconstruct( piPred, piResi, tu.cu->cs->slice->clpRng( compID ) );
#else
piPred.reconstruct( piPred, piResi, tu.cu->cs->slice->clpRng( compID ) );
#endif
#if !KEEP_PRED_AND_RESI_SIGNALS
pReco.copyFrom( piPred );
#endif
if (slice.getLmcsEnabledFlag() && (m_pcReshape->getCTUFlag() || slice.isIntra()) && compID == COMPONENT_Y)
{
#if REUSE_CU_RESULTS
{
piPred.copyFrom(tmpPred);
}
#endif
}
#if REUSE_CU_RESULTS
if( cs.pcv->isEncoder )
{
cs.picture->getRecoBuf( area ).copyFrom( pReco );
cs.picture->getPredBuf(area).copyFrom(piPred);
}
#endif
}
void DecCu::xReconIntraQT( CodingUnit &cu )
{
#if !JVET_O0525_REMOVE_PCM
if( cu.ipcm )
{
xReconPCM( *cu.firstTU );
return;
}
#endif
#if JVET_O0119_BASE_PALETTE_444
if (CU::isPLT(cu))
{
#if JVET_O0050_LOCAL_DUAL_TREE
if (cu.isSepTree())
#else
if (CS::isDualITree(*cu.cs))
#endif
{
if (cu.chType == CHANNEL_TYPE_LUMA)
{
xReconPLT(cu, COMPONENT_Y, 1);
}
if (cu.chromaFormat != CHROMA_400 && (cu.chType == CHANNEL_TYPE_CHROMA))
{
xReconPLT(cu, COMPONENT_Cb, 2);
}
}
else
{
xReconPLT(cu, COMPONENT_Y, 3);
}
return;
}
#endif
const uint32_t numChType = ::getNumberValidChannels( cu.chromaFormat );
for( uint32_t chType = CHANNEL_TYPE_LUMA; chType < numChType; chType++ )
{
if( cu.blocks[chType].valid() )
{
xIntraRecQT( cu, ChannelType( chType ) );
}
}
}
#if JVET_O0119_BASE_PALETTE_444
void DecCu::xReconPLT(CodingUnit &cu, ComponentID compBegin, uint32_t numComp)
{
const SPS& sps = *(cu.cs->sps);
TransformUnit& tu = *cu.firstTU;
PelBuf curPLTIdx = tu.getcurPLTIdx(compBegin);
uint32_t height = cu.block(compBegin).height;
uint32_t width = cu.block(compBegin).width;
//recon. pixels
uint32_t scaleX = getComponentScaleX(COMPONENT_Cb, sps.getChromaFormatIdc());
uint32_t scaleY = getComponentScaleY(COMPONENT_Cb, sps.getChromaFormatIdc());
for (uint32_t y = 0; y < height; y++)
{
for (uint32_t x = 0; x < width; x++)
{
for (uint32_t compID = compBegin; compID < (compBegin + numComp); compID++)
{
const int channelBitDepth = cu.cs->sps->getBitDepth(toChannelType((ComponentID)compID));
const CompArea &area = cu.blocks[compID];
PelBuf picReco = cu.cs->getRecoBuf(area);
PLTescapeBuf escapeValue = tu.getescapeValue((ComponentID)compID);
if (curPLTIdx.at(x, y) == cu.curPLTSize[compBegin])
{
Pel value;
QpParam cQP(tu, (ComponentID)compID);
#if JVET_O0919_TS_MIN_QP
int qp = cQP.Qp(false);
#else
int qp = cQP.Qp;
#endif
int qpRem = qp % 6;
int qpPer = qp / 6;
if (compBegin != COMPONENT_Y || compID == COMPONENT_Y)
{
int invquantiserRightShift = IQUANT_SHIFT;
int add = 1 << (invquantiserRightShift - 1);
value = ((((escapeValue.at(x, y)*g_invQuantScales[0][qpRem]) << qpPer) + add) >> invquantiserRightShift);
value = Pel(ClipBD<int>(value, channelBitDepth));
picReco.at(x, y) = value;
}
else if (compBegin == COMPONENT_Y && compID != COMPONENT_Y && y % (1 << scaleY) == 0 && x % (1 << scaleX) == 0)
{
uint32_t posYC = y >> scaleY;
uint32_t posXC = x >> scaleX;
int invquantiserRightShift = IQUANT_SHIFT;
int add = 1 << (invquantiserRightShift - 1);
value = ((((escapeValue.at(posXC, posYC)*g_invQuantScales[0][qpRem]) << qpPer) + add) >> invquantiserRightShift);
value = Pel(ClipBD<int>(value, channelBitDepth));
picReco.at(posXC, posYC) = value;
}
}
else
{
uint32_t curIdx = curPLTIdx.at(x, y);
if (compBegin != COMPONENT_Y || compID == COMPONENT_Y)
{
picReco.at(x, y) = cu.curPLT[compID][curIdx];
}
else if (compBegin == COMPONENT_Y && compID != COMPONENT_Y && y % (1 << scaleY) == 0 && x % (1 << scaleX) == 0)
{
uint32_t posYC = y >> scaleY;
uint32_t posXC = x >> scaleX;
picReco.at(posXC, posYC) = cu.curPLT[compID][curIdx];
}
}
}
}
}
for (uint32_t compID = compBegin; compID < (compBegin + numComp); compID++)
{
const CompArea &area = cu.blocks[compID];
PelBuf picReco = cu.cs->getRecoBuf(area);
cu.cs->picture->getRecoBuf(area).copyFrom(picReco);
cu.cs->setDecomp(area);
}
}
#endif
#if !JVET_O0525_REMOVE_PCM
/** Function for deriving reconstructed luma/chroma samples of a PCM mode CU.
* \param pcCU pointer to current CU
* \param uiPartIdx part index
* \param piPCM pointer to PCM code arrays
* \param piReco pointer to reconstructed sample arrays
* \param uiStride stride of reconstructed sample arrays
* \param uiWidth CU width
* \param uiHeight CU height
* \param compID colour component ID
* \returns void
*/
void DecCu::xDecodePCMTexture(TransformUnit &tu, const ComponentID compID)
{
const CompArea &area = tu.blocks[compID];
PelBuf piPicReco = tu.cs->getRecoBuf( area );
const CPelBuf piPicPcm = tu.getPcmbuf(compID);
const SPS &sps = *tu.cs->sps;
const uint32_t uiPcmLeftShiftBit = sps.getBitDepth(toChannelType(compID)) - sps.getPCMBitDepth(toChannelType(compID));
for (uint32_t uiY = 0; uiY < area.height; uiY++)
{
for (uint32_t uiX = 0; uiX < area.width; uiX++)
{
piPicReco.at(uiX, uiY) = (piPicPcm.at(uiX, uiY) << uiPcmLeftShiftBit);
}
}
tu.cs->picture->getRecoBuf( area ).copyFrom( piPicReco );
tu.cs->setDecomp( area );
}
/** Function for reconstructing a PCM mode CU.
* \param pcCU pointer to current CU
* \param uiDepth CU Depth
* \returns void
*/
void DecCu::xReconPCM(TransformUnit &tu)
{
#if !JVET_O0050_LOCAL_DUAL_TREE
const CodingStructure *cs = tu.cs;
#endif
const ChannelType chType = tu.chType;
#if JVET_O0050_LOCAL_DUAL_TREE
ComponentID compStr = (tu.cu->isSepTree() && !isLuma( chType )) ? COMPONENT_Cb : COMPONENT_Y;
ComponentID compEnd = (tu.cu->isSepTree() && isLuma( chType )) ? COMPONENT_Y : COMPONENT_Cr;
#else
ComponentID compStr = (CS::isDualITree(*cs) && !isLuma(chType)) ? COMPONENT_Cb: COMPONENT_Y;
ComponentID compEnd = (CS::isDualITree(*cs) && isLuma(chType)) ? COMPONENT_Y : COMPONENT_Cr;
#endif
for( ComponentID compID = compStr; compID <= compEnd; compID = ComponentID(compID+1) )
{
xDecodePCMTexture(tu, compID);
}
}
#endif
/** Function for deriving reconstructed PU/CU chroma samples with QTree structure
* \param pcRecoYuv pointer to reconstructed sample arrays
* \param pcPredYuv pointer to prediction sample arrays
* \param pcResiYuv pointer to residue sample arrays
* \param chType texture channel type (luma/chroma)
* \param rTu reference to transform data
*
\ This function derives reconstructed PU/CU chroma samples with QTree recursive structure
*/
void
DecCu::xIntraRecQT(CodingUnit &cu, const ChannelType chType)
{
for( auto &currTU : CU::traverseTUs( cu ) )
{
if( isLuma( chType ) )
{
xIntraRecBlk( currTU, COMPONENT_Y );
}
else
{
const uint32_t numValidComp = getNumberValidComponents( cu.chromaFormat );
for( uint32_t compID = COMPONENT_Cb; compID < numValidComp; compID++ )
{
xIntraRecBlk( currTU, ComponentID( compID ) );
}
}
}
}
/** Function for filling the PCM buffer of a CU using its reconstructed sample array
* \param pCU pointer to current CU
* \param depth CU Depth
*/
void DecCu::xFillPCMBuffer(CodingUnit &cu)
{
for( auto &currTU : CU::traverseTUs( cu ) )
{
for (const CompArea &area : currTU.blocks)
{
if( !area.valid() ) continue;;
CPelBuf source = cu.cs->getRecoBuf(area);
PelBuf destination = currTU.getPcmbuf(area.compID);
destination.copyFrom(source);
}
}
}
#include "CommonLib/dtrace_buffer.h"
void DecCu::xReconInter(CodingUnit &cu)
{
if( cu.triangle )
{
const bool splitDir = cu.firstPU->triangleSplitDir;
const uint8_t candIdx0 = cu.firstPU->triangleMergeIdx0;
const uint8_t candIdx1 = cu.firstPU->triangleMergeIdx1;
m_pcInterPred->motionCompensation4Triangle( cu, m_triangleMrgCtx, splitDir, candIdx0, candIdx1 );
PU::spanTriangleMotionInfo( *cu.firstPU, m_triangleMrgCtx, splitDir, candIdx0, candIdx1 );
}
else
{
m_pcIntraPred->geneIntrainterPred(cu);
// inter prediction
CHECK(CU::isIBC(cu) && cu.firstPU->mhIntraFlag, "IBC and MHIntra cannot be used together");
CHECK(CU::isIBC(cu) && cu.affine, "IBC and Affine cannot be used together");
CHECK(CU::isIBC(cu) && cu.triangle, "IBC and triangle cannot be used together");
CHECK(CU::isIBC(cu) && cu.firstPU->mmvdMergeFlag, "IBC and MMVD cannot be used together");
const bool luma = cu.Y().valid();
const bool chroma = cu.Cb().valid();
if (luma && chroma)
{
m_pcInterPred->motionCompensation(cu);
}
else
{
m_pcInterPred->motionCompensation(cu, REF_PIC_LIST_0, luma, chroma);
}
}
if (cu.Y().valid())
{
const PredictionUnit &pu = *cu.firstPU;
#if JVET_O0078_SINGLE_HMVPLUT
bool isShare = ((CU::isIBC(cu) && (cu.shareParentSize.width != cu.Y().lumaSize().width || cu.shareParentSize.height != cu.Y().lumaSize().height)) ? true : false);
if (!cu.affine && !cu.triangle && !isShare)
#else
if (!cu.affine && !cu.triangle)
#endif
{
MotionInfo mi = pu.getMotionInfo();
mi.GBiIdx = (mi.interDir == 3) ? cu.GBiIdx : GBI_DEFAULT;
cu.cs->addMiToLut(CU::isIBC(cu) ? cu.cs->motionLut.lutIbc : cu.cs->motionLut.lut, mi );
}
}
if (cu.firstPU->mhIntraFlag)
{
if (cu.cs->slice->getLmcsEnabledFlag() && m_pcReshape->getCTUFlag())
{
cu.cs->getPredBuf(*cu.firstPU).Y().rspSignal(m_pcReshape->getFwdLUT());
}
m_pcIntraPred->geneWeightedPred(COMPONENT_Y, cu.cs->getPredBuf(*cu.firstPU).Y(), *cu.firstPU, m_pcIntraPred->getPredictorPtr2(COMPONENT_Y, 0));
m_pcIntraPred->geneWeightedPred(COMPONENT_Cb, cu.cs->getPredBuf(*cu.firstPU).Cb(), *cu.firstPU, m_pcIntraPred->getPredictorPtr2(COMPONENT_Cb, 0));
m_pcIntraPred->geneWeightedPred(COMPONENT_Cr, cu.cs->getPredBuf(*cu.firstPU).Cr(), *cu.firstPU, m_pcIntraPred->getPredictorPtr2(COMPONENT_Cr, 0));
}
DTRACE ( g_trace_ctx, D_TMP, "pred " );
DTRACE_CRC( g_trace_ctx, D_TMP, *cu.cs, cu.cs->getPredBuf( cu ), &cu.Y() );
// inter recon
xDecodeInterTexture(cu);
// clip for only non-zero cbf case
CodingStructure &cs = *cu.cs;
if (cu.rootCbf)
{
#if REUSE_CU_RESULTS
const CompArea &area = cu.blocks[COMPONENT_Y];
CompArea tmpArea(COMPONENT_Y, area.chromaFormat, Position(0, 0), area.size());
PelBuf tmpPred;
#endif
if (cs.slice->getLmcsEnabledFlag() && m_pcReshape->getCTUFlag())
{
#if REUSE_CU_RESULTS
if (cs.pcv->isEncoder)
{
tmpPred = m_tmpStorageLCU->getBuf(tmpArea);
tmpPred.copyFrom(cs.getPredBuf(cu).get(COMPONENT_Y));
}
#endif
if (!cu.firstPU->mhIntraFlag && !CU::isIBC(cu))
cs.getPredBuf(cu).get(COMPONENT_Y).rspSignal(m_pcReshape->getFwdLUT());
}
#if KEEP_PRED_AND_RESI_SIGNALS
cs.getRecoBuf( cu ).reconstruct( cs.getPredBuf( cu ), cs.getResiBuf( cu ), cs.slice->clpRngs() );
#else
cs.getResiBuf( cu ).reconstruct( cs.getPredBuf( cu ), cs.getResiBuf( cu ), cs.slice->clpRngs() );
cs.getRecoBuf( cu ).copyFrom ( cs.getResiBuf( cu ) );
#endif
if (cs.slice->getLmcsEnabledFlag() && m_pcReshape->getCTUFlag())
{
#if REUSE_CU_RESULTS
if (cs.pcv->isEncoder)
{
cs.getPredBuf(cu).get(COMPONENT_Y).copyFrom(tmpPred);
}
#endif
}
}
else
{
cs.getRecoBuf(cu).copyClip(cs.getPredBuf(cu), cs.slice->clpRngs());
if (cs.slice->getLmcsEnabledFlag() && m_pcReshape->getCTUFlag() && !cu.firstPU->mhIntraFlag && !CU::isIBC(cu))
{
cs.getRecoBuf(cu).get(COMPONENT_Y).rspSignal(m_pcReshape->getFwdLUT());
}
}
DTRACE ( g_trace_ctx, D_TMP, "reco " );
DTRACE_CRC( g_trace_ctx, D_TMP, *cu.cs, cu.cs->getRecoBuf( cu ), &cu.Y() );
cs.setDecomp(cu);
}
void DecCu::xDecodeInterTU( TransformUnit & currTU, const ComponentID compID )
{
if( !currTU.blocks[compID].valid() ) return;
const CompArea &area = currTU.blocks[compID];
CodingStructure& cs = *currTU.cs;
//===== inverse transform =====
PelBuf resiBuf = cs.getResiBuf(area);
const QpParam cQP(currTU, compID);
#if JVET_O0105_ICT
if( currTU.jointCbCr && isChroma(compID) )
{
if( compID == COMPONENT_Cb )
{
PelBuf resiCr = cs.getResiBuf( currTU.blocks[ COMPONENT_Cr ] );
if( currTU.jointCbCr >> 1 )
{
m_pcTrQuant->invTransformNxN( currTU, COMPONENT_Cb, resiBuf, cQP );
}
else
{
const QpParam qpCr( currTU, COMPONENT_Cr );
m_pcTrQuant->invTransformNxN( currTU, COMPONENT_Cr, resiCr, qpCr );
}
m_pcTrQuant->invTransformICT( currTU, resiBuf, resiCr );
}
}
else
#else
// Joint chroma residual mode: Cr uses negative of the signalled Cb residual
if ( currTU.jointCbCr && compID == COMPONENT_Cr )
resiBuf.copyAndNegate( cs.getResiBuf( currTU.blocks[COMPONENT_Cb] ) );
else
#endif
if( TU::getCbf( currTU, compID ) )
{
m_pcTrQuant->invTransformNxN( currTU, compID, resiBuf, cQP );
}
else
{
resiBuf.fill( 0 );
}
//===== reconstruction =====
const Slice &slice = *cs.slice;
#if JVET_O0105_ICT
if (slice.getLmcsEnabledFlag() && isChroma(compID) && (TU::getCbf(currTU, compID) || currTU.jointCbCr)
&& slice.getLmcsChromaResidualScaleFlag() && currTU.blocks[compID].width * currTU.blocks[compID].height > 4)
{
#else
if (slice.getLmcsEnabledFlag() && isChroma(compID) && TU::getCbf(currTU, compID) && slice.getLmcsChromaResidualScaleFlag() && currTU.blocks[compID].width*currTU.blocks[compID].height > 4)
{
if ( !(currTU.jointCbCr && compID == COMPONENT_Cr) ) // Joint chroma residual mode: chroma scaling took place already when doing Cb
#endif
resiBuf.scaleSignal(currTU.getChromaAdj(), 0, currTU.cu->cs->slice->clpRng(compID));
}
if( isChroma( compID ) && currTU.compAlpha[compID] != 0 )
{
CrossComponentPrediction::crossComponentPrediction( currTU, compID, cs.getResiBuf( currTU.Y() ), resiBuf, resiBuf, true );
}
}
void DecCu::xDecodeInterTexture(CodingUnit &cu)
{
if( !cu.rootCbf )
{
return;
}
const uint32_t uiNumVaildComp = getNumberValidComponents(cu.chromaFormat);
for (uint32_t ch = 0; ch < uiNumVaildComp; ch++)
{
const ComponentID compID = ComponentID(ch);
for( auto& currTU : CU::traverseTUs( cu ) )
{
CodingStructure &cs = *cu.cs;
const Slice &slice = *cs.slice;
if (slice.getLmcsEnabledFlag() && slice.getLmcsChromaResidualScaleFlag() && (compID == COMPONENT_Y) && (currTU.cbf[COMPONENT_Cb] || currTU.cbf[COMPONENT_Cr]))
{
const CompArea &areaY = currTU.blocks[COMPONENT_Y];
#if JVET_O1109_UNFIY_CRS
int adj = m_pcReshape->calculateChromaAdjVpduNei(currTU, areaY);
#else
PelBuf predY = cs.getPredBuf(areaY);
CompArea tmpArea(COMPONENT_Y, areaY.chromaFormat, Position(0, 0), areaY.size());
PelBuf tmpPred = m_tmpStorageLCU->getBuf(tmpArea);
tmpPred.copyFrom(predY);
if (!cu.firstPU->mhIntraFlag && !CU::isIBC(cu))
tmpPred.rspSignal(m_pcReshape->getFwdLUT());
const Pel avgLuma = tmpPred.computeAvg();
int adj = m_pcReshape->calculateChromaAdj(avgLuma);
#endif
currTU.setChromaAdj(adj);
}
xDecodeInterTU( currTU, compID );
}
}
}
void DecCu::xDeriveCUMV( CodingUnit &cu )
{
for( auto &pu : CU::traversePUs( cu ) )
{
MergeCtx mrgCtx;
#if RExt__DECODER_DEBUG_TOOL_STATISTICS
if( pu.cu->affine )
{
CodingStatistics::IncrementStatisticTool( CodingStatisticsClassType{ STATS__TOOL_AFF, pu.Y().width, pu.Y().height } );
}
#endif
if( pu.mergeFlag )
{
if (pu.mmvdMergeFlag || pu.cu->mmvdSkip)
{
CHECK(pu.mhIntraFlag == true, "invalid MHIntra");
if (pu.cs->sps->getSBTMVPEnabledFlag())
{
Size bufSize = g_miScaling.scale(pu.lumaSize());
mrgCtx.subPuMvpMiBuf = MotionBuf(m_SubPuMiBuf, bufSize);
}
int fPosBaseIdx = pu.mmvdMergeIdx / MMVD_MAX_REFINE_NUM;
pu.shareParentPos = cu.shareParentPos;
pu.shareParentSize = cu.shareParentSize;
PU::getInterMergeCandidates(pu, mrgCtx, 1, fPosBaseIdx + 1);
PU::getInterMMVDMergeCandidates(pu, mrgCtx,
pu.mmvdMergeIdx
);
mrgCtx.setMmvdMergeCandiInfo(pu, pu.mmvdMergeIdx);
PU::spanMotionInfo(pu, mrgCtx);
}
else
{
{
if( pu.cu->triangle )
{
PU::getTriangleMergeCandidates( pu, m_triangleMrgCtx );
}
else
{
if( pu.cu->affine )
{
AffineMergeCtx affineMergeCtx;
if ( pu.cs->sps->getSBTMVPEnabledFlag() )
{
Size bufSize = g_miScaling.scale( pu.lumaSize() );
mrgCtx.subPuMvpMiBuf = MotionBuf( m_SubPuMiBuf, bufSize );
affineMergeCtx.mrgCtx = &mrgCtx;
}
PU::getAffineMergeCand( pu, affineMergeCtx, pu.mergeIdx );
pu.interDir = affineMergeCtx.interDirNeighbours[pu.mergeIdx];
pu.cu->affineType = affineMergeCtx.affineType[pu.mergeIdx];
pu.cu->GBiIdx = affineMergeCtx.GBiIdx[pu.mergeIdx];
pu.mergeType = affineMergeCtx.mergeType[pu.mergeIdx];
if ( pu.mergeType == MRG_TYPE_SUBPU_ATMVP )
{
pu.refIdx[0] = affineMergeCtx.mvFieldNeighbours[(pu.mergeIdx << 1) + 0][0].refIdx;
pu.refIdx[1] = affineMergeCtx.mvFieldNeighbours[(pu.mergeIdx << 1) + 1][0].refIdx;
}
else
{
for( int i = 0; i < 2; ++i )
{
if( pu.cs->slice->getNumRefIdx( RefPicList( i ) ) > 0 )
{
MvField* mvField = affineMergeCtx.mvFieldNeighbours[(pu.mergeIdx << 1) + i];
pu.mvpIdx[i] = 0;
pu.mvpNum[i] = 0;
pu.mvd[i] = Mv();
PU::setAllAffineMvField( pu, mvField, RefPicList( i ) );
}
}
}
PU::spanMotionInfo( pu, mrgCtx );
}
else
{
pu.shareParentPos = cu.shareParentPos;
pu.shareParentSize = cu.shareParentSize;
if (CU::isIBC(*pu.cu))
PU::getIBCMergeCandidates(pu, mrgCtx, pu.mergeIdx);
else
PU::getInterMergeCandidates(pu, mrgCtx, 0, pu.mergeIdx);
mrgCtx.setMergeInfo( pu, pu.mergeIdx );
PU::spanMotionInfo( pu, mrgCtx );
}
}
}
}
}
else
{
pu.shareParentPos = cu.shareParentPos;
pu.shareParentSize = cu.shareParentSize;
#if REUSE_CU_RESULTS
if ( cu.imv && !pu.cu->affine && !cu.cs->pcv->isEncoder )
#else
if (cu.imv && !pu.cu->affine)
#endif
{
PU::applyImv(pu, mrgCtx, m_pcInterPred);
}
else
{
if( pu.cu->affine )
{
for ( uint32_t uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
{
RefPicList eRefList = RefPicList( uiRefListIdx );
if ( pu.cs->slice->getNumRefIdx( eRefList ) > 0 && ( pu.interDir & ( 1 << uiRefListIdx ) ) )
{
AffineAMVPInfo affineAMVPInfo;
PU::fillAffineMvpCand( pu, eRefList, pu.refIdx[eRefList], affineAMVPInfo );
const unsigned mvp_idx = pu.mvpIdx[eRefList];
pu.mvpNum[eRefList] = affineAMVPInfo.numCand;
// Mv mv[3];
CHECK( pu.refIdx[eRefList] < 0, "Unexpected negative refIdx." );
if (!cu.cs->pcv->isEncoder)
{
pu.mvdAffi[eRefList][0].changeAffinePrecAmvr2Internal(pu.cu->imv);
pu.mvdAffi[eRefList][1].changeAffinePrecAmvr2Internal(pu.cu->imv);
if (cu.affineType == AFFINEMODEL_6PARAM)
{
pu.mvdAffi[eRefList][2].changeAffinePrecAmvr2Internal(pu.cu->imv);
}
}
Mv mvLT = affineAMVPInfo.mvCandLT[mvp_idx] + pu.mvdAffi[eRefList][0];
Mv mvRT = affineAMVPInfo.mvCandRT[mvp_idx] + pu.mvdAffi[eRefList][1];
mvRT += pu.mvdAffi[eRefList][0];
Mv mvLB;
if ( cu.affineType == AFFINEMODEL_6PARAM )
{
mvLB = affineAMVPInfo.mvCandLB[mvp_idx] + pu.mvdAffi[eRefList][2];
mvLB += pu.mvdAffi[eRefList][0];
}
PU::setAllAffineMv(pu, mvLT, mvRT, mvLB, eRefList, true);
}
}
}
else if (CU::isIBC(*pu.cu) && pu.interDir == 1)
{
AMVPInfo amvpInfo;
PU::fillIBCMvpCand(pu, amvpInfo);
pu.mvpNum[REF_PIC_LIST_0] = amvpInfo.numCand;
Mv mvd = pu.mvd[REF_PIC_LIST_0];
#if REUSE_CU_RESULTS
if (!cu.cs->pcv->isEncoder)
#endif
{
mvd.changeIbcPrecAmvr2Internal(pu.cu->imv);
}
#if JVET_O0162_IBC_MVP_FLAG
#if JVET_O0455_IBC_MAX_MERGE_NUM
if ( pu.cu->slice->getMaxNumIBCMergeCand() == 1 )
#else
if ( pu.cu->slice->getMaxNumMergeCand() == 1 )
#endif
{
CHECK( pu.mvpIdx[REF_PIC_LIST_0], "mvpIdx for IBC mode should be 0" );
}
#endif
pu.mv[REF_PIC_LIST_0] = amvpInfo.mvCand[pu.mvpIdx[REF_PIC_LIST_0]] + mvd;
pu.mv[REF_PIC_LIST_0].mvCliptoStorageBitDepth();
}
else
{
for ( uint32_t uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
{
RefPicList eRefList = RefPicList( uiRefListIdx );
if ((pu.cs->slice->getNumRefIdx(eRefList) > 0 || (eRefList == REF_PIC_LIST_0 && CU::isIBC(*pu.cu))) && (pu.interDir & (1 << uiRefListIdx)))
{
AMVPInfo amvpInfo;
PU::fillMvpCand(pu, eRefList, pu.refIdx[eRefList], amvpInfo);
pu.mvpNum [eRefList] = amvpInfo.numCand;
if (!cu.cs->pcv->isEncoder)
{
pu.mvd[eRefList].changeTransPrecAmvr2Internal(pu.cu->imv);
}
pu.mv[eRefList] = amvpInfo.mvCand[pu.mvpIdx[eRefList]] + pu.mvd[eRefList];
pu.mv[eRefList].mvCliptoStorageBitDepth();
}
}
}
PU::spanMotionInfo( pu, mrgCtx );
}
}
if( !cu.triangle )
{
if( g_mctsDecCheckEnabled && !MCTSHelper::checkMvBufferForMCTSConstraint( pu, true ) )
{
printf( "DECODER: pu motion vector across tile boundaries (%d,%d,%d,%d)\n", pu.lx(), pu.ly(), pu.lwidth(), pu.lheight() );
}
}
if (CU::isIBC(cu))
{
const int cuPelX = pu.Y().x;
const int cuPelY = pu.Y().y;
int roiWidth = pu.lwidth();
int roiHeight = pu.lheight();
#if !JVET_O1170_CHECK_BV_AT_DECODER
#if JVET_O1164_PS
const int picWidth = pu.cs->slice->getPPS()->getPicWidthInLumaSamples();
const int picHeight = pu.cs->slice->getPPS()->getPicHeightInLumaSamples();
#else
const int picWidth = pu.cs->slice->getSPS()->getPicWidthInLumaSamples();
const int picHeight = pu.cs->slice->getSPS()->getPicHeightInLumaSamples();
#endif
#endif
const unsigned int lcuWidth = pu.cs->slice->getSPS()->getMaxCUWidth();
int xPred = pu.mv[0].getHor() >> MV_FRACTIONAL_BITS_INTERNAL;
int yPred = pu.mv[0].getVer() >> MV_FRACTIONAL_BITS_INTERNAL;
#if JVET_O1170_CHECK_BV_AT_DECODER
CHECK(!m_pcInterPred->isLumaBvValid(lcuWidth, cuPelX, cuPelY, roiWidth, roiHeight, xPred, yPred), "invalid block vector for IBC detected.");
#else
#if !JVET_O1170_IBC_VIRTUAL_BUFFER
CHECK(!PU::isBlockVectorValid(pu, cuPelX, cuPelY, roiWidth, roiHeight, picWidth, picHeight, 0, 0, xPred, yPred, lcuWidth), "invalid block vector for IBC detected.");
#endif
#endif
}
}
}
//! \}
|
/// \file ParamGeneration.cpp
///
/// \brief Parameter manipulation routines for the Zerocoin cryptographic
/// components.
///
/// \author Ian Miers, Christina Garman and Matthew Green
/// \date June 2013
///
/// \copyright Copyright 2013 Ian Miers, Christina Garman and Matthew Green
/// \license This project is released under the MIT license.
#include <string>
#include "Zerocoin.h"
#include <math.h>
using namespace std;
namespace libzerocoin {
/// \brief Fill in a set of Zerocoin parameters from a modulus "N".
/// \param N A trusted RSA modulus
/// \param aux An optional auxiliary string used in derivation
/// \param securityLevel A security level
///
/// \throws ZerocoinException if the process fails
///
/// Fills in a ZC_Params data structure deterministically from
/// a trustworthy RSA modulus "N", which is provided as a Bignum.
///
/// Note: this routine makes the fundamental assumption that "N"
/// encodes a valid RSA-style modulus of the form "e1*e2" for some
/// unknown safe primes "e1" and "e2". These factors must not
/// be known to any party, or the security of Zerocoin is
/// compromised. The integer "N" must be a MINIMUM of 1023
/// in length, and 3072 bits is strongly recommended.
///
void CalculateParams(Params ¶ms, Bignum N, string aux, uint32_t securityLevel) {
params.initialized = false;
params.accumulatorParams.initialized = false;
// Verify that |N| is > 1023 bits.
uint32_t NLen = N.bitSize();
if (NLen < 1023) {
throw ZerocoinException("Modulus must be at least 1023 bits");
}
// Verify that "securityLevel" is at least 80 bits (minimum).
if (securityLevel < 80) {
throw ZerocoinException("Security level must be at least 80 bits.");
}
// Set the accumulator modulus to "N".
params.accumulatorParams.accumulatorModulus = N;
// Calculate the required size of the field "F_p" into which
// we're embedding the coin commitment group. This may throw an
// exception if the securityLevel is too large to be supported
// by the current modulus.
uint32_t pLen = 0;
uint32_t qLen = 0;
calculateGroupParamLengths(NLen - 2, securityLevel, &pLen, &qLen);
// Calculate candidate parameters ("p", "q") for the coin commitment group
// using a deterministic process based on "N", the "aux" string, and
// the dedicated string "COMMITMENTGROUP".
params.coinCommitmentGroup = deriveIntegerGroupParams(calculateSeed(N, aux, securityLevel, STRING_COMMIT_GROUP),
pLen, qLen);
// Next, we derive parameters for a second Accumulated Value commitment group.
// This is a Schnorr group with the specific property that the order of the group
// must be exactly equal to "q" from the commitment group. We set
// the modulus of the new group equal to "2q+1" and test to see if this is prime.
params.serialNumberSoKCommitmentGroup = deriveIntegerGroupFromOrder(params.coinCommitmentGroup.modulus);
// Calculate the parameters for the internal commitment
// using the same process.
params.accumulatorParams.accumulatorPoKCommitmentGroup = deriveIntegerGroupParams(
calculateSeed(N, aux, securityLevel, STRING_AIC_GROUP),
qLen + 300, qLen + 1);
// Calculate the parameters for the accumulator QRN commitment generators. This isn't really
// a whole group, just a pair of random generators in QR_N.
uint32_t resultCtr;
params.accumulatorParams.accumulatorQRNCommitmentGroup.g = generateIntegerFromSeed(NLen - 1,
calculateSeed(N, aux,
securityLevel,
STRING_QRNCOMMIT_GROUPG),
&resultCtr).pow_mod(
Bignum(2), N);
params.accumulatorParams.accumulatorQRNCommitmentGroup.h = generateIntegerFromSeed(NLen - 1,
calculateSeed(N, aux,
securityLevel,
STRING_QRNCOMMIT_GROUPH),
&resultCtr).pow_mod(
Bignum(2), N);
// Calculate the accumulator base, which we calculate as "u = C**2 mod N"
// where C is an arbitrary value. In the unlikely case that "u = 1" we increment
// "C" and repeat.
Bignum constant(ACCUMULATOR_BASE_CONSTANT);
params.accumulatorParams.accumulatorBase = Bignum(1);
for (uint32_t count = 0;
count < MAX_ACCUMGEN_ATTEMPTS && params.accumulatorParams.accumulatorBase.isOne(); count++) {
params.accumulatorParams.accumulatorBase = constant.pow_mod(Bignum(2),
params.accumulatorParams.accumulatorModulus);
}
// Compute the accumulator range. The upper range is the largest possible coin commitment value.
// The lower range is sqrt(upper range) + 1. Since OpenSSL doesn't have
// a square root function we use a slightly higher approximation.
params.accumulatorParams.maxCoinValue = params.coinCommitmentGroup.modulus;
params.accumulatorParams.minCoinValue = Bignum(2).pow((params.coinCommitmentGroup.modulus.bitSize() / 2) + 3);
// If all went well, mark params as successfully initialized.
params.accumulatorParams.initialized = true;
// If all went well, mark params as successfully initialized.
params.initialized = true;
}
/// \brief Format a seed string by hashing several values.
/// \param N A Bignum
/// \param aux An auxiliary string
/// \param securityLevel The security level in bits
/// \param groupName A group description string
/// \throws ZerocoinException if the process fails
///
/// Returns the hash of the value.
arith_uint256 calculateGeneratorSeed(arith_uint256 seed, arith_uint256 pSeed, arith_uint256 qSeed, string label, uint32_t index, uint32_t count) {
CHashWriter hasher(0, 0);
arith_uint256 hash;
// Compute the hash of:
// <modulus>||<securitylevel>||<auxString>||groupName
hasher << seed;
hasher << string("||");
hasher << pSeed;
hasher << string("||");
hasher << qSeed;
hasher << string("||");
hasher << label;
hasher << string("||");
hasher << index;
hasher << string("||");
hasher << count;
return hasher.GetArith256Hash();
}
/// \brief Format a seed string by hashing several values.
/// \param N A Bignum
/// \param aux An auxiliary string
/// \param securityLevel The security level in bits
/// \param groupName A group description string
/// \throws ZerocoinException if the process fails
///
/// Returns the hash of the value.
arith_uint256 calculateSeed(Bignum modulus, string auxString, uint32_t securityLevel, string groupName) {
CHashWriter hasher(0, 0);
arith_uint256 hash;
// Compute the hash of:
// <modulus>||<securitylevel>||<auxString>||groupName
hasher << modulus;
hasher << string("||");
hasher << securityLevel;
hasher << string("||");
hasher << auxString;
hasher << string("||");
hasher << groupName;
arith_uint256 hx = UintToArith256(hasher.GetHash());
return hx;
}
arith_uint256 calculateHash(arith_uint256 input) {
CHashWriter hasher(0, 0);
// Compute the hash of "input"
hasher << input;
arith_uint256 hx = UintToArith256(hasher.GetHash());
return hx;
}
/// \brief Calculate field/group parameter sizes based on a security level.
/// \param maxPLen Maximum size of the field (modulus "p") in bits.
/// \param securityLevel Required security level in bits (at least 80)
/// \param pLen Result: length of "p" in bits
/// \param qLen Result: length of "q" in bits
/// \throws ZerocoinException if the process fails
///
/// Calculates the appropriate sizes of "p" and "q" for a prime-order
/// subgroup of order "q" embedded within a field "F_p". The sizes
/// are based on a 'securityLevel' provided in symmetric-equivalent
/// bits. Our choices slightly exceed the specs in FIPS 186-3:
///
/// securityLevel = 80: pLen = 1024, qLen = 256
/// securityLevel = 112: pLen = 2048, qLen = 256
/// securityLevel = 128: qLen = 3072, qLen = 320
///
/// If the length of "p" exceeds the length provided in "maxPLen", or
/// if "securityLevel < 80" this routine throws an exception.
void calculateGroupParamLengths(uint32_t maxPLen, uint32_t securityLevel,
uint32_t *pLen, uint32_t *qLen) {
*pLen = *qLen = 0;
if (securityLevel < 80) {
throw ZerocoinException("Security level must be at least 80 bits.");
} else if (securityLevel == 80) {
*qLen = 256;
*pLen = 1024;
} else if (securityLevel <= 112) {
*qLen = 256;
*pLen = 2048;
} else if (securityLevel <= 128) {
*qLen = 320;
*pLen = 3072;
} else {
throw ZerocoinException("Security level not supported.");
}
if (*pLen > maxPLen) {
throw ZerocoinException("Modulus size is too small for this security level.");
}
}
/// \brief Deterministically compute a set of group parameters using NIST procedures.
/// \param seedStr A byte string seeding the process.
/// \param pLen The desired length of the modulus "p" in bits
/// \param qLen The desired length of the order "q" in bits
/// \return An IntegerGroupParams object
///
/// Calculates the description of a group G of prime order "q" embedded within
/// a field "F_p". The input to this routine is in arbitrary seed. It uses the
/// algorithms described in FIPS 186-3 Appendix A.1.2 to calculate
/// primes "p" and "q". It uses the procedure in Appendix A.2.3 to
/// derive two generators "g", "h".
IntegerGroupParams deriveIntegerGroupParams(arith_uint256 seed, uint32_t pLen, uint32_t qLen) {
IntegerGroupParams result;
Bignum p;
Bignum q;
arith_uint256 pSeed, qSeed;
// Calculate "p" and "q" and "domain_parameter_seed" from the
// "seed" buffer above, using the procedure described in NIST
// FIPS 186-3, Appendix A.1.2.
calculateGroupModulusAndOrder(seed, pLen, qLen, &(result.modulus),
&(result.groupOrder), &pSeed, &qSeed);
// Calculate the generators "g", "h" using the process described in
// NIST FIPS 186-3, Appendix A.2.3. This algorithm takes ("p", "q",
// "domain_parameter_seed", "index"). We use "index" value 1
// to generate "g" and "index" value 2 to generate "h".
result.g = calculateGroupGenerator(seed, pSeed, qSeed, result.modulus, result.groupOrder, 1);
result.h = calculateGroupGenerator(seed, pSeed, qSeed, result.modulus, result.groupOrder, 2);
// Perform some basic tests to make sure we have good parameters
if ((uint32_t)(result.modulus.bitSize()) < pLen || // modulus is pLen bits long
(uint32_t)(result.groupOrder.bitSize()) < qLen || // order is qLen bits long
!(result.modulus.isPrime()) || // modulus is prime
!(result.groupOrder.isPrime()) || // order is prime
!((result.g.pow_mod(result.groupOrder, result.modulus)).isOne()) || // g^order mod modulus = 1
!((result.h.pow_mod(result.groupOrder, result.modulus)).isOne()) || // h^order mod modulus = 1
((result.g.pow_mod(Bignum(100), result.modulus)).isOne()) || // g^100 mod modulus != 1
((result.h.pow_mod(Bignum(100), result.modulus)).isOne()) || // h^100 mod modulus != 1
result.g == result.h || // g != h
result.g.isOne()) { // g != 1
// If any of the above tests fail, throw an exception
throw ZerocoinException("Group parameters are not valid");
}
return result;
}
/// \brief Deterministically compute a set of group parameters with a specified order.
/// \param groupOrder The order of the group
/// \return An IntegerGroupParams object
///
/// Given "q" calculates the description of a group G of prime order "q" embedded within
/// a field "F_p".
IntegerGroupParams
deriveIntegerGroupFromOrder(Bignum &groupOrder) {
IntegerGroupParams result;
// Set the order to "groupOrder"
result.groupOrder = groupOrder;
// Try possible values for "modulus" of the form "groupOrder * 2 * i" where
// "p" is prime and i is a counter starting at 1.
for (uint32_t i = 1; i < NUM_SCHNORRGEN_ATTEMPTS; i++) {
// Set modulus equal to "groupOrder * 2 * i"
result.modulus = (result.groupOrder * Bignum(i * 2)) + Bignum(1);
// Test the result for primality
// TODO: This is a probabilistic routine and thus not the right choice
if (result.modulus.isPrime(256)) {
// Success.
//
// Calculate the generators "g", "h" using the process described in
// NIST FIPS 186-3, Appendix A.2.3. This algorithm takes ("p", "q",
// "domain_parameter_seed", "index"). We use "index" value 1
// to generate "g" and "index" value 2 to generate "h".
arith_uint256 seed = calculateSeed(groupOrder, "", 128, "");
arith_uint256 pSeed = calculateHash(seed);
arith_uint256 qSeed = calculateHash(pSeed);
result.g = calculateGroupGenerator(seed, pSeed, qSeed, result.modulus, result.groupOrder, 1);
result.h = calculateGroupGenerator(seed, pSeed, qSeed, result.modulus, result.groupOrder, 2);
// Perform some basic tests to make sure we have good parameters
if (!(result.modulus.isPrime()) || // modulus is prime
!(result.groupOrder.isPrime()) || // order is prime
!((result.g.pow_mod(result.groupOrder, result.modulus)).isOne()) || // g^order mod modulus = 1
!((result.h.pow_mod(result.groupOrder, result.modulus)).isOne()) || // h^order mod modulus = 1
((result.g.pow_mod(Bignum(100), result.modulus)).isOne()) || // g^100 mod modulus != 1
((result.h.pow_mod(Bignum(100), result.modulus)).isOne()) || // h^100 mod modulus != 1
result.g == result.h || // g != h
result.g.isOne()) { // g != 1
// If any of the above tests fail, throw an exception
throw ZerocoinException("Group parameters are not valid");
}
return result;
}
}
// If we reached this point group generation has failed. Throw an exception.
throw ZerocoinException("Too many attempts to generate Schnorr group.");
}
/// \brief Deterministically compute a group description using NIST procedures.
/// \param seed A byte string seeding the process.
/// \param pLen The desired length of the modulus "p" in bits
/// \param qLen The desired length of the order "q" in bits
/// \param resultModulus A value "p" describing a finite field "F_p"
/// \param resultGroupOrder A value "q" describing the order of a subgroup
/// \param resultDomainParameterSeed A resulting seed for use in later calculations.
///
/// Calculates the description of a group G of prime order "q" embedded within
/// a field "F_p". The input to this routine is in arbitrary seed. It uses the
/// algorithms described in FIPS 186-3 Appendix A.1.2 to calculate
/// primes "p" and "q".
void calculateGroupModulusAndOrder(arith_uint256 seed, uint32_t pLen, uint32_t qLen,
Bignum *resultModulus, Bignum *resultGroupOrder,
arith_uint256 *resultPseed, arith_uint256 *resultQseed) {
// Verify that the seed length is >= qLen
if (qLen > (sizeof(seed)) * 8) {
// TODO: The use of 256-bit seeds limits us to 256-bit group orders. We should probably change this.
// throw ZerocoinException("Seed is too short to support the required security level.");
}
#ifdef ZEROCOIN_DEBUG
cout << "calculateGroupModulusAndOrder: pLen = " << pLen << endl;
#endif
// Generate a random prime for the group order.
// This may throw an exception, which we'll pass upwards.
// Result is the value "resultGroupOrder", "qseed" and "qgen_counter".
arith_uint256 qseed;
uint32_t qgen_counter;
*resultGroupOrder = generateRandomPrime(qLen, seed, &qseed, &qgen_counter);
// Using ⎡pLen / 2 + 1⎤ as the length and qseed as the input_seed, use the random prime
// routine to obtain p0 , pseed, and pgen_counter. We pass exceptions upward.
uint32_t p0len = ceil((pLen / 2.0) + 1);
arith_uint256 pseed;
uint32_t pgen_counter;
Bignum p0 = generateRandomPrime(p0len, qseed, &pseed, &pgen_counter);
// Set x = 0, old_counter = pgen_counter
uint32_t old_counter = pgen_counter;
// Generate a random integer "x" of pLen bits
uint32_t iterations;
Bignum x = generateIntegerFromSeed(pLen, pseed, &iterations);
pseed += (iterations + 1);
// Set x = 2^{pLen−1} + (x mod 2^{pLen–1}).
Bignum powerOfTwo = Bignum(2).pow(pLen - 1);
x = powerOfTwo + (x % powerOfTwo);
// t = ⎡x / (2 * resultGroupOrder * p0)⎤.
// TODO: we don't have a ceiling function
Bignum t = x / (Bignum(2) * (*resultGroupOrder) * p0);
// Now loop until we find a valid prime "p" or we fail due to
// pgen_counter exceeding ((4*pLen) + old_counter).
for (; pgen_counter <= ((4 * pLen) + old_counter); pgen_counter++) {
// If (2 * t * resultGroupOrder * p0 + 1) > 2^{pLen}, then
// t = ⎡2^{pLen−1} / (2 * resultGroupOrder * p0)⎤.
powerOfTwo = Bignum(2).pow(pLen);
Bignum prod = (Bignum(2) * t * (*resultGroupOrder) * p0) + Bignum(1);
if (prod > powerOfTwo) {
// TODO: implement a ceil function
t = Bignum(2).pow(pLen - 1) / (Bignum(2) * (*resultGroupOrder) * p0);
}
// Compute a candidate prime resultModulus = 2tqp0 + 1.
*resultModulus = (Bignum(2) * t * (*resultGroupOrder) * p0) + Bignum(1);
// Verify that resultModulus is prime. First generate a pseudorandom integer "a".
Bignum a = generateIntegerFromSeed(pLen, pseed, &iterations);
pseed += iterations + 1;
// Set a = 2 + (a mod (resultModulus–3)).
a = Bignum(2) + (a % ((*resultModulus) - Bignum(3)));
// Set z = a^{2 * t * resultGroupOrder} mod resultModulus
Bignum z = a.pow_mod(Bignum(2) * t * (*resultGroupOrder), (*resultModulus));
// If GCD(z–1, resultModulus) == 1 AND (z^{p0} mod resultModulus == 1)
// then we have found our result. Return.
if ((resultModulus->gcd(z - Bignum(1))).isOne() &&
(z.pow_mod(p0, (*resultModulus))).isOne()) {
// Success! Return the seeds and primes.
*resultPseed = pseed;
*resultQseed = qseed;
return;
}
// This prime did not work out. Increment "t" and try again.
t = t + Bignum(1);
} // loop continues until pgen_counter exceeds a limit
// We reach this point only if we exceeded our maximum iteration count.
// Throw an exception.
throw ZerocoinException("Unable to generate a prime modulus for the group");
}
/// \brief Deterministically compute a generator for a given group.
/// \param seed A first seed for the process.
/// \param pSeed A second seed for the process.
/// \param qSeed A third seed for the process.
/// \param modulus Proposed prime modulus for the field.
/// \param groupOrder Proposed order of the group.
/// \param index Index value, selects which generator you're building.
/// \return The resulting generator.
/// \throws A ZerocoinException if error.
///
/// Generates a random group generator deterministically as a function of (seed,pSeed,qSeed)
/// Uses the algorithm described in FIPS 186-3 Appendix A.2.3.
Bignum calculateGroupGenerator(arith_uint256 seed, arith_uint256 pSeed, arith_uint256 qSeed, Bignum modulus,
Bignum groupOrder, uint32_t index) {
Bignum result;
// Verify that 0 <= index < 256
if (index > 255) {
throw ZerocoinException("Invalid index for group generation");
}
// Compute e = (modulus - 1) / groupOrder
Bignum e = (modulus - Bignum(1)) / groupOrder;
// Loop until we find a generator
for (uint32_t count = 1; count < MAX_GENERATOR_ATTEMPTS; count++) {
// hash = Hash(seed || pSeed || qSeed || “ggen” || index || count
arith_uint256 hash = calculateGeneratorSeed(seed, pSeed, qSeed, "ggen", index, count);
Bignum W(hash);
// Compute result = W^e mod p
result = W.pow_mod(e, modulus);
// If result > 1, we have a generator
if (result > 1) {
return result;
}
}
// We only get here if we failed to find a generator
throw ZerocoinException("Unable to find a generator, too many attempts");
}
/// \brief Deterministically compute a random prime number.
/// \param primeBitLen Desired bit length of the prime.
/// \param in_seed Input seed for the process.
/// \param out_seed Result: output seed from the process.
/// \param prime_gen_counter Result: number of iterations required.
/// \return The resulting prime number.
/// \throws A ZerocoinException if error.
///
/// Generates a random prime number of primeBitLen bits from a given input
/// seed. Uses the Shawe-Taylor algorithm as described in FIPS 186-3
/// Appendix C.6. This is a recursive function.
Bignum generateRandomPrime(uint32_t primeBitLen, arith_uint256 in_seed, arith_uint256 *out_seed,
uint32_t *prime_gen_counter) {
// Verify that primeBitLen is not too small
if (primeBitLen < 2) {
throw ZerocoinException("Prime length is too short");
}
// If primeBitLen < 33 bits, perform the base case.
if (primeBitLen < 33) {
Bignum result(0);
// Set prime_seed = in_seed, prime_gen_counter = 0.
arith_uint256 prime_seed = in_seed;
(*prime_gen_counter) = 0;
// Loop up to "4 * primeBitLen" iterations.
while ((*prime_gen_counter) < (4 * primeBitLen)) {
// Generate a pseudorandom integer "c" of length primeBitLength bits
uint32_t iteration_count;
Bignum c = generateIntegerFromSeed(primeBitLen, prime_seed, &iteration_count);
#ifdef ZEROCOIN_DEBUG
cout << "generateRandomPrime: primeBitLen = " << primeBitLen << endl;
cout << "Generated c = " << c << endl;
#endif
prime_seed += (iteration_count + 1);
(*prime_gen_counter)++;
// Set "intc" to be the least odd integer >= "c" we just generated
uint32_t intc = c.getulong();
intc = (2 * floor(intc / 2.0)) + 1;
#ifdef ZEROCOIN_DEBUG
cout << "Should be odd. c = " << intc << endl;
cout << "The big num is: c = " << c << endl;
#endif
// Perform trial division on this (relatively small) integer to determine if "intc"
// is prime. If so, return success.
if (primalityTestByTrialDivision(intc)) {
// Return "intc" converted back into a Bignum and "prime_seed". We also updated
// the variable "prime_gen_counter" in previous statements.
result = intc;
*out_seed = prime_seed;
// Success
return result;
}
} // while()
// If we reached this point there was an error finding a candidate prime
// so throw an exception.
throw ZerocoinException("Unable to find prime in Shawe-Taylor algorithm");
// END OF BASE CASE
}
// If primeBitLen >= 33 bits, perform the recursive case.
else {
// Recurse to find a new random prime of roughly half the size
uint32_t newLength = ceil((double) primeBitLen / 2.0) + 1;
Bignum c0 = generateRandomPrime(newLength, in_seed, out_seed, prime_gen_counter);
// Generate a random integer "x" of primeBitLen bits using the output
// of the previous call.
uint32_t numIterations;
Bignum x = generateIntegerFromSeed(primeBitLen, *out_seed, &numIterations);
(*out_seed) += numIterations + 1;
// Compute "t" = ⎡x / (2 * c0⎤
// TODO no Ceiling call
Bignum t = x / (Bignum(2) * c0);
// Repeat the following procedure until we find a prime (or time out)
for (uint32_t testNum = 0; testNum < MAX_PRIMEGEN_ATTEMPTS; testNum++) {
// If ((2 * t * c0) + 1 > 2^{primeBitLen}),
// then t = ⎡2^{primeBitLen} – 1 / (2 * c0)⎤.
if ((Bignum(2) * t * c0) > (Bignum(2).pow(Bignum(primeBitLen)))) {
t = ((Bignum(2).pow(Bignum(primeBitLen))) - Bignum(1)) / (Bignum(2) * c0);
}
// Set c = (2 * t * c0) + 1
Bignum c = (Bignum(2) * t * c0) + Bignum(1);
// Increment prime_gen_counter
(*prime_gen_counter)++;
// Test "c" for primality as follows:
// 1. First pick an integer "a" in between 2 and (c - 2)
Bignum a = generateIntegerFromSeed(c.bitSize(), (*out_seed), &numIterations);
a = Bignum(2) + (a % (c - Bignum(3)));
(*out_seed) += (numIterations + 1);
// 2. Compute "z" = a^{2*t} mod c
Bignum z = a.pow_mod(Bignum(2) * t, c);
// 3. Check if "c" is prime.
// Specifically, verify that gcd((z-1), c) == 1 AND (z^c0 mod c) == 1
// If so we return "c" as our result.
if (c.gcd(z - Bignum(1)).isOne() && z.pow_mod(c0, c).isOne()) {
// Return "c", out_seed and prime_gen_counter
// (the latter two of which were already updated)
return c;
}
// 4. If the test did not succeed, increment "t" and loop
t = t + Bignum(1);
} // end of test loop
}
// We only reach this point if the test loop has iterated MAX_PRIMEGEN_ATTEMPTS
// and failed to identify a valid prime. Throw an exception.
throw ZerocoinException("Unable to generate random prime (too many tests)");
}
Bignum generateIntegerFromSeed(uint32_t numBits, arith_uint256 seed, uint32_t *numIterations) {
Bignum result(0);
uint32_t iterations = ceil((double) numBits / (double) HASH_OUTPUT_BITS);
#ifdef ZEROCOIN_DEBUG
cout << "numBits = " << numBits << endl;
cout << "iterations = " << iterations << endl;
#endif
// Loop "iterations" times filling up the value "result" with random bits
for (uint32_t count = 0; count < iterations; count++) {
// result += ( H(pseed + count) * 2^{count * p0len} )
result += Bignum(calculateHash(seed + count)) * Bignum(2).pow(count * HASH_OUTPUT_BITS);
}
result = Bignum(2).pow(numBits - 1) + (result % (Bignum(2).pow(numBits - 1)));
// Return the number of iterations and the result
*numIterations = iterations;
return result;
}
/// \brief Determines whether a uint32_t is a prime through trial division.
/// \param candidate Candidate to test.
/// \return true if the value is prime, false otherwise
///
/// Performs trial division to determine whether a uint32_t is prime.
bool
primalityTestByTrialDivision(uint32_t candidate) {
// TODO: HACK HACK WRONG WRONG
Bignum canBignum(candidate);
return canBignum.isPrime();
}
} // namespace libzerocoin
|
/**************************
* Includes
*
**************************/
#include <windows.h>
#include <gl/gl.h>
/**************************
* Function Declarations
*
**************************/
LRESULT CALLBACK WndProc (HWND hWnd, UINT message,
WPARAM wParam, LPARAM lParam);
void EnableOpenGL (HWND hWnd, HDC *hDC, HGLRC *hRC);
void DisableOpenGL (HWND hWnd, HDC hDC, HGLRC hRC);
/**************************
* WinMain
*
**************************/
int WINAPI WinMain (HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int iCmdShow)
{
WNDCLASS wc;
HWND hWnd;
HDC hDC;
HGLRC hRC;
MSG msg;
BOOL bQuit = FALSE;
float theta = 0.0f;
/* register window class */
wc.style = CS_OWNDC;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon (NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor (NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH) GetStockObject (BLACK_BRUSH);
wc.lpszMenuName = NULL;
wc.lpszClassName = "GLSample";
RegisterClass (&wc);
/* create main window */
hWnd = CreateWindow (
"GLSample", "OpenGL Sample",
WS_CAPTION | WS_POPUPWINDOW | WS_VISIBLE,
0, 0, 256, 256,
NULL, NULL, hInstance, NULL);
/* enable OpenGL for the window */
EnableOpenGL (hWnd, &hDC, &hRC);
/* program main loop */
while (!bQuit)
{
/* check for messages */
if (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
{
/* handle or dispatch messages */
if (msg.message == WM_QUIT)
{
bQuit = TRUE;
}
else
{
TranslateMessage (&msg);
DispatchMessage (&msg);
}
}
else
{
/* OpenGL animation code goes here */
glClearColor (0.0f, 0.0f, 0.0f, 0.0f);
glClear (GL_COLOR_BUFFER_BIT);
glPushMatrix ();
glRotatef (theta, 0.0f, 0.0f, 1.0f);
glBegin (GL_TRIANGLES);
glColor3f (1.0f, 0.0f, 0.0f); glVertex2f (0.0f, 1.0f);
glColor3f (0.0f, 1.0f, 0.0f); glVertex2f (0.87f, -0.5f);
glColor3f (0.0f, 0.0f, 1.0f); glVertex2f (-0.87f, -0.5f);
glEnd ();
glPopMatrix ();
SwapBuffers (hDC);
theta += 1.0f;
Sleep (1);
}
}
/* shutdown OpenGL */
DisableOpenGL (hWnd, hDC, hRC);
/* destroy the window explicitly */
DestroyWindow (hWnd);
return msg.wParam;
}
/********************
* Window Procedure
*
********************/
LRESULT CALLBACK WndProc (HWND hWnd, UINT message,
WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CREATE:
return 0;
case WM_CLOSE:
PostQuitMessage (0);
return 0;
case WM_DESTROY:
return 0;
case WM_KEYDOWN:
switch (wParam)
{
case VK_ESCAPE:
PostQuitMessage(0);
return 0;
}
return 0;
default:
return DefWindowProc (hWnd, message, wParam, lParam);
}
}
/*******************
* Enable OpenGL
*
*******************/
void EnableOpenGL (HWND hWnd, HDC *hDC, HGLRC *hRC)
{
PIXELFORMATDESCRIPTOR pfd;
int iFormat;
/* get the device context (DC) */
*hDC = GetDC (hWnd);
/* set the pixel format for the DC */
ZeroMemory (&pfd, sizeof (pfd));
pfd.nSize = sizeof (pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW |
PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 24;
pfd.cDepthBits = 16;
pfd.iLayerType = PFD_MAIN_PLANE;
iFormat = ChoosePixelFormat (*hDC, &pfd);
SetPixelFormat (*hDC, iFormat, &pfd);
/* create and enable the render context (RC) */
*hRC = wglCreateContext( *hDC );
wglMakeCurrent( *hDC, *hRC );
}
/******************
* Disable OpenGL
*
******************/
void DisableOpenGL (HWND hWnd, HDC hDC, HGLRC hRC)
{
wglMakeCurrent (NULL, NULL);
wglDeleteContext (hRC);
ReleaseDC (hWnd, hDC);
}
|
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/client/lib/qr.h"
#include "tensorflow/compiler/xla/array2d.h"
#include "tensorflow/compiler/xla/array3d.h"
#include "tensorflow/compiler/xla/client/lib/constants.h"
#include "tensorflow/compiler/xla/client/lib/matrix.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/compiler/xla/literal.h"
#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/compiler/xla/test.h"
#include "tensorflow/compiler/xla/tests/client_library_test_base.h"
#include "tensorflow/compiler/xla/tests/literal_test_util.h"
#include "tensorflow/compiler/xla/tests/test_macros.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/tensor_float_32_utils.h"
namespace {
using QrTest = xla::ClientLibraryTestBase;
XLA_TEST_F(QrTest, Simple) {
// Test fails with TensorFloat-32 enabled
tensorflow::enable_tensor_float_32_execution(false);
xla::Array2D<float> data({
{4, 6, 8, 10},
{6, 45, 54, 63},
{8, 54, 146, 166},
{10, 63, 166, 310},
});
for (bool full_matrices : {false, true}) {
for (xla::int64 m : {3, 4}) {
for (xla::int64 n : {3, 4}) {
xla::XlaBuilder builder(TestName());
xla::XlaOp a, q, r;
xla::Array<float> a_vals = data.Slice({0, 0}, {m, n});
auto a_data = CreateParameter<float>(a_vals, 0, "a", &builder, &a);
xla::QrExplicit(a, full_matrices, q, r);
// Verifies that the decomposition composes back to the original matrix.
//
// This isn't a terribly demanding test, (e.g., we should verify that Q
// is orthonormal and R is upper-triangular) but it's awkward to write
// such tests without more linear algebra libraries. It's easier to test
// the numerics from Python, anyway, where we have access to numpy and
// scipy.
xla::BatchDot(q, r, xla::PrecisionConfig::HIGHEST);
TF_ASSERT_OK_AND_ASSIGN(xla::Shape q_shape, builder.GetShape(q));
TF_ASSERT_OK_AND_ASSIGN(xla::Shape r_shape, builder.GetShape(r));
EXPECT_EQ(q_shape,
xla::ShapeUtil::MakeShape(
xla::F32, {m, full_matrices ? m : std::min(m, n)}));
EXPECT_EQ(r_shape,
xla::ShapeUtil::MakeShape(
xla::F32, {full_matrices ? m : std::min(m, n), n}));
ComputeAndCompare<float>(&builder, a_vals, {a_data.get()},
xla::ErrorSpec(1e-4, 1e-4));
}
}
}
}
XLA_TEST_F(QrTest, ZeroDiagonal) {
// Test fails with TensorFloat-32 enabled
tensorflow::enable_tensor_float_32_execution(false);
xla::XlaBuilder builder(TestName());
xla::Array2D<float> a_vals({
{0, 1, 1},
{1, 0, 1},
{1, 1, 0},
});
xla::XlaOp a, q, r;
auto a_data = CreateR2Parameter<float>(a_vals, 0, "a", &builder, &a);
xla::QrExplicit(a, /*full_matrices=*/true, q, r);
// Verifies that the decomposition composes back to the original matrix.
//
// This isn't a terribly demanding test, (e.g., we should verify that Q is
// orthonormal and R is upper-triangular) but it's awkward to write such tests
// without more linear algebra libraries. It's easier to test the numerics
// from Python, anyway, where we have access to numpy and scipy.
xla::BatchDot(q, r, xla::PrecisionConfig::HIGHEST);
ComputeAndCompareR2<float>(&builder, a_vals, {a_data.get()},
xla::ErrorSpec(1e-4, 1e-4));
}
XLA_TEST_F(QrTest, SimpleBatched) {
// Test fails with TensorFloat-32 enabled
tensorflow::enable_tensor_float_32_execution(false);
xla::XlaBuilder builder(TestName());
xla::Array3D<float> a_vals({
{
{4, 6, 8, 10},
{6, 45, 54, 63},
{8, 54, 146, 166},
{10, 63, 166, 310},
},
{
{16, 24, 8, 12},
{24, 61, 82, 48},
{8, 82, 456, 106},
{12, 48, 106, 62},
},
});
xla::XlaOp a, q, r;
auto a_data = CreateR3Parameter<float>(a_vals, 0, "a", &builder, &a);
xla::QrExplicit(a, /*full_matrices=*/true, q, r);
xla::BatchDot(q, r, xla::PrecisionConfig::HIGHEST);
ComputeAndCompareR3<float>(&builder, a_vals, {a_data.get()},
xla::ErrorSpec(1e-4, 1e-4));
}
XLA_TEST_F(QrTest, SubnormalComplex) {
tensorflow::enable_tensor_float_32_execution(false);
// Verifies that we don't get NaNs in the case that the norm of a complex
// number would be denormal but its imaginary value is not exactly 0.
xla::Array2D<xla::complex64> a_vals({
{xla::complex64(4e-20, 5e-23), 6, 80},
{0, 45, 54},
{0, 54, 146},
});
xla::XlaBuilder builder(TestName());
xla::XlaOp a, q, r;
auto a_data = CreateParameter<xla::complex64>(a_vals, 0, "a", &builder, &a);
xla::QrExplicit(a, /*full_matrices=*/true, q, r);
xla::BatchDot(q, r, xla::PrecisionConfig::HIGHEST);
ComputeAndCompare<xla::complex64>(&builder, a_vals, {a_data.get()},
xla::ErrorSpec(1e-4, 1e-4));
}
} // namespace
|
// Boost config.hpp configuration header file ------------------------------//
// Copyright (c) 2001-2003 John Maddock
// Copyright (c) 2001 Darin Adler
// Copyright (c) 2001 Peter Dimov
// Copyright (c) 2002 Bill Kempf
// Copyright (c) 2002 Jens Maurer
// Copyright (c) 2002-2003 David Abrahams
// Copyright (c) 2003 Gennaro Prota
// Copyright (c) 2003 Eric Friedman
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/ for most recent version.
// Boost config.hpp policy and rationale documentation has been moved to
// http://www.boost.org/libs/config/
//
// This file is intended to be stable, and relatively unchanging.
// It should contain boilerplate code only - no compiler specific
// code unless it is unavoidable - no changes unless unavoidable.
#ifndef BOOST_CONFIG_SUFFIX_HPP
#define BOOST_CONFIG_SUFFIX_HPP
//
// look for long long by looking for the appropriate macros in <limits.h>.
// Note that we use limits.h rather than climits for maximal portability,
// remember that since these just declare a bunch of macros, there should be
// no namespace issues from this.
//
#if !defined(BOOST_HAS_LONG_LONG) \
&& !defined(BOOST_MSVC) && !defined(__BORLANDC__)
# include <limits.h>
# if (defined(ULLONG_MAX) || defined(ULONG_LONG_MAX) || defined(ULONGLONG_MAX))
# define BOOST_HAS_LONG_LONG
# endif
#endif
// GCC 3.x will clean up all of those nasty macro definitions that
// BOOST_NO_CTYPE_FUNCTIONS is intended to help work around, so undefine
// it under GCC 3.x.
#if defined(__GNUC__) && (__GNUC__ >= 3) && defined(BOOST_NO_CTYPE_FUNCTIONS)
# undef BOOST_NO_CTYPE_FUNCTIONS
#endif
//
// Assume any extensions are in namespace std:: unless stated otherwise:
//
# ifndef BOOST_STD_EXTENSION_NAMESPACE
# define BOOST_STD_EXTENSION_NAMESPACE std
# endif
//
// If cv-qualified specializations are not allowed, then neither are cv-void ones:
//
# if defined(BOOST_NO_CV_SPECIALIZATIONS) \
&& !defined(BOOST_NO_CV_VOID_SPECIALIZATIONS)
# define BOOST_NO_CV_VOID_SPECIALIZATIONS
# endif
//
// If there is no numeric_limits template, then it can't have any compile time
// constants either!
//
# if defined(BOOST_NO_LIMITS) \
&& !defined(BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS)
# define BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS
# define BOOST_NO_MS_INT64_NUMERIC_LIMITS
# define BOOST_NO_LONG_LONG_NUMERIC_LIMITS
# endif
//
// if there is no long long then there is no specialisation
// for numeric_limits<long long> either:
//
#if !defined(BOOST_HAS_LONG_LONG) && !defined(BOOST_NO_LONG_LONG_NUMERIC_LIMITS)
# define BOOST_NO_LONG_LONG_NUMERIC_LIMITS
#endif
//
// if there is no __int64 then there is no specialisation
// for numeric_limits<__int64> either:
//
#if !defined(BOOST_HAS_MS_INT64) && !defined(BOOST_NO_MS_INT64_NUMERIC_LIMITS)
# define BOOST_NO_MS_INT64_NUMERIC_LIMITS
#endif
//
// if member templates are supported then so is the
// VC6 subset of member templates:
//
# if !defined(BOOST_NO_MEMBER_TEMPLATES) \
&& !defined(BOOST_MSVC6_MEMBER_TEMPLATES)
# define BOOST_MSVC6_MEMBER_TEMPLATES
# endif
//
// Without partial specialization, can't test for partial specialisation bugs:
//
# if defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) \
&& !defined(BOOST_BCB_PARTIAL_SPECIALIZATION_BUG)
# define BOOST_BCB_PARTIAL_SPECIALIZATION_BUG
# endif
//
// Without partial specialization, we can't have array-type partial specialisations:
//
# if defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) \
&& !defined(BOOST_NO_ARRAY_TYPE_SPECIALIZATIONS)
# define BOOST_NO_ARRAY_TYPE_SPECIALIZATIONS
# endif
//
// Without partial specialization, std::iterator_traits can't work:
//
# if defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) \
&& !defined(BOOST_NO_STD_ITERATOR_TRAITS)
# define BOOST_NO_STD_ITERATOR_TRAITS
# endif
//
// Without partial specialization, partial
// specialization with default args won't work either:
//
# if defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) \
&& !defined(BOOST_NO_PARTIAL_SPECIALIZATION_IMPLICIT_DEFAULT_ARGS)
# define BOOST_NO_PARTIAL_SPECIALIZATION_IMPLICIT_DEFAULT_ARGS
# endif
//
// Without member template support, we can't have template constructors
// in the standard library either:
//
# if defined(BOOST_NO_MEMBER_TEMPLATES) \
&& !defined(BOOST_MSVC6_MEMBER_TEMPLATES) \
&& !defined(BOOST_NO_TEMPLATED_ITERATOR_CONSTRUCTORS)
# define BOOST_NO_TEMPLATED_ITERATOR_CONSTRUCTORS
# endif
//
// Without member template support, we can't have a conforming
// std::allocator template either:
//
# if defined(BOOST_NO_MEMBER_TEMPLATES) \
&& !defined(BOOST_MSVC6_MEMBER_TEMPLATES) \
&& !defined(BOOST_NO_STD_ALLOCATOR)
# define BOOST_NO_STD_ALLOCATOR
# endif
//
// without ADL support then using declarations will break ADL as well:
//
#if defined(BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP) && !defined(BOOST_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL)
# define BOOST_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL
#endif
//
// Without typeid support we have no dynamic RTTI either:
//
#if defined(BOOST_NO_TYPEID) && !defined(BOOST_NO_RTTI)
# define BOOST_NO_RTTI
#endif
//
// If we have a standard allocator, then we have a partial one as well:
//
#if !defined(BOOST_NO_STD_ALLOCATOR)
# define BOOST_HAS_PARTIAL_STD_ALLOCATOR
#endif
//
// We can't have a working std::use_facet if there is no std::locale:
//
# if defined(BOOST_NO_STD_LOCALE) && !defined(BOOST_NO_STD_USE_FACET)
# define BOOST_NO_STD_USE_FACET
# endif
//
// We can't have a std::messages facet if there is no std::locale:
//
# if defined(BOOST_NO_STD_LOCALE) && !defined(BOOST_NO_STD_MESSAGES)
# define BOOST_NO_STD_MESSAGES
# endif
//
// We can't have a working std::wstreambuf if there is no std::locale:
//
# if defined(BOOST_NO_STD_LOCALE) && !defined(BOOST_NO_STD_WSTREAMBUF)
# define BOOST_NO_STD_WSTREAMBUF
# endif
//
// We can't have a <cwctype> if there is no <cwchar>:
//
# if defined(BOOST_NO_CWCHAR) && !defined(BOOST_NO_CWCTYPE)
# define BOOST_NO_CWCTYPE
# endif
//
// We can't have a swprintf if there is no <cwchar>:
//
# if defined(BOOST_NO_CWCHAR) && !defined(BOOST_NO_SWPRINTF)
# define BOOST_NO_SWPRINTF
# endif
//
// If Win32 support is turned off, then we must turn off
// threading support also, unless there is some other
// thread API enabled:
//
#if defined(BOOST_DISABLE_WIN32) && defined(_WIN32) \
&& !defined(BOOST_DISABLE_THREADS) && !defined(BOOST_HAS_PTHREADS)
# define BOOST_DISABLE_THREADS
#endif
//
// Turn on threading support if the compiler thinks that it's in
// multithreaded mode. We put this here because there are only a
// limited number of macros that identify this (if there's any missing
// from here then add to the appropriate compiler section):
//
#if (defined(__MT__) || defined(_MT) || defined(_REENTRANT) \
|| defined(_PTHREADS)) && !defined(BOOST_HAS_THREADS)
# define BOOST_HAS_THREADS
#endif
//
// Turn threading support off if BOOST_DISABLE_THREADS is defined:
//
#if defined(BOOST_DISABLE_THREADS) && defined(BOOST_HAS_THREADS)
# undef BOOST_HAS_THREADS
#endif
//
// Turn threading support off if we don't recognise the threading API:
//
#if defined(BOOST_HAS_THREADS) && !defined(BOOST_HAS_PTHREADS)\
&& !defined(BOOST_HAS_WINTHREADS) && !defined(BOOST_HAS_BETHREADS)\
&& !defined(BOOST_HAS_MPTASKS)
# undef BOOST_HAS_THREADS
#endif
//
// Turn threading detail macros off if we don't (want to) use threading
//
#ifndef BOOST_HAS_THREADS
# undef BOOST_HAS_PTHREADS
# undef BOOST_HAS_PTHREAD_MUTEXATTR_SETTYPE
# undef BOOST_HAS_PTHREAD_YIELD
# undef BOOST_HAS_PTHREAD_DELAY_NP
# undef BOOST_HAS_WINTHREADS
# undef BOOST_HAS_BETHREADS
# undef BOOST_HAS_MPTASKS
#endif
//
// If the compiler claims to be C99 conformant, then it had better
// have a <stdint.h>:
//
# if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901)
# define BOOST_HAS_STDINT_H
# ifndef BOOST_HAS_LOG1P
# define BOOST_HAS_LOG1P
# endif
# ifndef BOOST_HAS_EXPM1
# define BOOST_HAS_EXPM1
# endif
# endif
//
// Define BOOST_NO_SLIST and BOOST_NO_HASH if required.
// Note that this is for backwards compatibility only.
//
# if !defined(BOOST_HAS_SLIST) && !defined(BOOST_NO_SLIST)
# define BOOST_NO_SLIST
# endif
# if !defined(BOOST_HAS_HASH) && !defined(BOOST_NO_HASH)
# define BOOST_NO_HASH
# endif
//
// Set BOOST_SLIST_HEADER if not set already:
//
#if defined(BOOST_HAS_SLIST) && !defined(BOOST_SLIST_HEADER)
# define BOOST_SLIST_HEADER <slist>
#endif
//
// Set BOOST_HASH_SET_HEADER if not set already:
//
#if defined(BOOST_HAS_HASH) && !defined(BOOST_HASH_SET_HEADER)
# define BOOST_HASH_SET_HEADER <hash_set>
#endif
//
// Set BOOST_HASH_MAP_HEADER if not set already:
//
#if defined(BOOST_HAS_HASH) && !defined(BOOST_HASH_MAP_HEADER)
# define BOOST_HASH_MAP_HEADER <hash_map>
#endif
// BOOST_HAS_ABI_HEADERS
// This macro gets set if we have headers that fix the ABI,
// and prevent ODR violations when linking to external libraries:
#if defined(BOOST_ABI_PREFIX) && defined(BOOST_ABI_SUFFIX) && !defined(BOOST_HAS_ABI_HEADERS)
# define BOOST_HAS_ABI_HEADERS
#endif
#if defined(BOOST_HAS_ABI_HEADERS) && defined(BOOST_DISABLE_ABI_HEADERS)
# undef BOOST_HAS_ABI_HEADERS
#endif
// BOOST_NO_STDC_NAMESPACE workaround --------------------------------------//
// Because std::size_t usage is so common, even in boost headers which do not
// otherwise use the C library, the <cstddef> workaround is included here so
// that ugly workaround code need not appear in many other boost headers.
// NOTE WELL: This is a workaround for non-conforming compilers; <cstddef>
// must still be #included in the usual places so that <cstddef> inclusion
// works as expected with standard conforming compilers. The resulting
// double inclusion of <cstddef> is harmless.
# ifdef BOOST_NO_STDC_NAMESPACE
# include <cstddef>
namespace std { using ::ptrdiff_t; using ::size_t; }
# endif
// Workaround for the unfortunate min/max macros defined by some platform headers
#define BOOST_PREVENT_MACRO_SUBSTITUTION
#ifndef BOOST_USING_STD_MIN
# define BOOST_USING_STD_MIN() using std::min
#endif
#ifndef BOOST_USING_STD_MAX
# define BOOST_USING_STD_MAX() using std::max
#endif
// BOOST_NO_STD_MIN_MAX workaround -----------------------------------------//
# ifdef BOOST_NO_STD_MIN_MAX
namespace std {
template <class _Tp>
inline const _Tp& min BOOST_PREVENT_MACRO_SUBSTITUTION (const _Tp& __a, const _Tp& __b) {
return __b < __a ? __b : __a;
}
template <class _Tp>
inline const _Tp& max BOOST_PREVENT_MACRO_SUBSTITUTION (const _Tp& __a, const _Tp& __b) {
return __a < __b ? __b : __a;
}
}
# endif
// BOOST_STATIC_CONSTANT workaround --------------------------------------- //
// On compilers which don't allow in-class initialization of static integral
// constant members, we must use enums as a workaround if we want the constants
// to be available at compile-time. This macro gives us a convenient way to
// declare such constants.
# ifdef BOOST_NO_INCLASS_MEMBER_INITIALIZATION
# define BOOST_STATIC_CONSTANT(type, assignment) enum { assignment }
# else
# define BOOST_STATIC_CONSTANT(type, assignment) static const type assignment
# endif
// BOOST_USE_FACET / HAS_FACET workaround ----------------------------------//
// When the standard library does not have a conforming std::use_facet there
// are various workarounds available, but they differ from library to library.
// The same problem occurs with has_facet.
// These macros provide a consistent way to access a locale's facets.
// Usage:
// replace
// std::use_facet<Type>(loc);
// with
// BOOST_USE_FACET(Type, loc);
// Note do not add a std:: prefix to the front of BOOST_USE_FACET!
// Use for BOOST_HAS_FACET is analogous.
#if defined(BOOST_NO_STD_USE_FACET)
# ifdef BOOST_HAS_TWO_ARG_USE_FACET
# define BOOST_USE_FACET(Type, loc) std::use_facet(loc, static_cast<Type*>(0))
# define BOOST_HAS_FACET(Type, loc) std::has_facet(loc, static_cast<Type*>(0))
# elif defined(BOOST_HAS_MACRO_USE_FACET)
# define BOOST_USE_FACET(Type, loc) std::_USE(loc, Type)
# define BOOST_HAS_FACET(Type, loc) std::_HAS(loc, Type)
# elif defined(BOOST_HAS_STLP_USE_FACET)
# define BOOST_USE_FACET(Type, loc) (*std::_Use_facet<Type >(loc))
# define BOOST_HAS_FACET(Type, loc) std::has_facet< Type >(loc)
# endif
#else
# define BOOST_USE_FACET(Type, loc) std::use_facet< Type >(loc)
# define BOOST_HAS_FACET(Type, loc) std::has_facet< Type >(loc)
#endif
// BOOST_NESTED_TEMPLATE workaround ------------------------------------------//
// Member templates are supported by some compilers even though they can't use
// the A::template member<U> syntax, as a workaround replace:
//
// typedef typename A::template rebind<U> binder;
//
// with:
//
// typedef typename A::BOOST_NESTED_TEMPLATE rebind<U> binder;
#ifndef BOOST_NO_MEMBER_TEMPLATE_KEYWORD
# define BOOST_NESTED_TEMPLATE template
#else
# define BOOST_NESTED_TEMPLATE
#endif
// BOOST_UNREACHABLE_RETURN(x) workaround -------------------------------------//
// Normally evaluates to nothing, unless BOOST_NO_UNREACHABLE_RETURN_DETECTION
// is defined, in which case it evaluates to return x; Use when you have a return
// statement that can never be reached.
#ifdef BOOST_NO_UNREACHABLE_RETURN_DETECTION
# define BOOST_UNREACHABLE_RETURN(x) return x;
#else
# define BOOST_UNREACHABLE_RETURN(x)
#endif
// BOOST_DEDUCED_TYPENAME workaround ------------------------------------------//
//
// Some compilers don't support the use of `typename' for dependent
// types in deduced contexts, e.g.
//
// template <class T> void f(T, typename T::type);
// ^^^^^^^^
// Replace these declarations with:
//
// template <class T> void f(T, BOOST_DEDUCED_TYPENAME T::type);
#ifndef BOOST_NO_DEDUCED_TYPENAME
# define BOOST_DEDUCED_TYPENAME typename
#else
# define BOOST_DEDUCED_TYPENAME
#endif
#ifndef BOOST_NO_TYPENAME_WITH_CTOR
# define BOOST_CTOR_TYPENAME typename
#else
# define BOOST_CTOR_TYPENAME
#endif
// long long workaround ------------------------------------------//
// On gcc (and maybe other compilers?) long long is alway supported
// but it's use may generate either warnings (with -ansi), or errors
// (with -pedantic -ansi) unless it's use is prefixed by __extension__
//
#if defined(BOOST_HAS_LONG_LONG)
namespace boost{
# ifdef __GNUC__
__extension__ typedef long long long_long_type;
__extension__ typedef unsigned long long ulong_long_type;
# else
typedef long long long_long_type;
typedef unsigned long long ulong_long_type;
# endif
}
#endif
// BOOST_[APPEND_]EXPLICIT_TEMPLATE_[NON_]TYPE macros --------------------------//
//
// Some compilers have problems with function templates whose template
// parameters don't appear in the function parameter list (basically
// they just link one instantiation of the template in the final
// executable). These macros provide a uniform way to cope with the
// problem with no effects on the calling syntax.
// Example:
//
// #include <iostream>
// #include <ostream>
// #include <typeinfo>
//
// template <int n>
// void f() { std::cout << n << ' '; }
//
// template <typename T>
// void g() { std::cout << typeid(T).name() << ' '; }
//
// int main() {
// f<1>();
// f<2>();
//
// g<int>();
// g<double>();
// }
//
// With VC++ 6.0 the output is:
//
// 2 2 double double
//
// To fix it, write
//
// template <int n>
// void f(BOOST_EXPLICIT_TEMPLATE_NON_TYPE(int, n)) { ... }
//
// template <typename T>
// void g(BOOST_EXPLICIT_TEMPLATE_TYPE(T)) { ... }
//
#if defined BOOST_NO_EXPLICIT_FUNCTION_TEMPLATE_ARGUMENTS
# include "boost/type.hpp"
# include "boost/non_type.hpp"
# define BOOST_EXPLICIT_TEMPLATE_TYPE(t) boost::type<t>* = 0
# define BOOST_EXPLICIT_TEMPLATE_TYPE_SPEC(t) boost::type<t>*
# define BOOST_EXPLICIT_TEMPLATE_NON_TYPE(t, v) boost::non_type<t, v>* = 0
# define BOOST_EXPLICIT_TEMPLATE_NON_TYPE_SPEC(t, v) boost::non_type<t, v>*
# define BOOST_APPEND_EXPLICIT_TEMPLATE_TYPE(t) \
, BOOST_EXPLICIT_TEMPLATE_TYPE(t)
# define BOOST_APPEND_EXPLICIT_TEMPLATE_TYPE_SPEC(t) \
, BOOST_EXPLICIT_TEMPLATE_TYPE_SPEC(t)
# define BOOST_APPEND_EXPLICIT_TEMPLATE_NON_TYPE(t, v) \
, BOOST_EXPLICIT_TEMPLATE_NON_TYPE(t, v)
# define BOOST_APPEND_EXPLICIT_TEMPLATE_NON_TYPE_SPEC(t, v) \
, BOOST_EXPLICIT_TEMPLATE_NON_TYPE_SPEC(t, v)
#else
// no workaround needed: expand to nothing
# define BOOST_EXPLICIT_TEMPLATE_TYPE(t)
# define BOOST_EXPLICIT_TEMPLATE_TYPE_SPEC(t)
# define BOOST_EXPLICIT_TEMPLATE_NON_TYPE(t, v)
# define BOOST_EXPLICIT_TEMPLATE_NON_TYPE_SPEC(t, v)
# define BOOST_APPEND_EXPLICIT_TEMPLATE_TYPE(t)
# define BOOST_APPEND_EXPLICIT_TEMPLATE_TYPE_SPEC(t)
# define BOOST_APPEND_EXPLICIT_TEMPLATE_NON_TYPE(t, v)
# define BOOST_APPEND_EXPLICIT_TEMPLATE_NON_TYPE_SPEC(t, v)
#endif // defined BOOST_NO_EXPLICIT_FUNCTION_TEMPLATE_ARGUMENTS
// ---------------------------------------------------------------------------//
//
// Helper macro BOOST_STRINGIZE:
// Converts the parameter X to a string after macro replacement
// on X has been performed.
//
#define BOOST_STRINGIZE(X) BOOST_DO_STRINGIZE(X)
#define BOOST_DO_STRINGIZE(X) #X
//
// Helper macro BOOST_JOIN:
// The following piece of macro magic joins the two
// arguments together, even when one of the arguments is
// itself a macro (see 16.3.1 in C++ standard). The key
// is that macro expansion of macro arguments does not
// occur in BOOST_DO_JOIN2 but does in BOOST_DO_JOIN.
//
#define BOOST_JOIN( X, Y ) BOOST_DO_JOIN( X, Y )
#define BOOST_DO_JOIN( X, Y ) BOOST_DO_JOIN2(X,Y)
#define BOOST_DO_JOIN2( X, Y ) X##Y
//
// Set some default values for compiler/library/platform names.
// These are for debugging config setup only:
//
# ifndef BOOST_COMPILER
# define BOOST_COMPILER "Unknown ISO C++ Compiler"
# endif
# ifndef BOOST_STDLIB
# define BOOST_STDLIB "Unknown ISO standard library"
# endif
# ifndef BOOST_PLATFORM
# if defined(unix) || defined(__unix) || defined(_XOPEN_SOURCE) \
|| defined(_POSIX_SOURCE)
# define BOOST_PLATFORM "Generic Unix"
# else
# define BOOST_PLATFORM "Unknown"
# endif
# endif
#endif
|
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/cloudaudit/v20190319/model/InquireAuditCreditResponse.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Cloudaudit::V20190319::Model;
using namespace std;
InquireAuditCreditResponse::InquireAuditCreditResponse() :
m_auditAmountHasBeenSet(false)
{
}
CoreInternalOutcome InquireAuditCreditResponse::Deserialize(const string &payload)
{
rapidjson::Document d;
d.Parse(payload.c_str());
if (d.HasParseError() || !d.IsObject())
{
return CoreInternalOutcome(Core::Error("response not json format"));
}
if (!d.HasMember("Response") || !d["Response"].IsObject())
{
return CoreInternalOutcome(Core::Error("response `Response` is null or not object"));
}
rapidjson::Value &rsp = d["Response"];
if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.RequestId` is null or not string"));
}
string requestId(rsp["RequestId"].GetString());
SetRequestId(requestId);
if (rsp.HasMember("Error"))
{
if (!rsp["Error"].IsObject() ||
!rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() ||
!rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.Error` format error").SetRequestId(requestId));
}
string errorCode(rsp["Error"]["Code"].GetString());
string errorMsg(rsp["Error"]["Message"].GetString());
return CoreInternalOutcome(Core::Error(errorCode, errorMsg).SetRequestId(requestId));
}
if (rsp.HasMember("AuditAmount") && !rsp["AuditAmount"].IsNull())
{
if (!rsp["AuditAmount"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `AuditAmount` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_auditAmount = rsp["AuditAmount"].GetInt64();
m_auditAmountHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
string InquireAuditCreditResponse::ToJsonString() const
{
rapidjson::Document value;
value.SetObject();
rapidjson::Document::AllocatorType& allocator = value.GetAllocator();
if (m_auditAmountHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "AuditAmount";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_auditAmount, allocator);
}
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RequestId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value().SetString(GetRequestId().c_str(), allocator), allocator);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
value.Accept(writer);
return buffer.GetString();
}
int64_t InquireAuditCreditResponse::GetAuditAmount() const
{
return m_auditAmount;
}
bool InquireAuditCreditResponse::AuditAmountHasBeenSet() const
{
return m_auditAmountHasBeenSet;
}
|
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/ec2/model/AttachVpnGatewayResponse.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/logging/LogMacros.h>
#include <utility>
using namespace Aws::EC2::Model;
using namespace Aws::Utils::Xml;
using namespace Aws::Utils::Logging;
using namespace Aws::Utils;
using namespace Aws;
AttachVpnGatewayResponse::AttachVpnGatewayResponse()
{
}
AttachVpnGatewayResponse::AttachVpnGatewayResponse(const Aws::AmazonWebServiceResult<XmlDocument>& result)
{
*this = result;
}
AttachVpnGatewayResponse& AttachVpnGatewayResponse::operator =(const Aws::AmazonWebServiceResult<XmlDocument>& result)
{
const XmlDocument& xmlDocument = result.GetPayload();
XmlNode rootNode = xmlDocument.GetRootElement();
XmlNode resultNode = rootNode;
if (!rootNode.IsNull() && (rootNode.GetName() != "AttachVpnGatewayResponse"))
{
resultNode = rootNode.FirstChild("AttachVpnGatewayResponse");
}
if(!resultNode.IsNull())
{
XmlNode vpcAttachmentNode = resultNode.FirstChild("attachment");
if(!vpcAttachmentNode.IsNull())
{
m_vpcAttachment = vpcAttachmentNode;
}
}
if (!rootNode.IsNull()) {
XmlNode requestIdNode = rootNode.FirstChild("requestId");
if (!requestIdNode.IsNull())
{
m_responseMetadata.SetRequestId(StringUtils::Trim(requestIdNode.GetText().c_str()));
}
AWS_LOGSTREAM_DEBUG("Aws::EC2::Model::AttachVpnGatewayResponse", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() );
}
return *this;
}
|
/****************************************************************************
*
* Copyright (C) 2013 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* Driver for the PX4 audio alarm port, /dev/tone_alarm.
*
* The tone_alarm driver supports a set of predefined "alarm"
* tunes and one user-supplied tune.
*
* The TONE_SET_ALARM ioctl can be used to select a predefined
* alarm tune, from 1 - <TBD>. Selecting tune zero silences
* the alarm.
*
* Tunes follow the syntax of the Microsoft GWBasic/QBasic PLAY
* statement, with some exceptions and extensions.
*
* From Wikibooks:
*
* PLAY "[string expression]"
*
* Used to play notes and a score ... The tones are indicated by letters A through G.
* Accidentals are indicated with a "+" or "#" (for sharp) or "-" (for flat)
* immediately after the note letter. See this example:
*
* PLAY "C C# C C#"
*
* Whitespaces are ignored inside the string expression. There are also codes that
* set the duration, octave and tempo. They are all case-insensitive. PLAY executes
* the commands or notes the order in which they appear in the string. Any indicators
* that change the properties are effective for the notes following that indicator.
*
* Ln Sets the duration (length) of the notes. The variable n does not indicate an actual duration
* amount but rather a note type; L1 - whole note, L2 - half note, L4 - quarter note, etc.
* (L8, L16, L32, L64, ...). By default, n = 4.
* For triplets and quintets, use L3, L6, L12, ... and L5, L10, L20, ... series respectively.
* The shorthand notation of length is also provided for a note. For example, "L4 CDE L8 FG L4 AB"
* can be shortened to "L4 CDE F8G8 AB". F and G play as eighth notes while others play as quarter notes.
* On Sets the current octave. Valid values for n are 0 through 6. An octave begins with C and ends with B.
* Remember that C- is equivalent to B.
* < > Changes the current octave respectively down or up one level.
* Nn Plays a specified note in the seven-octave range. Valid values are from 0 to 84. (0 is a pause.)
* Cannot use with sharp and flat. Cannot use with the shorthand notation neither.
* MN Stand for Music Normal. Note duration is 7/8ths of the length indicated by Ln. It is the default mode.
* ML Stand for Music Legato. Note duration is full length of that indicated by Ln.
* MS Stand for Music Staccato. Note duration is 3/4ths of the length indicated by Ln.
* Pn Causes a silence (pause) for the length of note indicated (same as Ln).
* Tn Sets the number of "L4"s per minute (tempo). Valid values are from 32 to 255. The default value is T120.
* . When placed after a note, it causes the duration of the note to be 3/2 of the set duration.
* This is how to get "dotted" notes. "L4 C#." would play C sharp as a dotted quarter note.
* It can be used for a pause as well.
*
* Extensions/variations:
*
* MB MF The MF command causes the tune to play once and then stop. The MB command causes the
* tune to repeat when it ends.
*
*/
#include <nuttx/config.h>
#include <debug.h>
#include <drivers/device/device.h>
#include <drivers/drv_tone_alarm.h>
#include <sys/types.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <math.h>
#include <ctype.h>
#include <board_config.h>
#include <drivers/drv_hrt.h>
#include <arch/stm32/chip.h>
#include <up_internal.h>
#include <up_arch.h>
#include <stm32.h>
#include <stm32_gpio.h>
#include <stm32_tim.h>
#include <systemlib/err.h>
/* Tone alarm configuration */
#if TONE_ALARM_TIMER == 2
# define TONE_ALARM_BASE STM32_TIM2_BASE
# define TONE_ALARM_CLOCK STM32_APB1_TIM2_CLKIN
# define TONE_ALARM_CLOCK_ENABLE RCC_APB1ENR_TIM2EN
# ifdef CONFIG_STM32_TIM2
# error Must not set CONFIG_STM32_TIM2 when TONE_ALARM_TIMER is 2
# endif
#elif TONE_ALARM_TIMER == 3
# define TONE_ALARM_BASE STM32_TIM3_BASE
# define TONE_ALARM_CLOCK STM32_APB1_TIM3_CLKIN
# define TONE_ALARM_CLOCK_ENABLE RCC_APB1ENR_TIM3EN
# ifdef CONFIG_STM32_TIM3
# error Must not set CONFIG_STM32_TIM3 when TONE_ALARM_TIMER is 3
# endif
#elif TONE_ALARM_TIMER == 4
# define TONE_ALARM_BASE STM32_TIM4_BASE
# define TONE_ALARM_CLOCK STM32_APB1_TIM4_CLKIN
# define TONE_ALARM_CLOCK_ENABLE RCC_APB1ENR_TIM4EN
# ifdef CONFIG_STM32_TIM4
# error Must not set CONFIG_STM32_TIM4 when TONE_ALARM_TIMER is 4
# endif
#elif TONE_ALARM_TIMER == 5
# define TONE_ALARM_BASE STM32_TIM5_BASE
# define TONE_ALARM_CLOCK STM32_APB1_TIM5_CLKIN
# define TONE_ALARM_CLOCK_ENABLE RCC_APB1ENR_TIM5EN
# ifdef CONFIG_STM32_TIM5
# error Must not set CONFIG_STM32_TIM5 when TONE_ALARM_TIMER is 5
# endif
#elif TONE_ALARM_TIMER == 9
# define TONE_ALARM_BASE STM32_TIM9_BASE
#if defined(CONFIG_ARCH_BOARD_F4BY)
# define TONE_ALARM_CLOCK STM32_APB2_TIM9_CLKIN
# define TONE_ALARM_CLOCK_ENABLE RCC_APB2ENR_TIM9EN
#else
# define TONE_ALARM_CLOCK STM32_APB1_TIM9_CLKIN
# define TONE_ALARM_CLOCK_ENABLE RCC_APB1ENR_TIM9EN
#endif
# ifdef CONFIG_STM32_TIM9
# error Must not set CONFIG_STM32_TIM9 when TONE_ALARM_TIMER is 9
# endif
#elif TONE_ALARM_TIMER == 10
# define TONE_ALARM_BASE STM32_TIM10_BASE
# define TONE_ALARM_CLOCK STM32_APB1_TIM10_CLKIN
# define TONE_ALARM_CLOCK_ENABLE RCC_APB1ENR_TIM10EN
# ifdef CONFIG_STM32_TIM10
# error Must not set CONFIG_STM32_TIM10 when TONE_ALARM_TIMER is 10
# endif
#elif TONE_ALARM_TIMER == 11
# define TONE_ALARM_BASE STM32_TIM11_BASE
# define TONE_ALARM_CLOCK STM32_APB1_TIM11_CLKIN
# define TONE_ALARM_CLOCK_ENABLE RCC_APB1ENR_TIM11EN
# ifdef CONFIG_STM32_TIM11
# error Must not set CONFIG_STM32_TIM11 when TONE_ALARM_TIMER is 11
# endif
#else
# error Must set TONE_ALARM_TIMER to a generic timer in order to use this driver.
#endif
#if TONE_ALARM_CHANNEL == 1
# define TONE_CCMR1 (3 << 4)
# define TONE_CCMR2 0
# define TONE_CCER (1 << 0)
# define TONE_rCCR rCCR1
#elif TONE_ALARM_CHANNEL == 2
# define TONE_CCMR1 (3 << 12)
# define TONE_CCMR2 0
# define TONE_CCER (1 << 4)
# define TONE_rCCR rCCR2
#elif TONE_ALARM_CHANNEL == 3
# define TONE_CCMR1 0
# define TONE_CCMR2 (3 << 4)
# define TONE_CCER (1 << 8)
# define TONE_rCCR rCCR3
#elif TONE_ALARM_CHANNEL == 4
# define TONE_CCMR1 0
# define TONE_CCMR2 (3 << 12)
# define TONE_CCER (1 << 12)
# define TONE_rCCR rCCR4
#else
# error Must set TONE_ALARM_CHANNEL to a value between 1 and 4 to use this driver.
#endif
/*
* Timer register accessors
*/
#define REG(_reg) (*(volatile uint32_t *)(TONE_ALARM_BASE + _reg))
#define rCR1 REG(STM32_GTIM_CR1_OFFSET)
#define rCR2 REG(STM32_GTIM_CR2_OFFSET)
#define rSMCR REG(STM32_GTIM_SMCR_OFFSET)
#define rDIER REG(STM32_GTIM_DIER_OFFSET)
#define rSR REG(STM32_GTIM_SR_OFFSET)
#define rEGR REG(STM32_GTIM_EGR_OFFSET)
#define rCCMR1 REG(STM32_GTIM_CCMR1_OFFSET)
#define rCCMR2 REG(STM32_GTIM_CCMR2_OFFSET)
#define rCCER REG(STM32_GTIM_CCER_OFFSET)
#define rCNT REG(STM32_GTIM_CNT_OFFSET)
#define rPSC REG(STM32_GTIM_PSC_OFFSET)
#define rARR REG(STM32_GTIM_ARR_OFFSET)
#define rCCR1 REG(STM32_GTIM_CCR1_OFFSET)
#define rCCR2 REG(STM32_GTIM_CCR2_OFFSET)
#define rCCR3 REG(STM32_GTIM_CCR3_OFFSET)
#define rCCR4 REG(STM32_GTIM_CCR4_OFFSET)
#define rDCR REG(STM32_GTIM_DCR_OFFSET)
#define rDMAR REG(STM32_GTIM_DMAR_OFFSET)
class ToneAlarm : public device::CDev
{
public:
ToneAlarm();
~ToneAlarm();
virtual int init();
virtual int ioctl(file *filp, int cmd, unsigned long arg);
virtual ssize_t write(file *filp, const char *buffer, size_t len);
inline const char *name(int tune) {
return _tune_names[tune];
}
private:
static const unsigned _tune_max = 1024 * 8; // be reasonable about user tunes
const char * _default_tunes[TONE_NUMBER_OF_TUNES];
const char * _tune_names[TONE_NUMBER_OF_TUNES];
static const uint8_t _note_tab[];
unsigned _default_tune_number; // number of currently playing default tune (0 for none)
const char *_user_tune;
const char *_tune; // current tune string
const char *_next; // next note in the string
unsigned _tempo;
unsigned _note_length;
enum { MODE_NORMAL, MODE_LEGATO, MODE_STACCATO} _note_mode;
unsigned _octave;
unsigned _silence_length; // if nonzero, silence before next note
bool _repeat; // if true, tune restarts at end
hrt_call _note_call; // HRT callout for note completion
// Convert a note value in the range C1 to B7 into a divisor for
// the configured timer's clock.
//
unsigned note_to_divisor(unsigned note);
// Calculate the duration in microseconds of play and silence for a
// note given the current tempo, length and mode and the number of
// dots following in the play string.
//
unsigned note_duration(unsigned &silence, unsigned note_length, unsigned dots);
// Calculate the duration in microseconds of a rest corresponding to
// a given note length.
//
unsigned rest_duration(unsigned rest_length, unsigned dots);
// Start playing the note
//
void start_note(unsigned note);
// Stop playing the current note and make the player 'safe'
//
void stop_note();
// Start playing the tune
//
void start_tune(const char *tune);
// Parse the next note out of the string and play it
//
void next_note();
// Find the next character in the string, discard any whitespace and
// return the canonical (uppercase) version.
//
int next_char();
// Extract a number from the string, consuming all the digit characters.
//
unsigned next_number();
// Consume dot characters from the string, returning the number consumed.
//
unsigned next_dots();
// hrt_call trampoline for next_note
//
static void next_trampoline(void *arg);
};
// semitone offsets from C for the characters 'A'-'G'
const uint8_t ToneAlarm::_note_tab[] = {9, 11, 0, 2, 4, 5, 7};
/*
* Driver 'main' command.
*/
extern "C" __EXPORT int tone_alarm_main(int argc, char *argv[]);
ToneAlarm::ToneAlarm() :
CDev("tone_alarm", TONEALARM_DEVICE_PATH),
_default_tune_number(0),
_user_tune(nullptr),
_tune(nullptr),
_next(nullptr)
{
// enable debug() calls
//_debug_enabled = true;
_default_tunes[TONE_STARTUP_TUNE] = "MFT240L8 O4aO5dc O4aO5dc O4aO5dc L16dcdcdcdc"; // startup tune
_default_tunes[TONE_ERROR_TUNE] = "MBT200a8a8a8PaaaP"; // ERROR tone
_default_tunes[TONE_NOTIFY_POSITIVE_TUNE] = "MFT200e8a8a"; // Notify Positive tone
_default_tunes[TONE_NOTIFY_NEUTRAL_TUNE] = "MFT200e8e"; // Notify Neutral tone
_default_tunes[TONE_NOTIFY_NEGATIVE_TUNE] = "MFT200e8c8e8c8e8c8"; // Notify Negative tone
_default_tunes[TONE_ARMING_WARNING_TUNE] = "MNT75L1O2G"; //arming warning
_default_tunes[TONE_BATTERY_WARNING_SLOW_TUNE] = "MBNT100a8"; //battery warning slow
_default_tunes[TONE_BATTERY_WARNING_FAST_TUNE] = "MBNT255a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8"; //battery warning fast
_default_tunes[TONE_GPS_WARNING_TUNE] = "MFT255L4AAAL1F#"; //gps warning slow
_default_tunes[TONE_ARMING_FAILURE_TUNE] = "MFT255L4<<<BAP";
_default_tunes[TONE_PARACHUTE_RELEASE_TUNE] = "MFT255L16agagagag"; // parachute release
_default_tunes[TONE_EKF_WARNING_TUNE] = "MFT255L8ddd#d#eeff"; // ekf warning
_default_tunes[TONE_BARO_WARNING_TUNE] = "MFT255L4gf#fed#d"; // baro warning
_tune_names[TONE_STARTUP_TUNE] = "startup"; // startup tune
_tune_names[TONE_ERROR_TUNE] = "error"; // ERROR tone
_tune_names[TONE_NOTIFY_POSITIVE_TUNE] = "positive"; // Notify Positive tone
_tune_names[TONE_NOTIFY_NEUTRAL_TUNE] = "neutral"; // Notify Neutral tone
_tune_names[TONE_NOTIFY_NEGATIVE_TUNE] = "negative"; // Notify Negative tone
_tune_names[TONE_ARMING_WARNING_TUNE] = "arming"; // arming warning
_tune_names[TONE_BATTERY_WARNING_SLOW_TUNE] = "slow_bat"; // battery warning slow
_tune_names[TONE_BATTERY_WARNING_FAST_TUNE] = "fast_bat"; // battery warning fast
_tune_names[TONE_GPS_WARNING_TUNE] = "gps_warning"; // gps warning
_tune_names[TONE_ARMING_FAILURE_TUNE] = "arming_failure"; //fail to arm
_tune_names[TONE_PARACHUTE_RELEASE_TUNE] = "parachute_release"; // parachute release
_tune_names[TONE_EKF_WARNING_TUNE] = "ekf_warning"; // ekf warning
_tune_names[TONE_BARO_WARNING_TUNE] = "baro_warning"; // baro warning
}
ToneAlarm::~ToneAlarm()
{
}
int
ToneAlarm::init()
{
int ret;
ret = CDev::init();
if (ret != OK)
return ret;
/* configure the GPIO to the idle state */
stm32_configgpio(GPIO_TONE_ALARM_IDLE);
/* clock/power on our timer */
#if defined(CONFIG_ARCH_BOARD_F4BY)
modifyreg32(STM32_RCC_APB2ENR, 0, TONE_ALARM_CLOCK_ENABLE);
#else
modifyreg32(STM32_RCC_APB1ENR, 0, TONE_ALARM_CLOCK_ENABLE);
#endif
/* initialise the timer */
rCR1 = 0;
rCR2 = 0;
rSMCR = 0;
rDIER = 0;
rCCER &= TONE_CCER; /* unlock CCMR* registers */
rCCMR1 = TONE_CCMR1;
rCCMR2 = TONE_CCMR2;
rCCER = TONE_CCER;
rDCR = 0;
/* toggle the CC output each time the count passes 1 */
TONE_rCCR = 1;
/* default the timer to a prescale value of 1; playing notes will change this */
rPSC = 0;
/* make sure the timer is running */
rCR1 = GTIM_CR1_CEN;
debug("ready");
return OK;
}
unsigned
ToneAlarm::note_to_divisor(unsigned note)
{
// compute the frequency first (Hz)
float freq = 880.0f * expf(logf(2.0f) * ((int)note - 46) / 12.0f);
float period = 0.5f / freq;
// and the divisor, rounded to the nearest integer
unsigned divisor = (period * TONE_ALARM_CLOCK) + 0.5f;
return divisor;
}
unsigned
ToneAlarm::note_duration(unsigned &silence, unsigned note_length, unsigned dots)
{
unsigned whole_note_period = (60 * 1000000 * 4) / _tempo;
if (note_length == 0)
note_length = 1;
unsigned note_period = whole_note_period / note_length;
switch (_note_mode) {
case MODE_NORMAL:
silence = note_period / 8;
break;
case MODE_STACCATO:
silence = note_period / 4;
break;
default:
case MODE_LEGATO:
silence = 0;
break;
}
note_period -= silence;
unsigned dot_extension = note_period / 2;
while (dots--) {
note_period += dot_extension;
dot_extension /= 2;
}
return note_period;
}
unsigned
ToneAlarm::rest_duration(unsigned rest_length, unsigned dots)
{
unsigned whole_note_period = (60 * 1000000 * 4) / _tempo;
if (rest_length == 0)
rest_length = 1;
unsigned rest_period = whole_note_period / rest_length;
unsigned dot_extension = rest_period / 2;
while (dots--) {
rest_period += dot_extension;
dot_extension /= 2;
}
return rest_period;
}
void
ToneAlarm::start_note(unsigned note)
{
// compute the divisor
unsigned divisor = note_to_divisor(note);
// pick the lowest prescaler value that we can use
// (note that the effective prescale value is 1 greater)
unsigned prescale = divisor / 65536;
// calculate the timer period for the selected prescaler value
unsigned period = (divisor / (prescale + 1)) - 1;
rPSC = prescale; // load new prescaler
rARR = period; // load new toggle period
rEGR = GTIM_EGR_UG; // force a reload of the period
rCCER |= TONE_CCER; // enable the output
// configure the GPIO to enable timer output
stm32_configgpio(GPIO_TONE_ALARM);
}
void
ToneAlarm::stop_note()
{
/* stop the current note */
rCCER &= ~TONE_CCER;
/*
* Make sure the GPIO is not driving the speaker.
*/
stm32_configgpio(GPIO_TONE_ALARM_IDLE);
}
void
ToneAlarm::start_tune(const char *tune)
{
// kill any current playback
hrt_cancel(&_note_call);
// record the tune
_tune = tune;
_next = tune;
// initialise player state
_tempo = 120;
_note_length = 4;
_note_mode = MODE_NORMAL;
_octave = 4;
_silence_length = 0;
_repeat = false; // otherwise command-line tunes repeat forever...
// schedule a callback to start playing
hrt_call_after(&_note_call, 0, (hrt_callout)next_trampoline, this);
}
void
ToneAlarm::next_note()
{
// do we have an inter-note gap to wait for?
if (_silence_length > 0) {
stop_note();
hrt_call_after(&_note_call, (hrt_abstime)_silence_length, (hrt_callout)next_trampoline, this);
_silence_length = 0;
return;
}
// make sure we still have a tune - may be removed by the write / ioctl handler
if ((_next == nullptr) || (_tune == nullptr)) {
stop_note();
return;
}
// parse characters out of the string until we have resolved a note
unsigned note = 0;
unsigned note_length = _note_length;
unsigned duration;
while (note == 0) {
// we always need at least one character from the string
int c = next_char();
if (c == 0)
goto tune_end;
_next++;
switch (c) {
case 'L': // select note length
_note_length = next_number();
if (_note_length < 1)
goto tune_error;
break;
case 'O': // select octave
_octave = next_number();
if (_octave > 6)
_octave = 6;
break;
case '<': // decrease octave
if (_octave > 0)
_octave--;
break;
case '>': // increase octave
if (_octave < 6)
_octave++;
break;
case 'M': // select inter-note gap
c = next_char();
if (c == 0)
goto tune_error;
_next++;
switch (c) {
case 'N':
_note_mode = MODE_NORMAL;
break;
case 'L':
_note_mode = MODE_LEGATO;
break;
case 'S':
_note_mode = MODE_STACCATO;
break;
case 'F':
_repeat = false;
break;
case 'B':
_repeat = true;
break;
default:
goto tune_error;
}
break;
case 'P': // pause for a note length
stop_note();
hrt_call_after(&_note_call,
(hrt_abstime)rest_duration(next_number(), next_dots()),
(hrt_callout)next_trampoline,
this);
return;
case 'T': { // change tempo
unsigned nt = next_number();
if ((nt >= 32) && (nt <= 255)) {
_tempo = nt;
} else {
goto tune_error;
}
break;
}
case 'N': // play an arbitrary note
note = next_number();
if (note > 84)
goto tune_error;
if (note == 0) {
// this is a rest - pause for the current note length
hrt_call_after(&_note_call,
(hrt_abstime)rest_duration(_note_length, next_dots()),
(hrt_callout)next_trampoline,
this);
return;
}
break;
case 'A'...'G': // play a note in the current octave
note = _note_tab[c - 'A'] + (_octave * 12) + 1;
c = next_char();
switch (c) {
case '#': // up a semitone
case '+':
if (note < 84)
note++;
_next++;
break;
case '-': // down a semitone
if (note > 1)
note--;
_next++;
break;
default:
// 0 / no next char here is OK
break;
}
// shorthand length notation
note_length = next_number();
if (note_length == 0)
note_length = _note_length;
break;
default:
goto tune_error;
}
}
// compute the duration of the note and the following silence (if any)
duration = note_duration(_silence_length, note_length, next_dots());
// start playing the note
start_note(note);
// and arrange a callback when the note should stop
hrt_call_after(&_note_call, (hrt_abstime)duration, (hrt_callout)next_trampoline, this);
return;
// tune looks bad (unexpected EOF, bad character, etc.)
tune_error:
lowsyslog("tune error\n");
_repeat = false; // don't loop on error
// stop (and potentially restart) the tune
tune_end:
stop_note();
if (_repeat) {
start_tune(_tune);
} else {
_tune = nullptr;
_default_tune_number = 0;
}
return;
}
int
ToneAlarm::next_char()
{
while (isspace(*_next)) {
_next++;
}
return toupper(*_next);
}
unsigned
ToneAlarm::next_number()
{
unsigned number = 0;
int c;
for (;;) {
c = next_char();
if (!isdigit(c))
return number;
_next++;
number = (number * 10) + (c - '0');
}
}
unsigned
ToneAlarm::next_dots()
{
unsigned dots = 0;
while (next_char() == '.') {
_next++;
dots++;
}
return dots;
}
void
ToneAlarm::next_trampoline(void *arg)
{
ToneAlarm *ta = (ToneAlarm *)arg;
ta->next_note();
}
int
ToneAlarm::ioctl(file *filp, int cmd, unsigned long arg)
{
int result = OK;
debug("ioctl %i %u", cmd, arg);
// irqstate_t flags = irqsave();
/* decide whether to increase the alarm level to cmd or leave it alone */
switch (cmd) {
case TONE_SET_ALARM:
debug("TONE_SET_ALARM %u", arg);
if (arg < TONE_NUMBER_OF_TUNES) {
if (arg == TONE_STOP_TUNE) {
// stop the tune
_tune = nullptr;
_next = nullptr;
_repeat = false;
_default_tune_number = 0;
} else {
/* always interrupt alarms, unless they are repeating and already playing */
if (!(_repeat && _default_tune_number == arg)) {
/* play the selected tune */
_default_tune_number = arg;
start_tune(_default_tunes[arg]);
}
}
} else {
result = -EINVAL;
}
break;
default:
result = -ENOTTY;
break;
}
// irqrestore(flags);
/* give it to the superclass if we didn't like it */
if (result == -ENOTTY)
result = CDev::ioctl(filp, cmd, arg);
return result;
}
int
ToneAlarm::write(file *filp, const char *buffer, size_t len)
{
// sanity-check the buffer for length and nul-termination
if (len > _tune_max)
return -EFBIG;
// if we have an existing user tune, free it
if (_user_tune != nullptr) {
// if we are playing the user tune, stop
if (_tune == _user_tune) {
_tune = nullptr;
_next = nullptr;
}
// free the old user tune
free((void *)_user_tune);
_user_tune = nullptr;
}
// if the new tune is empty, we're done
if (buffer[0] == '\0')
return OK;
// allocate a copy of the new tune
_user_tune = strndup(buffer, len);
if (_user_tune == nullptr)
return -ENOMEM;
// and play it
start_tune(_user_tune);
return len;
}
/**
* Local functions in support of the shell command.
*/
namespace
{
ToneAlarm *g_dev;
int
play_tune(unsigned tune)
{
int fd, ret;
fd = open(TONEALARM_DEVICE_PATH, 0);
if (fd < 0)
err(1, TONEALARM_DEVICE_PATH);
ret = ioctl(fd, TONE_SET_ALARM, tune);
close(fd);
if (ret != 0)
err(1, "TONE_SET_ALARM");
exit(0);
}
int
play_string(const char *str, bool free_buffer)
{
int fd, ret;
fd = open(TONEALARM_DEVICE_PATH, O_WRONLY);
if (fd < 0)
err(1, TONEALARM_DEVICE_PATH);
ret = write(fd, str, strlen(str) + 1);
close(fd);
if (free_buffer)
free((void *)str);
if (ret < 0)
err(1, "play tune");
exit(0);
}
} // namespace
int
tone_alarm_main(int argc, char *argv[])
{
unsigned tune;
/* start the driver lazily */
if (g_dev == nullptr) {
g_dev = new ToneAlarm;
if (g_dev == nullptr)
errx(1, "couldn't allocate the ToneAlarm driver");
if (g_dev->init() != OK) {
delete g_dev;
errx(1, "ToneAlarm init failed");
}
}
if (argc > 1) {
const char *argv1 = argv[1];
if (!strcmp(argv1, "start"))
play_tune(TONE_STARTUP_TUNE);
if (!strcmp(argv1, "stop"))
play_tune(TONE_STOP_TUNE);
if ((tune = strtol(argv1, nullptr, 10)) != 0)
play_tune(tune);
/* It might be a tune name */
for (tune = 1; tune < TONE_NUMBER_OF_TUNES; tune++)
if (!strcmp(g_dev->name(tune), argv1))
play_tune(tune);
/* If it is a file name then load and play it as a string */
if (*argv1 == '/') {
FILE *fd = fopen(argv1, "r");
int sz;
char *buffer;
if (fd == nullptr)
errx(1, "couldn't open '%s'", argv1);
fseek(fd, 0, SEEK_END);
sz = ftell(fd);
fseek(fd, 0, SEEK_SET);
buffer = (char *)malloc(sz + 1);
if (buffer == nullptr)
errx(1, "not enough memory memory");
fread(buffer, sz, 1, fd);
/* terminate the string */
buffer[sz] = 0;
play_string(buffer, true);
}
/* if it looks like a PLAY string... */
if (strlen(argv1) > 2) {
if (*argv1 == 'M') {
play_string(argv1, false);
}
}
}
errx(1, "unrecognized command, try 'start', 'stop', an alarm number or name, or a file name starting with a '/'");
}
|
/*
-- MAGMA (version 2.5.4) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date October 2020
@generated from sparse/control/magma_zparict_tools.cpp, normal z -> s, Thu Oct 8 23:05:51 2020
@author Hartwig Anzt
*/
#include "magmasparse_internal.h"
#ifdef _OPENMP
#include <omp.h>
#endif
#define SWAP(a, b) { tmp = a; a = b; b = tmp; }
#define SWAP_INT(a, b) { tmpi = a; a = b; b = tmpi; }
#define AVOID_DUPLICATES
//#define NANCHECK
/***************************************************************************//**
Purpose
-------
This function identifies the candidates like they appear as ILU1 fill-in.
In this version, the matrices are assumed unordered,
the linked list is traversed to acces the entries of a row.
Arguments
---------
@param[in]
L0 magma_s_matrix
tril( ILU(0) ) pattern of original system matrix.
@param[in]
L magma_s_matrix
Current lower triangular factor.
@param[in]
LT magma_s_matrix
Transose of the lower triangular factor.
@param[in,out]
L_new magma_s_matrix*
List of candidates for L in COO format.
@param[in]
queue magma_queue_t
Queue to execute in.
@ingroup magmasparse_saux
*******************************************************************************/
extern "C" magma_int_t
magma_sparict_candidates(
magma_s_matrix L0,
magma_s_matrix L,
magma_s_matrix LT,
magma_s_matrix *L_new,
magma_queue_t queue )
{
magma_int_t info = 0;
magma_index_t *insertedL;
float thrs = 1e-8;
magma_int_t orig = 1; // the pattern L0 and U0 is considered
magma_int_t existing = 0; // existing elements are also considered
magma_int_t ilufill = 1;
// magma_int_t num_threads;
//
// #pragma omp parallel
// {
// num_threads = omp_get_max_threads();
// }
// for now: also some part commented out. If it turns out
// this being correct, I need to clean up the code.
CHECK( magma_index_malloc_cpu( &L_new->row, L.num_rows+1 ));
CHECK( magma_index_malloc_cpu( &insertedL, L.num_rows+1 ));
#pragma omp parallel for
for( magma_int_t i=0; i<L.num_rows+1; i++ ){
L_new->row[i] = 0;
insertedL[i] = 0;
}
L_new->num_rows = L.num_rows;
L_new->num_cols = L.num_cols;
L_new->storage_type = Magma_CSR;
L_new->memory_location = Magma_CPU;
// go over the original matrix - this is the only way to allow elements to come back...
if( orig == 1 ){
#pragma omp parallel for
for( magma_index_t row=0; row<L0.num_rows; row++){
magma_int_t numaddrowL = 0;
magma_int_t ilu0 = L0.row[row];
magma_int_t ilut = L.row[row];
magma_int_t endilu0 = L0.row[ row+1 ];
magma_int_t endilut = L.row[ row+1 ];
magma_int_t ilu0col;
magma_int_t ilutcol;
do{
ilu0col = L0.col[ ilu0 ];
ilutcol = L.col[ ilut ];
if( ilu0col == ilutcol ){
ilu0++;
ilut++;
if( existing==1 )
numaddrowL++;
}
else if( ilutcol<ilu0col ){
ilut++;
if( existing==1 )
numaddrowL++;
}
else {
// this element is missing in the current approximation
// mark it as candidate
numaddrowL++;
ilu0++;
}
}while( ilut<endilut && ilu0<endilu0 );
// do the rest if existing
if( ilu0<endilu0 ){
do{
numaddrowL++;
ilu0++;
}while( ilu0<endilu0 );
}
L_new->row[ row+1 ] = L_new->row[ row+1 ]+numaddrowL;
}
} // end original
if( ilufill == 1 ){
// how to determine candidates:
// for each node i, look at any "intermediate" neighbor nodes numbered
// less, and then see if this neighbor has another neighbor j numbered
// more than the intermediate; if so, fill in is (i,j) if it is not
// already nonzero
#pragma omp parallel for
for( magma_index_t row=0; row<L.num_rows; row++){
magma_int_t numaddrowL = 0;
// loop first element over row - only for elements smaller the diagonal
for( magma_index_t el1=L.row[row]; el1<L.row[row+1]-1; el1++ ){
magma_index_t col1 = L.col[ el1 ];
// now check the upper triangular
// second loop first element over row - only for elements larger the intermediate
for( magma_index_t el2 = LT.row[ col1 ]+1; el2 < LT.row[ col1+1 ]; el2++ ){
magma_index_t col2 = LT.col[ el2 ];
magma_index_t cand_row = row;
magma_index_t cand_col = col2;
// check whether this element already exists
// first case: part of L
if( cand_col < row ){
// check whether this element already exists in L
magma_int_t exist = 0;
if( existing == 0 ){
for(magma_index_t k=L.row[cand_row]; k<L.row[cand_row+1]; k++ ){
if( L.col[ k ] == cand_col ){
exist = 1;
break;
}
}
}
// if it does not exist, increase counter for this location
// use the entry one further down to allow for parallel insertion
if( exist == 0 ){
//printf("checked row: %d this element does not yet exist in L: (%d,%d)\n", cand_row, cand_col);
numaddrowL++;
//numaddL[ row+1 ]++;
}
} else {
;
// we don't check if row>col. The motivation is that the element
// will in this case be identified as candidate from a differen row.
// Due to symmetry we have:
// Assume we have a fill-in element (i,j) with i<j
// Then there exists a k such that A(i,k)\neq 0 and A(k,j)\neq 0.
// Due to symmetry, we then also have A(k,i)\neq 0 and A(j,k)\neq 0.
// as a result, A(j,i) will be identified as fill-in also from row j
// in which i i the column and i<j.
}
}
}
L_new->row[ row+1 ] = L_new->row[ row+1 ]+numaddrowL;
}
} // end ilu-fill
//end = magma_sync_wtime( queue ); printf("llop 1.2 : %.2e\n", end-start);
// #########################################################################
// get the total candidate count
L_new->nnz = 0;
L_new->row[ 0 ] = L_new->nnz;
#pragma omp parallel
{
#ifdef _OPENMP
magma_int_t id = omp_get_thread_num();
#else
magma_int_t id = 0;
#endif
if( id == 0 ){
for( magma_int_t i = 0; i<L.num_rows; i++ ){
L_new->nnz = L_new->nnz + L_new->row[ i+1 ];
L_new->row[ i+1 ] = L_new->nnz;
}
}
}
magma_smalloc_cpu( &L_new->val, L_new->nnz );
magma_index_malloc_cpu( &L_new->rowidx, L_new->nnz );
magma_index_malloc_cpu( &L_new->col, L_new->nnz );
#pragma omp parallel for
for( magma_int_t i=0; i<L_new->nnz; i++ ){
L_new->val[i] = MAGMA_S_ZERO;
}
#pragma omp parallel for
for( magma_int_t i=0; i<L_new->nnz; i++ ){
L_new->col[i] = -1;
L_new->rowidx[i] = -1;
}
// #########################################################################
if( orig == 1 ){
#pragma omp parallel for
for( magma_index_t row=0; row<L0.num_rows; row++){
magma_int_t laddL = 0;
magma_int_t offsetL = L_new->row[row];
magma_int_t ilu0 = L0.row[row];
magma_int_t ilut = L.row[row];
magma_int_t endilu0 = L0.row[ row+1 ];
magma_int_t endilut = L.row[ row+1 ];
magma_int_t ilu0col;
magma_int_t ilutcol;
do{
ilu0col = L0.col[ ilu0 ];
ilutcol = L.col[ ilut ];
if( ilu0col == ilutcol ){
ilu0++;
ilut++;
if( existing==1 ){
L_new->col[ offsetL + laddL ] = ilu0col;
L_new->rowidx[ offsetL + laddL ] = row;
L_new->val[ offsetL + laddL ] = MAGMA_S_ONE;
laddL++;
}
}
else if( ilutcol<ilu0col ){
if( existing==1 ){
L_new->col[ offsetL + laddL ] = ilutcol;
L_new->rowidx[ offsetL + laddL ] = row;
L_new->val[ offsetL + laddL ] = MAGMA_S_ONE;
laddL++;
}
ilut++;
}
else {
// this element is missing in the current approximation
// mark it as candidate
L_new->col[ offsetL + laddL ] = ilu0col;
L_new->rowidx[ offsetL + laddL ] = row;
L_new->val[ offsetL + laddL ] = MAGMA_S_ONE + MAGMA_S_ONE + MAGMA_S_ONE;
laddL++;
ilu0++;
}
}while( ilut<endilut && ilu0<endilu0 );
if( ilu0<endilu0 ){
do{
ilu0col = L0.col[ ilu0 ];
L_new->col[ offsetL + laddL ] = ilu0col;
L_new->rowidx[ offsetL + laddL ] = row;
L_new->val[ offsetL + laddL ] = MAGMA_S_ONE + MAGMA_S_ONE + MAGMA_S_ONE;
laddL++;
ilu0++;
}while( ilu0<endilu0 );
}
insertedL[row] = laddL;
}
} // end original
if( ilufill==1 ){
#pragma omp parallel for
for( magma_index_t row=0; row<L.num_rows; row++){
magma_int_t laddL = 0;
magma_int_t offsetL = L_new->row[row] + insertedL[row];
// loop first element over row - only for elements smaller the diagonal
for( magma_index_t el1=L.row[row]; el1<L.row[row+1]-1; el1++ ){
magma_index_t col1 = L.col[ el1 ];
// now check the upper triangular
// second loop first element over row - only for elements larger the intermediate
for( magma_index_t el2 = LT.row[ col1 ]+1; el2 < LT.row[ col1+1 ]; el2++ ){
magma_index_t col2 = LT.col[ el2 ];
magma_index_t cand_row = row;
magma_index_t cand_col = col2;
//$########### we now have the candidate cand_row cand_col
// check whether this element already exists
// first case: part of L
if( cand_col < row ){
magma_int_t exist = 0;
if( existing == 0 ){
for(magma_index_t k=L.row[cand_row]; k<L.row[cand_row+1]; k++ ){
if( L.col[ k ] == cand_col ){
exist = 1;
break;
}
}
}
#ifdef AVOID_DUPLICATES
for( magma_int_t k=L_new->row[cand_row]; k<L_new->row[cand_row+1]; k++){
if( L_new->col[ k ] == cand_col ){
// element included in LU and nonzero
exist = 1;
break;
}
}
#endif
// if it does not exist, increase counter for this location
// use the entry one further down to allow for parallel insertion
if( exist == 0 ){
// printf("---------------->>> candidate in L at (%d, %d)\n", cand_row, cand_col);
//add in the next location for this row
// L_new->val[ numaddL[row] + laddL ] = MAGMA_S_MAKE(1e-14,0.0);
L_new->rowidx[ offsetL + laddL ] = cand_row;
L_new->col[ offsetL + laddL ] = cand_col;
L_new->val[ offsetL + laddL ] = MAGMA_S_ONE;
// L_new->list[ numaddL[row] + laddL ] = -1;
// L_new->row[ numaddL[row] + laddL ] = -1;
laddL++;
}
} else {
;
}
}
}
}
} //end ilufill
#ifdef AVOID_DUPLICATES
// #####################################################################
CHECK( magma_sparilut_thrsrm( 1, L_new, &thrs, queue ) );
// #####################################################################
#endif
cleanup:
magma_free_cpu( insertedL );
return info;
}
/***************************************************************************//**
Purpose
-------
This function does one synchronized ParILU sweep. Input and output are
different arrays.
Arguments
---------
@param[in]
A magma_s_matrix*
System matrix.
@param[in]
L magma_s_matrix*
Current approximation for the lower triangular factor
The format is sorted CSR.
@param[in]
U magma_s_matrix*
Current approximation for the upper triangular factor
The format is sorted CSC.
@param[out]
L_new magma_s_matrix*
Current approximation for the lower triangular factor
The format is unsorted CSR.
@param[out]
U_new magma_s_matrix*
Current approximation for the upper triangular factor
The format is unsorted CSC.
@param[in]
queue magma_queue_t
Queue to execute in.
@ingroup magmasparse_saux
*******************************************************************************/
extern "C" magma_int_t
magma_sparict_sweep_sync(
magma_s_matrix *A,
magma_s_matrix *L,
magma_queue_t queue )
{
magma_int_t info = 0;
//printf("\n"); fflush(stdout);
// parallel for using openmp
// temporary vectors to swap the col/rowidx later
// magma_index_t *tmpi;
float *L_new_val = NULL, *val_swap = NULL;
CHECK( magma_smalloc_cpu( &L_new_val, L->nnz ));
#pragma omp parallel for
for( magma_int_t e=0; e<L->nnz; e++){
magma_int_t i,j,icol,jcol;//,jold;
magma_index_t row = L->rowidx[ e ];
magma_index_t col = L->col[ e ];
float A_e = MAGMA_S_ZERO;
// check whether A contains element in this location
for( i = A->row[row]; i<A->row[row+1]; i++){
if( A->col[i] == col ){
A_e = A->val[i];
break;
}
}
//now do the actual iteration
i = L->row[ row ];
j = L->row[ col ];
magma_int_t endi = L->row[ row+1 ];
magma_int_t endj = L->row[ col+1 ];
float sum = MAGMA_S_ZERO;
float lsum = MAGMA_S_ZERO;
while( i<endi && j<endj ){
lsum = MAGMA_S_ZERO;
//jold = j;
icol = L->col[i];
jcol = L->col[j];
if( icol == jcol ){
lsum = L->val[i] * L->val[j];
sum = sum + lsum;
i++;
j++;
}
else if( icol<jcol ){
i++;
}
else {
j++;
}
}
sum = sum - lsum;
if( row == col ){
// write back to location e
L_new_val[ e ] = MAGMA_S_MAKE( sqrt( fabs( MAGMA_S_REAL(A_e - sum) )), 0.0 );
} else {
// write back to location e
L_new_val[ e ] = ( A_e - sum ) / L->val[endj-1];
}
}// end omp parallel section
val_swap = L_new_val;
L_new_val = L->val;
L->val = val_swap;
magma_free_cpu( L_new_val );
cleanup:
return info;
}
|
// Copyright (C) 2012-2015,2017 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include <config.h>
#include <dhcpsrv/addr_utilities.h>
#include <exceptions/exceptions.h>
#include <gtest/gtest.h>
#include <vector>
#include <stdint.h>
#include <stdlib.h>
using namespace std;
using namespace isc::dhcp;
using namespace isc::asiolink;
namespace {
// This test verifies that lastAddrInPrefix is able to handle IPv4 operations.
TEST(AddrUtilitiesTest, lastAddrInPrefix4) {
IOAddress addr1("192.0.2.1");
// Prefixes rounded to addresses are easy...
EXPECT_EQ("192.255.255.255", lastAddrInPrefix(addr1, 8).toText());
EXPECT_EQ("192.0.255.255", lastAddrInPrefix(addr1, 16).toText());
EXPECT_EQ("192.0.2.255", lastAddrInPrefix(addr1, 24).toText());
// these are trickier
EXPECT_EQ("192.0.2.127", lastAddrInPrefix(addr1, 25).toText());
EXPECT_EQ("192.0.2.63", lastAddrInPrefix(addr1, 26).toText());
EXPECT_EQ("192.0.2.31", lastAddrInPrefix(addr1, 27).toText());
EXPECT_EQ("192.0.2.15", lastAddrInPrefix(addr1, 28).toText());
EXPECT_EQ("192.0.2.7", lastAddrInPrefix(addr1, 29).toText());
EXPECT_EQ("192.0.2.3", lastAddrInPrefix(addr1, 30).toText());
// that doesn't make much sense as /31 subnet consists of network address
// and a broadcast address, with 0 usable addresses.
EXPECT_EQ("192.0.2.1", lastAddrInPrefix(addr1, 31).toText());
EXPECT_EQ("192.0.2.1", lastAddrInPrefix(addr1, 32).toText());
// Let's check extreme cases
IOAddress anyAddr("0.0.0.0");
EXPECT_EQ("127.255.255.255", lastAddrInPrefix(anyAddr, 1).toText());
EXPECT_EQ("255.255.255.255", lastAddrInPrefix(anyAddr, 0).toText());
EXPECT_EQ("0.0.0.0", lastAddrInPrefix(anyAddr, 32).toText());
}
// This test checks if firstAddrInPrefix is able to handle IPv4 operations.
TEST(AddrUtilitiesTest, firstAddrInPrefix4) {
IOAddress addr1("192.223.2.255");
// Prefixes rounded to addresses are easy...
EXPECT_EQ("192.0.0.0", firstAddrInPrefix(addr1, 8).toText());
EXPECT_EQ("192.223.0.0", firstAddrInPrefix(addr1, 16).toText());
EXPECT_EQ("192.223.2.0", firstAddrInPrefix(addr1, 24).toText());
// these are trickier
EXPECT_EQ("192.223.2.128", firstAddrInPrefix(addr1, 25).toText());
EXPECT_EQ("192.223.2.192", firstAddrInPrefix(addr1, 26).toText());
EXPECT_EQ("192.223.2.224", firstAddrInPrefix(addr1, 27).toText());
EXPECT_EQ("192.223.2.240", firstAddrInPrefix(addr1, 28).toText());
EXPECT_EQ("192.223.2.248", firstAddrInPrefix(addr1, 29).toText());
EXPECT_EQ("192.223.2.252", firstAddrInPrefix(addr1, 30).toText());
// that doesn't make much sense as /31 subnet consists of network address
// and a broadcast address, with 0 usable addresses.
EXPECT_EQ("192.223.2.254", firstAddrInPrefix(addr1, 31).toText());
EXPECT_EQ("192.223.2.255", firstAddrInPrefix(addr1, 32).toText());
// Let's check extreme cases.
IOAddress bcast("255.255.255.255");
EXPECT_EQ("128.0.0.0", firstAddrInPrefix(bcast, 1).toText());
EXPECT_EQ("0.0.0.0", firstAddrInPrefix(bcast, 0).toText());
EXPECT_EQ("255.255.255.255", firstAddrInPrefix(bcast, 32).toText());
}
/// This test checks if lastAddrInPrefix properly supports IPv6 operations
TEST(AddrUtilitiesTest, lastAddrInPrefix6) {
IOAddress addr1("2001:db8:1:1234:5678:abcd:1234:beef");
// Prefixes rounded to nibbles are easy...
EXPECT_EQ("2001:db8:1:1234:5678:abcd:1234:ffff",
lastAddrInPrefix(addr1, 112).toText());
EXPECT_EQ("2001:db8:1:1234:5678:abcd:123f:ffff",
lastAddrInPrefix(addr1, 108).toText());
EXPECT_EQ("2001:db8:1:1234:5678:abcd:12ff:ffff",
lastAddrInPrefix(addr1, 104).toText());
EXPECT_EQ("2001:db8:1:1234:ffff:ffff:ffff:ffff",
lastAddrInPrefix(addr1, 64).toText());
IOAddress addr2("2001::");
// These are tricker, though, as they are done in 1 bit increments
// the last address in 2001::/127 pool should be 2001::1
EXPECT_EQ("2001::1", lastAddrInPrefix(addr2, 127).toText());
EXPECT_EQ("2001::3", lastAddrInPrefix(addr2, 126).toText());
EXPECT_EQ("2001::7", lastAddrInPrefix(addr2, 125).toText());
EXPECT_EQ("2001::f", lastAddrInPrefix(addr2, 124).toText());
EXPECT_EQ("2001::1f", lastAddrInPrefix(addr2, 123).toText());
EXPECT_EQ("2001::3f", lastAddrInPrefix(addr2, 122).toText());
EXPECT_EQ("2001::7f", lastAddrInPrefix(addr2, 121).toText());
EXPECT_EQ("2001::ff", lastAddrInPrefix(addr2, 120).toText());
// Let's check extreme cases
IOAddress anyAddr("::");
EXPECT_EQ("7fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
lastAddrInPrefix(anyAddr, 1).toText());
EXPECT_EQ("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
lastAddrInPrefix(anyAddr, 0).toText());
EXPECT_EQ("::", lastAddrInPrefix(anyAddr, 128).toText());
}
/// This test checks if firstAddrInPrefix properly supports IPv6 operations
TEST(AddrUtilitiesTest, firstAddrInPrefix6) {
IOAddress addr1("2001:db8:1:1234:5678:1234:abcd:beef");
// Prefixes rounded to nibbles are easy...
EXPECT_EQ("2001:db8:1:1234:5678:1234::",
firstAddrInPrefix(addr1, 96).toText());
EXPECT_EQ("2001:db8:1:1234:5678:1230::",
firstAddrInPrefix(addr1, 92).toText());
EXPECT_EQ("2001:db8:1:1234:5678:1200::",
firstAddrInPrefix(addr1, 88).toText());
EXPECT_EQ("2001:db8:1:1234::",
firstAddrInPrefix(addr1, 64).toText());
IOAddress addr2("2001::ffff");
// These are tricker, though, as they are done in 1 bit increments
// the first address in 2001::/127 pool should be 2001::1
EXPECT_EQ("2001::fffe", firstAddrInPrefix(addr2, 127).toText());
EXPECT_EQ("2001::fffc", firstAddrInPrefix(addr2, 126).toText());
EXPECT_EQ("2001::fff8", firstAddrInPrefix(addr2, 125).toText());
EXPECT_EQ("2001::fff0", firstAddrInPrefix(addr2, 124).toText());
EXPECT_EQ("2001::ffe0", firstAddrInPrefix(addr2, 123).toText());
EXPECT_EQ("2001::ffc0", firstAddrInPrefix(addr2, 122).toText());
EXPECT_EQ("2001::ff80", firstAddrInPrefix(addr2, 121).toText());
EXPECT_EQ("2001::ff00", firstAddrInPrefix(addr2, 120).toText());
}
// Checks if IPv4 netmask is generated properly
TEST(AddrUtilitiesTest, getNetmask4) {
EXPECT_EQ("0.0.0.0", getNetmask4(0).toText());
EXPECT_EQ("128.0.0.0", getNetmask4(1).toText());
EXPECT_EQ("192.0.0.0", getNetmask4(2).toText());
EXPECT_EQ("224.0.0.0", getNetmask4(3).toText());
EXPECT_EQ("240.0.0.0", getNetmask4(4).toText());
EXPECT_EQ("248.0.0.0", getNetmask4(5).toText());
EXPECT_EQ("252.0.0.0", getNetmask4(6).toText());
EXPECT_EQ("254.0.0.0", getNetmask4(7).toText());
EXPECT_EQ("255.0.0.0", getNetmask4(8).toText());
EXPECT_EQ("255.128.0.0", getNetmask4(9).toText());
EXPECT_EQ("255.192.0.0", getNetmask4(10).toText());
EXPECT_EQ("255.224.0.0", getNetmask4(11).toText());
EXPECT_EQ("255.240.0.0", getNetmask4(12).toText());
EXPECT_EQ("255.248.0.0", getNetmask4(13).toText());
EXPECT_EQ("255.252.0.0", getNetmask4(14).toText());
EXPECT_EQ("255.254.0.0", getNetmask4(15).toText());
EXPECT_EQ("255.255.0.0", getNetmask4(16).toText());
EXPECT_EQ("255.255.128.0", getNetmask4(17).toText());
EXPECT_EQ("255.255.192.0", getNetmask4(18).toText());
EXPECT_EQ("255.255.224.0", getNetmask4(19).toText());
EXPECT_EQ("255.255.240.0", getNetmask4(20).toText());
EXPECT_EQ("255.255.248.0", getNetmask4(21).toText());
EXPECT_EQ("255.255.252.0", getNetmask4(22).toText());
EXPECT_EQ("255.255.254.0", getNetmask4(23).toText());
EXPECT_EQ("255.255.255.0", getNetmask4(24).toText());
EXPECT_EQ("255.255.255.128", getNetmask4(25).toText());
EXPECT_EQ("255.255.255.192", getNetmask4(26).toText());
EXPECT_EQ("255.255.255.224", getNetmask4(27).toText());
EXPECT_EQ("255.255.255.240", getNetmask4(28).toText());
EXPECT_EQ("255.255.255.248", getNetmask4(29).toText());
EXPECT_EQ("255.255.255.252", getNetmask4(30).toText());
EXPECT_EQ("255.255.255.254", getNetmask4(31).toText());
EXPECT_EQ("255.255.255.255", getNetmask4(32).toText());
EXPECT_THROW(getNetmask4(33), isc::BadValue);
}
// Checks if the calculation for IPv4 addresses in range are correct.
TEST(AddrUtilitiesTest, addrsInRange4) {
// Let's start with something simple
EXPECT_EQ(1, addrsInRange(IOAddress("192.0.2.0"), IOAddress("192.0.2.0")));
EXPECT_EQ(10, addrsInRange(IOAddress("192.0.2.10"), IOAddress("192.0.2.19")));
EXPECT_EQ(256, addrsInRange(IOAddress("192.0.2.0"), IOAddress("192.0.2.255")));
EXPECT_EQ(65536, addrsInRange(IOAddress("192.0.0.0"), IOAddress("192.0.255.255")));
EXPECT_EQ(16777216, addrsInRange(IOAddress("10.0.0.0"), IOAddress("10.255.255.255")));
// Let's check if the network boundaries are crossed correctly.
EXPECT_EQ(3, addrsInRange(IOAddress("10.0.0.255"), IOAddress("10.0.1.1")));
// Let's go a bit overboard with this! How many addresses are there in
// IPv4 address space? That's a slightly tricky question, as the answer
// cannot be stored in uint32_t.
EXPECT_EQ(uint64_t(std::numeric_limits<uint32_t>::max()) + 1,
addrsInRange(IOAddress("0.0.0.0"), IOAddress("255.255.255.255")));
// The upper bound cannot be smaller than the lower bound.
EXPECT_THROW(addrsInRange(IOAddress("192.0.2.5"), IOAddress("192.0.2.4")),
isc::BadValue);
}
// Checks if the calculation for IPv6 addresses in range are correct.
TEST(AddrUtilitiesTest, addrsInRange6) {
// Let's start with something simple
EXPECT_EQ(1, addrsInRange(IOAddress("::"), IOAddress("::")));
EXPECT_EQ(16, addrsInRange(IOAddress("fe80::1"), IOAddress("fe80::10")));
EXPECT_EQ(65536, addrsInRange(IOAddress("fe80::"), IOAddress("fe80::ffff")));
EXPECT_EQ(uint64_t(std::numeric_limits<uint32_t>::max()) + 1,
addrsInRange(IOAddress("fe80::"), IOAddress("fe80::ffff:ffff")));
// There's 2^80 addresses between those. Due to uint64_t limits, this method is
// capped at 2^64 -1.
EXPECT_EQ(std::numeric_limits<uint64_t>::max(),
addrsInRange(IOAddress("2001:db8:1::"), IOAddress("2001:db8:2::")));
// Let's check if the network boundaries are crossed correctly.
EXPECT_EQ(3, addrsInRange(IOAddress("2001:db8::ffff"), IOAddress("2001:db8::1:1")));
// Let's go a bit overboard with this! How many addresses are there in
// IPv6 address space? That's a really tricky question, as the answer
// wouldn't fit even in uint128_t (if we had it). This method is capped
// at max value of uint64_t.
EXPECT_EQ(std::numeric_limits<uint64_t>::max(), addrsInRange(IOAddress("::"),
IOAddress("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")));
EXPECT_THROW(addrsInRange(IOAddress("fe80::5"), IOAddress("fe80::4")),
isc::BadValue);
}
// Checks if IPv4 address ranges can be converted to prefix / prefix_len
TEST(AddrUtilitiesTest, prefixLengthFromRange4) {
// Use a shorter name
const auto& plfr = prefixLengthFromRange;
// Let's start with something simple
EXPECT_EQ(32, plfr(IOAddress("192.0.2.0"), IOAddress("192.0.2.0")));
EXPECT_EQ(31, plfr(IOAddress("192.0.2.0"), IOAddress("192.0.2.1")));
EXPECT_EQ(30, plfr(IOAddress("192.0.2.0"), IOAddress("192.0.2.3")));
EXPECT_EQ(29, plfr(IOAddress("192.0.2.0"), IOAddress("192.0.2.7")));
EXPECT_EQ(28, plfr(IOAddress("192.0.2.0"), IOAddress("192.0.2.15")));
EXPECT_EQ(27, plfr(IOAddress("192.0.2.0"), IOAddress("192.0.2.31")));
EXPECT_EQ(26, plfr(IOAddress("192.0.2.0"), IOAddress("192.0.2.63")));
EXPECT_EQ(25, plfr(IOAddress("192.0.2.0"), IOAddress("192.0.2.127")));
EXPECT_EQ(24, plfr(IOAddress("192.0.2.0"), IOAddress("192.0.2.255")));
EXPECT_EQ(23, plfr(IOAddress("192.0.2.0"), IOAddress("192.0.3.255")));
EXPECT_EQ(16, plfr(IOAddress("10.0.0.0"), IOAddress("10.0.255.255")));
EXPECT_EQ(8, plfr(IOAddress("10.0.0.0"), IOAddress("10.255.255.255")));
EXPECT_EQ(0, plfr(IOAddress("0.0.0.0"), IOAddress("255.255.255.255")));
// Fail if a network boundary is crossed
EXPECT_EQ(-1, plfr(IOAddress("10.0.0.255"), IOAddress("10.0.1.1")));
// The upper bound cannot be smaller than the lower bound
EXPECT_THROW(plfr(IOAddress("192.0.2.5"), IOAddress("192.0.2.4")),
isc::BadValue);
}
// Checks if IPv6 address ranges can be converted to prefix / prefix_len
TEST(AddrUtilitiesTest, prefixLengthFromRange6) {
// Use a shorter name
const auto& plfr = prefixLengthFromRange;
// Let's start with something simple
EXPECT_EQ(128, plfr(IOAddress("::"), IOAddress("::")));
EXPECT_EQ(112, plfr(IOAddress("fe80::"), IOAddress("fe80::ffff")));
EXPECT_EQ(96, plfr(IOAddress("fe80::"), IOAddress("fe80::ffff:ffff")));
EXPECT_EQ(80, plfr(IOAddress("fe80::"),
IOAddress("fe80::ffff:ffff:ffff")));
EXPECT_EQ(64, plfr(IOAddress("fe80::"),
IOAddress("fe80::ffff:ffff:ffff:ffff")));
EXPECT_EQ(63, plfr(IOAddress("fe80::"),
IOAddress("fe80::1:ffff:ffff:ffff:ffff")));
EXPECT_EQ(62, plfr(IOAddress("fe80::"),
IOAddress("fe80::3:ffff:ffff:ffff:ffff")));
EXPECT_EQ(61, plfr(IOAddress("fe80::"),
IOAddress("fe80::7:ffff:ffff:ffff:ffff")));
EXPECT_EQ(60, plfr(IOAddress("fe80::"),
IOAddress("fe80::f:ffff:ffff:ffff:ffff")));
EXPECT_EQ(59, plfr(IOAddress("fe80::"),
IOAddress("fe80::1f:ffff:ffff:ffff:ffff")));
EXPECT_EQ(58, plfr(IOAddress("fe80::"),
IOAddress("fe80::3f:ffff:ffff:ffff:ffff")));
EXPECT_EQ(57, plfr(IOAddress("fe80::"),
IOAddress("fe80::7f:ffff:ffff:ffff:ffff")));
EXPECT_EQ(56, plfr(IOAddress("fe80::"),
IOAddress("fe80::ff:ffff:ffff:ffff:ffff")));
EXPECT_EQ(55, plfr(IOAddress("fe80::"),
IOAddress("fe80::1ff:ffff:ffff:ffff:ffff")));
EXPECT_EQ(54, plfr(IOAddress("fe80::"),
IOAddress("fe80::3ff:ffff:ffff:ffff:ffff")));
EXPECT_EQ(53, plfr(IOAddress("fe80::"),
IOAddress("fe80::7ff:ffff:ffff:ffff:ffff")));
EXPECT_EQ(52, plfr(IOAddress("fe80::"),
IOAddress("fe80::fff:ffff:ffff:ffff:ffff")));
EXPECT_EQ(51, plfr(IOAddress("fe80::"),
IOAddress("fe80::1fff:ffff:ffff:ffff:ffff")));
EXPECT_EQ(50, plfr(IOAddress("fe80::"),
IOAddress("fe80::3fff:ffff:ffff:ffff:ffff")));
EXPECT_EQ(49, plfr(IOAddress("fe80::"),
IOAddress("fe80::7fff:ffff:ffff:ffff:ffff")));
EXPECT_EQ(48, plfr(IOAddress("fe80::"),
IOAddress("fe80::ffff:ffff:ffff:ffff:ffff")));
EXPECT_EQ(0, plfr(IOAddress("::"),
IOAddress("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")));
// Fail if a network boundary is crossed
EXPECT_EQ(-1, plfr(IOAddress("2001:db8::ffff"),
IOAddress("2001:db8::1:1")));
// The upper bound cannot be smaller than the lower bound
EXPECT_THROW(plfr(IOAddress("fe80::5"), IOAddress("fe80::4")),
isc::BadValue);
// Address family must match
EXPECT_THROW(plfr(IOAddress("192.0.2.0"), IOAddress("fe80::1")),
isc::BadValue);
}
// Checks if prefixInRange returns valid number of prefixes in specified range.
TEST(AddrUtilitiesTest, prefixesInRange) {
// How many /64 prefixes are in /64 pool?
EXPECT_EQ(1, prefixesInRange(64, 64));
// How many /63 prefixes are in /64 pool?
EXPECT_EQ(2, prefixesInRange(63, 64));
// How many /64 prefixes are in /48 pool?
EXPECT_EQ(65536, prefixesInRange(48, 64));
// How many /127 prefixes are in /64 pool?
EXPECT_EQ(uint64_t(9223372036854775808ull), prefixesInRange(64, 127));
// How many /128 prefixes are in /64 pool?
EXPECT_EQ(std::numeric_limits<uint64_t>::max(),
prefixesInRange(64, 128));
// Let's go overboard again. How many IPv6 addresses are there?
EXPECT_EQ(std::numeric_limits<uint64_t>::max(),
prefixesInRange(0, 128));
}
}; // end of anonymous namespace
|
#pragma once
#include <cstring>
#include <string>
#include <vector>
template <size_t Sigma = 26>
struct Trie {
struct Node {
char c;
int nx[Sigma];
std::vector<int> tails;
Node(char c) : c(c) { std::memset(nx, -1, sizeof(nx)); }
};
std::vector<Node> nodes;
Trie(const char basis = 'a') : basis(basis) { nodes.emplace_back('$'); }
void add(const std::string &s, int id = -1, int pos = 0) {
for (char c : s) {
int now = convert(c);
if (nodes[pos].nx[now] == -1) {
int nx_pos = nodes.size();
nodes[pos].nx[now] = nx_pos;
nodes.emplace_back(c);
pos = nx_pos;
} else {
pos = nodes[pos].nx[now];
}
}
nodes[pos].tails.emplace_back(id);
}
int find(const std::string &t, int pos = 0) const {
for (char c : t) {
int now = convert(c);
if (nodes[pos].nx[now] == -1) return -1;
pos = nodes[pos].nx[now];
}
return pos;
}
int convert(char c) const { return c - basis; }
private:
const char basis;
};
|
#include "parser.hpp"
void parser::create_variable(std::tuple<std::string, std::string> var) {
variable_list.emplace_back(var);
}
/* put a lot of this into syntax analysis, because that is half of the parser, then use the parser for opcode generation */
void parser::parse_code(std::vector<std::string> c)
{
lexer lex;
for (int i = 0; i < c.size(); ++i)
{
switch (lex.get_keyword(c.at(i).substr(0, 3)))
{
case lex.add_keyword:
{
this->erase(c, i, 0, 4);
int by = this->find_part(c, i, "by");
std::string target = this->get_sub(c, i, 0, by); //target
std::string::iterator end = std::remove(target.begin(), target.end(), ' ');
target.erase(end, target.end());
this->erase(c, i, 0, by);
std::string::reverse_iterator v = this->find_reverse(c, i);
std::string val = this->get_sub(c, i, 3, *v);
c.at(i).erase(3, *v);
std::tuple<int, std::string, std::string> instruction_tuple(opcode::op_add, target, val);
this->instruction_list.emplace_back(instruction_tuple);
break;
}
case lex.sub_keyword:
{
this->erase(c, i, 0, 4);
int to = this->find_part(c, i, "by");
std::string target = c.at(i).substr(0, to);
std::string::iterator end = std::remove(target.begin(), target.end(), ' ');
target.erase(end, target.end());
c.at(i).erase(0, to);
std::string::reverse_iterator v = c.at(i).rbegin();
std::string val = c.at(i).substr(3, *v);
c.at(i).erase(3, *v);
std::tuple<int, std::string, std::string> instruction_tuple(opcode::op_sub, target, val);
this->instruction_list.emplace_back(instruction_tuple);
break;
}
case lex.mul_keyword:
{
c.at(i).erase(0, 4);
int to = c.at(i).find("by");
std::string target = c.at(i).substr(0, to);
std::string::iterator end = std::remove(target.begin(), target.end(), ' ');
target.erase(end, target.end());
c.at(i).erase(0, to);
std::string::reverse_iterator v = c.at(i).rbegin();
std::string val = c.at(i).substr(3, *v);
c.at(i).erase(3, *v);
std::tuple<int, std::string, std::string> instruction_tuple(opcode::op_mul, target, val);
this->instruction_list.emplace_back(instruction_tuple);
break;
}
case lex.div_keyword:
{
c.at(i).erase(0, 4);
int to = c.at(i).find("by");
std::string target = c.at(i).substr(0, to);
std::string::iterator end = std::remove(target.begin(), target.end(), ' ');
target.erase(end, target.end());
c.at(i).erase(0, to);
std::string::reverse_iterator v = c.at(i).rbegin();
std::string val = c.at(i).substr(3, *v);
c.at(i).erase(3, *v);
std::tuple<int, std::string, std::string> instruction_tuple(opcode::op_div, target, val);
this->instruction_list.emplace_back(instruction_tuple);
break;
}
case lex.mod_keyword:
{
c.at(i).erase(0, 4);
int to = c.at(i).find("by");
std::string target = c.at(i).substr(0, to);
std::string::iterator end = std::remove(target.begin(), target.end(), ' ');
target.erase(end, target.end());
c.at(i).erase(0, to);
std::string::reverse_iterator v = c.at(i).rbegin();
std::string val = c.at(i).substr(3, *v);
c.at(i).erase(3, *v);
std::tuple<int, std::string, std::string> instruction_tuple(opcode::op_mod, target, val);
this->instruction_list.emplace_back(instruction_tuple);
break;
}
case lex.mov_keyword:
{
}
case lex.var_keyword:
{
c.at(i).erase(0, 4);
int eq = c.at(i).find("=");
std::string sub = c.at(i).substr(0, eq);
std::string::iterator end = std::remove(sub.begin(), sub.end(), ' ');
sub.erase(end, sub.end());
c.at(i).erase(0, eq);
std::string::reverse_iterator v = c.at(i).rbegin();
std::string val = c.at(i).substr(2, *v);
if (val.find("\"") != std::string::npos)
{
std::string::iterator end = std::remove(val.begin(), val.end(), '\"');
val.erase(end, val.end());
}
std::tuple<std::string, std::string> new_var(sub, val);
this->create_variable(new_var);
break;
}
case lex.out_keyword:
{
c.at(i).erase(0, 4);
std::string::reverse_iterator it = c.at(i).rbegin();
std::string var = c.at(i).substr(0, *it);
std::tuple<int, std::string, std::string> instruction_tuple(opcode::op_out, var, "");
this->instruction_list.emplace_back(instruction_tuple);
break;
}
case lex.cin_keyword:
{
}
default:
break;
}
}
}
|
/*=========================================================================
Program: Visualization Toolkit
Module: TestOSConeCxx.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// This test covers offscreen rendering.
//
// The command line arguments are:
// -I => run in interactive mode; unless this is used, the program will
// not allow interaction and exit
#include "vtkTestUtilities.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRenderWindow.h"
#include "vtkRenderer.h"
#include "vtkActor.h"
#include "vtkPolyDataMapper.h"
#include "vtkConeSource.h"
int TestOSConeCxx(int argc, char* argv[])
{
vtkRenderWindow *renWin = vtkRenderWindow::New();
renWin->OffScreenRenderingOn();
renWin->SetMultiSamples(0);
vtkRenderer *renderer = vtkRenderer::New();
renWin->AddRenderer(renderer);
renderer->Delete();
vtkConeSource *cone=vtkConeSource::New();
vtkPolyDataMapper *mapper=vtkPolyDataMapper::New();
mapper->SetInputConnection(cone->GetOutputPort());
cone->Delete();
vtkActor *actor=vtkActor::New();
actor->SetMapper(mapper);
mapper->Delete();
renderer->AddActor(actor);
actor->Delete();
#if 0
vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
iren->SetRenderWindow(renWin);
renWin->Delete();
renWin->Render();
int retVal = vtkRegressionTestImage( renWin );
if ( retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
// Cleanup
iren->Delete();
#else // the interactor version fails with OSMesa.
renWin->Render();
int retVal = vtkRegressionTestImage( renWin );
renWin->Delete();
#endif
return !retVal;
}
|
//==============================================================================
// Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_CONSTANT_CONSTANTS_EPS_HPP_INCLUDED
#define BOOST_SIMD_CONSTANT_CONSTANTS_EPS_HPP_INCLUDED
#include <boost/simd/include/functor.hpp>
#include <boost/simd/constant/register.hpp>
#include <boost/simd/constant/hierarchy.hpp>
namespace boost { namespace simd
{
namespace tag
{
/*!
@brief Eps generic tag
Represents the Eps constant in generic contexts.
@par Models:
Hierarchy
**/
BOOST_SIMD_CONSTANT_REGISTER(Eps,double,1,0X34000000,0x3CB0000000000000ULL)
}
namespace ext
{
template<class Site, class... Ts>
BOOST_FORCEINLINE generic_dispatcher<tag::Eps, Site> dispatching_Eps(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...)
{
return generic_dispatcher<tag::Eps, Site>();
}
template<class... Args>
struct impl_Eps;
}
/*!
Generates two times the machine epsilon.
@par Semantic:
@code
T r = Eps<T>();
@endcode
is similar to:
@code
if T is integral
r = T(1)
else if T is double
r = pow(2.0, -53);
else if T is float
r = pow(2.0f, -23);
@endcode
**/
BOOST_SIMD_CONSTANT_IMPLEMENTATION(boost::simd::tag::Eps, Eps)
} }
#include <boost/simd/constant/common.hpp>
#endif
|
#include <cctbx/boost_python/flex_fwd.h>
#include <boost/python/module.hpp>
#include <boost/python/class.hpp>
#include <boost/python/def.hpp>
#include <boost/python/list.hpp>
#include <boost/python/dict.hpp>
#include <scitbx/array_family/flex_types.h>
#include <scitbx/array_family/shared.h>
#include <scitbx/array_family/versa.h>
#include <scitbx/array_family/accessors/c_grid.h>
#include <cctbx/miller.h>
#include <dials/array_family/reflection_table.h>
#include <algorithm>
typedef cctbx::miller::index<> miller_index_t;
namespace sx_merging {
/**
* This visitor solves 2 problems:
* 1. Reflection tables have typed columns and the templated operator()
* function allows us to modify the columns without knowing the type.
* 2. Because of 1, we have to iterate over keys which means we
* cannot use the reflection table operator [] because it checks
* if the columns are all the same length. So here we extract the
* columns first, then modify them.
*/
struct hkl_splitter_visitor : public boost::static_visitor<void> {
dials::af::reflection_table &src;
dials::af::reflection_table::key_type key;
const std::map<miller_index_t, size_t> chunk_lookup;
const std::vector<dials::af::reflection_table> tables;
dials::af::shared<miller_index_t> src_hkls;
hkl_splitter_visitor(dials::af::reflection_table &src_,
dials::af::reflection_table::key_type key_,
const std::map<miller_index_t, size_t> &chunk_lookup_,
const std::vector<dials::af::reflection_table> &tables_)
: src(src_), key(key_), chunk_lookup(chunk_lookup_), tables(tables_) {
src_hkls = src.get<miller_index_t>("miller_index_asymmetric");
}
template <typename U>
void operator()(const dials::af::shared<U> &other_column) const {
std::vector<dials::af::shared<U> > all_columns;
for (size_t i = 0; i < tables.size(); i++) {
dials::af::reflection_table::const_iterator it = tables[i].find(key);
DIALS_ASSERT(it != tables[i].end());
dials::af::shared<U> col = boost::get<dials::af::shared<U> >(it->second);
all_columns.push_back(col);
}
for (size_t i = 0; i < src.size(); ++i) {
miller_index_t hkl = src_hkls[i];
std::map<miller_index_t, size_t>::const_iterator it = chunk_lookup.find(hkl);
if (it == chunk_lookup.end())
continue;
size_t table_idx = it->second;
all_columns[table_idx].push_back(other_column[i]);
}
}
};
void get_hkl_chunks_cpp(dials::af::reflection_table reflections,
const scitbx::af::shared<miller_index_t>& hkl_list,
const scitbx::af::shared<int>& chunk_id_list,
boost::python::list hkl_chunks_cpp){
// set up a map hkl:chunk_id
std::map<miller_index_t, size_t> chunk_lookup;
for(size_t i = 0UL; i < hkl_list.size(); ++i){
chunk_lookup[hkl_list[i]] = (size_t)chunk_id_list[i];
}
int n_chunks = boost::python::len(hkl_chunks_cpp);
std::vector<dials::af::reflection_table> tables;
for(size_t i=0UL; i < n_chunks; ++i){
tables.push_back(boost::python::extract<dials::af::reflection_table>(hkl_chunks_cpp[i]));
}
// distribute reflections over chunks
for (dials::af::reflection_table::const_iterator it = reflections.begin(); it != reflections.end(); ++it) {
hkl_splitter_visitor visitor(reflections, it->first, chunk_lookup, tables);
it->second.apply_visitor(visitor);
}
}
/**
* This visitor solves 2 problems:
* 1. Reflection tables have typed columns and the templated operator()
* function allows us to modify the columns without knowing the type.
* 2. Because of 1, we have to iterate over keys which means we
* cannot use the reflection table operator [] because it checks
* if the columns are all the same length. So here we extract the
* columns first, then modify them.
*/
struct experiment_id_splitter_visitor : public boost::static_visitor<void> {
dials::af::reflection_table &src;
dials::af::reflection_table::key_type key;
const std::map<std::string, size_t> chunk_lookup;
const std::vector<dials::af::reflection_table> tables;
dials::af::shared<std::string> expt_ids;
experiment_id_splitter_visitor(dials::af::reflection_table &src_,
dials::af::reflection_table::key_type key_,
const std::map<std::string, size_t> &chunk_lookup_,
const std::vector<dials::af::reflection_table> &tables_)
: src(src_), key(key_), chunk_lookup(chunk_lookup_), tables(tables_) {
expt_ids = src.get<std::string>("exp_id");
}
template <typename U>
void operator()(const dials::af::shared<U> &other_column) const {
std::vector<dials::af::shared<U> > all_columns;
for (size_t i = 0; i < tables.size(); i++) {
dials::af::reflection_table::const_iterator it = tables[i].find(key);
DIALS_ASSERT(it != tables[i].end());
dials::af::shared<U> col = boost::get<dials::af::shared<U> >(it->second);
all_columns.push_back(col);
}
for (size_t i = 0; i < src.size(); ++i) {
std::string experiment_id = expt_ids[i];
std::map<std::string, size_t>::const_iterator it = chunk_lookup.find(experiment_id);
DIALS_ASSERT(it != chunk_lookup.end());
size_t table_idx = it->second;
all_columns[table_idx].push_back(other_column[i]);
}
}
};
//template <typename T>
void split_reflections_by_experiment_chunks_cpp(dials::af::reflection_table reflections,
const scitbx::af::shared<std::string>& exp_id_list,
const scitbx::af::shared<int>& chunk_id_list,
boost::python::list reflection_chunks){
// set up a map exp_id:chunk_id
std::map<std::string, size_t> chunk_lookup;
for(size_t i = 0UL; i < exp_id_list.size(); ++i){
chunk_lookup[exp_id_list[i]] = (size_t)chunk_id_list[i];
}
int n_chunks = boost::python::len(reflection_chunks);
std::vector<dials::af::reflection_table> tables;
for(size_t i=0UL; i < n_chunks; ++i){
tables.push_back(boost::python::extract<dials::af::reflection_table>(reflection_chunks[i]));
}
// distribute reflections over chunks
for (dials::af::reflection_table::const_iterator it = reflections.begin(); it != reflections.end(); ++it) {
experiment_id_splitter_visitor visitor(reflections, it->first, chunk_lookup, tables);
it->second.apply_visitor(visitor);
}
}
dials::af::reflection_table isigi_dict_to_reflection_table(
dials::af::shared<cctbx::miller::index<> > miller_indices,
boost::python::dict ISIGI) {
dials::af::reflection_table table;
boost::python::list keys = ISIGI.keys();
dials::af::shared<cctbx::miller::index<> > miller_index = table.get<cctbx::miller::index<> >("miller_index");
dials::af::shared<cctbx::miller::index<> > miller_index_original = table.get<cctbx::miller::index<> >("miller_index_original");
dials::af::shared<double> scaled_intensity = table.get<double>("scaled_intensity");
dials::af::shared<double> isigi = table.get<double>("isigi");
dials::af::shared<double> slope = table.get<double>("slope");
dials::af::shared<double> iobs = table.get<double>("iobs");
dials::af::shared<size_t> miller_id = table.get<size_t>("miller_id");
dials::af::shared<size_t> crystal_id = table.get<size_t>("crystal_id");
for (size_t i = 0; i < miller_indices.size(); i ++) {
if (!ISIGI.has_key<cctbx::miller::index<> >(miller_indices[i])) continue;
boost::python::list values = boost::python::extract<boost::python::list>(ISIGI[miller_indices[i]]);
for (size_t j = 0; j < boost::python::len(values); j++) {
miller_index.push_back(miller_indices[i]);
boost::python::tuple item = boost::python::extract<boost::python::tuple>(values[j]);
scaled_intensity.push_back(boost::python::extract<double>(item[0]));
isigi.push_back(boost::python::extract<double>(item[1]));
slope.push_back(boost::python::extract<double>(item[2]));
miller_id.push_back(i);
crystal_id.push_back(0);
iobs.push_back(0);
miller_index_original.push_back(cctbx::miller::index<int>(0,0,0));
}
}
return table;
}
}
using namespace boost::python;
namespace sx_merging{
namespace boost_python { namespace {
void
sx_merging_init_module() {
using namespace boost::python;
def("get_hkl_chunks_cpp",&sx_merging::get_hkl_chunks_cpp);
def("isigi_dict_to_reflection_table",&sx_merging::isigi_dict_to_reflection_table);
def("split_reflections_by_experiment_chunks_cpp",&sx_merging::split_reflections_by_experiment_chunks_cpp);
}
}
}} // namespace sx_merging::boost_python::<anonymous>
BOOST_PYTHON_MODULE(sx_merging_ext)
{
sx_merging::boost_python::sx_merging_init_module();
}
|
#include "test.cpp"
int main ()
{
std::cout << "-------------------vector_test-------------------\n";
vector_test();
std::cout << std::endl;
std::cout << "-------------------line_test-------------------\n";
line_test();
std::cout << std::endl;
std::cout << "-------------------triangle_test-------------------\n";
triangle_test();
std::cout << std::endl;
std::cout << "-------------------surface_test-------------------\n";
surface_test();
std::cout << std::endl;
std::cout << "-------------------line_segment_test-------------------\n";
line_segment_test();
std::cout << std::endl;
std::cout << "-------------------end_to_end_test-------------------\n";
end_to_end_test();
// big_test();
}
|
//
// Copyright (c) 2002-2011 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "angle_gl.h"
#include "compiler/translator/BuiltInFunctionEmulator.h"
#include "compiler/translator/BuiltInFunctionEmulatorGLSL.h"
#include "compiler/translator/SymbolTable.h"
void InitBuiltInFunctionEmulatorForGLSL(BuiltInFunctionEmulator *emu, sh::GLenum shaderType)
{
#if defined(__APPLE__)
// we use macros here instead of function definitions to work around more GLSL
// compiler bugs, in particular on NVIDIA hardware on Mac OSX. Macros are
// problematic because if the argument has side-effects they will be repeatedly
// evaluated. This is unlikely to show up in real shaders, but is something to
// consider.
TType float1(EbtFloat);
TType float2(EbtFloat, 2);
TType float3(EbtFloat, 3);
TType float4(EbtFloat, 4);
if (shaderType == GL_FRAGMENT_SHADER)
{
emu->addEmulatedFunction(EOpCos, float1, "webgl_emu_precision float webgl_cos_emu(webgl_emu_precision float a) { return cos(a); }");
emu->addEmulatedFunction(EOpCos, float2, "webgl_emu_precision vec2 webgl_cos_emu(webgl_emu_precision vec2 a) { return cos(a); }");
emu->addEmulatedFunction(EOpCos, float3, "webgl_emu_precision vec3 webgl_cos_emu(webgl_emu_precision vec3 a) { return cos(a); }");
emu->addEmulatedFunction(EOpCos, float4, "webgl_emu_precision vec4 webgl_cos_emu(webgl_emu_precision vec4 a) { return cos(a); }");
}
emu->addEmulatedFunction(EOpDistance, float1, float1, "#define webgl_distance_emu(x, y) ((x) >= (y) ? (x) - (y) : (y) - (x))");
emu->addEmulatedFunction(EOpDot, float1, float1, "#define webgl_dot_emu(x, y) ((x) * (y))");
emu->addEmulatedFunction(EOpLength, float1, "#define webgl_length_emu(x) ((x) >= 0.0 ? (x) : -(x))");
emu->addEmulatedFunction(EOpNormalize, float1, "#define webgl_normalize_emu(x) ((x) == 0.0 ? 0.0 : ((x) > 0.0 ? 1.0 : -1.0))");
emu->addEmulatedFunction(EOpReflect, float1, float1, "#define webgl_reflect_emu(I, N) ((I) - 2.0 * (N) * (I) * (N))");
#endif
}
|
#include "ObjReader.hpp"
#include "VecMatMath.hpp"
#include <stdio.h>
#include <map>
#include <cstring>
using std::vector;
struct PackedVertex {
vec3 position;
vec2 uv;
vec3 normal;
bool operator<(const PackedVertex &that) const
{
return memcmp((void *)this, (void *)&that, sizeof(PackedVertex)) > 0;
}
};
bool ObjReader::loadOBJ(const char *path,
vector<vec3> &out_vertices,
vector<vec2> &out_uvs,
vector<vec3> &out_normals)
{
vector<unsigned int> vertexIndices, uvIndices, normalIndices;
vector<vec3> temp_vertices;
vector<vec2> temp_uvs;
vector<vec3> temp_normals;
FILE *file = fopen(path, "r");
if (file == NULL) {
printf("Cannot open file: %s\n", path);
getchar();
return false;
}
while (true) {
char lineHeader[128];
// read the first word of the line
int res = fscanf(file, "%127s", lineHeader);
if (res == EOF)
break; // EOF = End Of File. Quit the loop.
// else : parse lineHeader
if (strcmp(lineHeader, "v") == 0) {
vec3 vertex;
fscanf(file, "%f %f %f\n", &vertex[0], &vertex[1], &vertex[2]);
temp_vertices.push_back(vertex);
} else if (strcmp(lineHeader, "vt") == 0) {
vec2 uv;
fscanf(file, "%f %f\n", &uv[0], &uv[1]);
uv[1] = -uv[1]; // Invert V coordinate since we will only use DDS texture, which are inverted. Remove if you want to use TGA or BMP loaders.
temp_uvs.push_back(uv);
} else if (strcmp(lineHeader, "vn") == 0) {
vec3 normal;
fscanf(file, "%f %f %f\n", &normal[0], &normal[1], &normal[2]);
temp_normals.push_back(normal);
} else if (strcmp(lineHeader, "f") == 0) {
unsigned int vertexIndex[3], uvIndex[3], normalIndex[3];
int matches = fscanf(file, "%u/%u/%u %u/%u/%u %u/%u/%u\n", &vertexIndex[0], &uvIndex[0], &normalIndex[0], &vertexIndex[1], &uvIndex[1], &normalIndex[1], &vertexIndex[2], &uvIndex[2], &normalIndex[2]);
if (matches != 9) {
printf("File can't be read by our simple parser :-( Try exporting with other options, and make sure the mesh is triangulated.\n");
return false;
}
vertexIndices.push_back(vertexIndex[0]);
vertexIndices.push_back(vertexIndex[1]);
vertexIndices.push_back(vertexIndex[2]);
uvIndices .push_back(uvIndex[0]);
uvIndices .push_back(uvIndex[1]);
uvIndices .push_back(uvIndex[2]);
normalIndices.push_back(normalIndex[0]);
normalIndices.push_back(normalIndex[1]);
normalIndices.push_back(normalIndex[2]);
} else {
// Probably a comment, eat up the rest of the line
char stupidBuffer[1000];
fgets(stupidBuffer, 1000, file);
}
}
fclose(file);
// For each vertex of each triangle
for (unsigned int i = 0; i < vertexIndices.size(); i++) {
// Get the indices of its attributes
unsigned int vertexIndex = vertexIndices[i];
unsigned int uvIndex = uvIndices[i];
unsigned int normalIndex = normalIndices[i];
// Get the attributes thanks to the index, then put the attributes in buffers
out_vertices.push_back(temp_vertices[ vertexIndex - 1 ]);
out_uvs .push_back(temp_uvs[ uvIndex - 1 ]);
out_normals .push_back(temp_normals[ normalIndex - 1 ]);
}
return true;
}
bool ObjReader::loadOBJIndexed(
const char *path,
vector<vec3> &out_vertices,
vector<vec2> &out_uvs,
vector<vec3> &out_normals,
vector<unsigned short> &out_indices)
{
vector<vec3> temp_out_vertices;
vector<vec2> temp_out_uvs;
vector<vec3> temp_out_normals;
loadOBJ(path, temp_out_vertices, temp_out_uvs, temp_out_normals);
indexVBO(temp_out_vertices,
temp_out_uvs,
temp_out_normals,
out_indices,
out_vertices,
out_uvs,
out_normals);
return true;
}
bool getSimilarVertexIndex_fast(
PackedVertex &packed,
std::map<PackedVertex, unsigned short> &VertexToOutIndex,
unsigned short &result)
{
std::map<PackedVertex, unsigned short>::iterator it = VertexToOutIndex.find(packed);
if (it == VertexToOutIndex.end()) {
return false;
} else {
result = it->second;
return true;
}
}
void ObjReader::indexVBO(
vector<vec3> &in_vertices,
vector<vec2> &in_uvs,
vector<vec3> &in_normals,
vector<unsigned short> &out_indices,
vector<vec3> &out_vertices,
vector<vec2> &out_uvs,
vector<vec3> &out_normals)
{
std::map<PackedVertex, unsigned short> VertexToOutIndex;
// For each input vertex
for (unsigned int i = 0; i < in_vertices.size(); i++) {
PackedVertex packed = { in_vertices[i], in_uvs[i], in_normals[i] };
// Try to find a similar vertex in out_XXXX
unsigned short index;
bool found = getSimilarVertexIndex_fast(packed, VertexToOutIndex, index);
if (found) { // A similar vertex is already in the VBO, use it instead !
out_indices.push_back(index);
} else { // If not, it needs to be added in the output data.
out_vertices.push_back(in_vertices[i]);
out_uvs .push_back(in_uvs[i]);
out_normals .push_back(in_normals[i]);
unsigned short newindex = (unsigned short)out_vertices.size() - 1;
out_indices .push_back(newindex);
VertexToOutIndex[ packed ] = newindex;
}
}
}
|
/*
# Copyright (c) 2022 José Miguel Guerrero Hernández
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
*/
#include <memory>
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"
#include "sensor_msgs/msg/image.hpp"
#include "sensor_msgs/msg/point_cloud2.hpp"
#include <image_transport/image_transport.hpp>
#include <memory>
#include "cv_bridge/cv_bridge.h"
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/dnn.hpp>
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"
#include <pcl/point_types.h>
#include <pcl_conversions/pcl_conversions.h>
#include <pcl/point_types_conversion.h>
#include <pcl/PCLPointCloud2.h>
#include <pcl/conversions.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/filters/statistical_outlier_removal.h>
#include <pcl/filters/extract_indices.h>
#include <pcl/segmentation/sac_segmentation.h>
#include <pcl/sample_consensus/ransac.h>
#include <pcl/sample_consensus/sac_model_sphere.h>
pcl::PointCloud<pcl::PointXYZRGB> pcl_processing(const pcl::PointCloud<pcl::PointXYZRGB> in_pointcloud);
cv::Mat image_processing(const cv::Mat in_image);
class ComputerVisionSubscriber : public rclcpp::Node
{
public:
ComputerVisionSubscriber()
: Node("opencv_subscriber")
{
auto qos = rclcpp::QoS( rclcpp::QoSInitialization( RMW_QOS_POLICY_HISTORY_KEEP_LAST, 5 ));
qos.reliability(RMW_QOS_POLICY_RELIABILITY_BEST_EFFORT);
subscription_ = this->create_subscription<sensor_msgs::msg::Image>(
"/head_front_camera/rgb/image_raw", qos, std::bind(&ComputerVisionSubscriber::topic_callback, this, std::placeholders::_1));
publisher_ = this->create_publisher<sensor_msgs::msg::Image>(
"cv_image", qos);
}
private:
void topic_callback(const sensor_msgs::msg::Image::SharedPtr msg) const
{
// Convert ROS Image to CV Image
cv_bridge::CvImagePtr cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8);
cv::Mat image_raw = cv_ptr->image;
// Image processing
cv::Mat cv_image = image_processing(image_raw);
// Convert OpenCV Image to ROS Image
cv_bridge::CvImage img_bridge = cv_bridge::CvImage(msg->header, sensor_msgs::image_encodings::BGR8, cv_image);
sensor_msgs::msg::Image out_image; // >> message to be sent
img_bridge.toImageMsg(out_image); // from cv_bridge to sensor_msgs::Image
// Publish the data
publisher_ -> publish(out_image);
}
rclcpp::Subscription<sensor_msgs::msg::Image>::SharedPtr subscription_;
rclcpp::Publisher<sensor_msgs::msg::Image>::SharedPtr publisher_;
};
class PCLSubscriber : public rclcpp::Node
{
public:
PCLSubscriber()
: Node("pcl_subscriber")
{
auto qos = rclcpp::QoS( rclcpp::QoSInitialization( RMW_QOS_POLICY_HISTORY_KEEP_LAST, 5 ));
qos.reliability(RMW_QOS_POLICY_RELIABILITY_RELIABLE);
subscription_3d_ = this->create_subscription<sensor_msgs::msg::PointCloud2>(
"/head_front_camera/depth_registered/points", qos, std::bind(&PCLSubscriber::topic_callback_3d, this, std::placeholders::_1));
publisher_3d_ = this->create_publisher<sensor_msgs::msg::PointCloud2>(
"pcl_points", qos);
}
private:
void topic_callback_3d(const sensor_msgs::msg::PointCloud2::SharedPtr msg) const
{
// Convert to PCL data type
pcl::PointCloud<pcl::PointXYZRGB> point_cloud;
pcl::fromROSMsg(*msg, point_cloud);
pcl::PointCloud<pcl::PointXYZRGB> pcl_pointcloud = pcl_processing(point_cloud);
// Convert to ROS data type
sensor_msgs::msg::PointCloud2 output;
pcl::toROSMsg(pcl_pointcloud, output);
output.header = msg->header;
// Publish the data
publisher_3d_ -> publish(output);
}
rclcpp::Subscription<sensor_msgs::msg::PointCloud2>::SharedPtr subscription_3d_;
rclcpp::Publisher<sensor_msgs::msg::PointCloud2>::SharedPtr publisher_3d_;
};
/**
TO-DO
*/
cv::Mat image_processing(const cv::Mat in_image)
{
// Create output image
cv::Mat out_image = in_image;
// You must to return a 3-channels image to show it in ROS, so do it with 1-channel images
//cv::cvtColor(out_image, out_image, cv::COLOR_GRAY2BGR);
return out_image;
}
/**
TO-DO
*/
pcl::PointCloud<pcl::PointXYZRGB> pcl_processing(const pcl::PointCloud<pcl::PointXYZRGB> in_pointcloud)
{
pcl::PointCloud<pcl::PointXYZRGB> out_pointcloud;
out_pointcloud = in_pointcloud;
return out_pointcloud;
}
int main(int argc, char * argv[])
{
rclcpp::init(argc, argv);
rclcpp::executors::SingleThreadedExecutor exec;
auto cv_node = std::make_shared<ComputerVisionSubscriber>();
auto pcl_node = std::make_shared<PCLSubscriber>();
exec.add_node(cv_node);
exec.add_node(pcl_node);
exec.spin();
rclcpp::shutdown();
return 0;
}
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE590_Free_Memory_Not_on_Heap__delete_wchar_t_alloca_12.cpp
Label Definition File: CWE590_Free_Memory_Not_on_Heap__delete.pointer.label.xml
Template File: sources-sink-12.tmpl.cpp
*/
/*
* @description
* CWE: 590 Free Memory Not on Heap
* BadSource: alloca Data buffer is allocated on the stack with alloca()
* GoodSource: Allocate memory on the heap
* Sink:
* BadSink : Print then free data
* Flow Variant: 12 Control flow: if(globalReturnsTrueOrFalse())
*
* */
#include "std_testcase.h"
#include <wchar.h>
namespace CWE590_Free_Memory_Not_on_Heap__delete_wchar_t_alloca_12
{
#ifndef OMITBAD
void bad()
{
wchar_t * data;
data = NULL; /* Initialize data */
if(globalReturnsTrueOrFalse())
{
{
/* FLAW: data is allocated on the stack and deallocated in the BadSink */
wchar_t * dataBuffer = (wchar_t *)ALLOCA(sizeof(wchar_t));
*dataBuffer = L'A';
data = dataBuffer;
}
}
else
{
{
/* FIX: data is allocated on the heap and deallocated in the BadSink */
wchar_t * dataBuffer = new wchar_t;
*dataBuffer = L'A';
data = dataBuffer;
}
}
printWcharLine(*data);
/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */
delete data;
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() - use goodsource and badsink by changing the "if" so that
both branches use the GoodSource */
static void goodG2B()
{
wchar_t * data;
data = NULL; /* Initialize data */
if(globalReturnsTrueOrFalse())
{
{
/* FIX: data is allocated on the heap and deallocated in the BadSink */
wchar_t * dataBuffer = new wchar_t;
*dataBuffer = L'A';
data = dataBuffer;
}
}
else
{
{
/* FIX: data is allocated on the heap and deallocated in the BadSink */
wchar_t * dataBuffer = new wchar_t;
*dataBuffer = L'A';
data = dataBuffer;
}
}
printWcharLine(*data);
/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */
delete data;
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE590_Free_Memory_Not_on_Heap__delete_wchar_t_alloca_12; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
////////////////////////////////////////////////////////////////////////////////////////////////////////
// Part of Injectable Generic Camera System
// Copyright(c) 2019, Frans Bouma
// All rights reserved.
// https://github.com/FransBouma/InjectableGenericCameraSystem
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met :
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and / or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "System.h"
#include "Globals.h"
#include "Defaults.h"
#include "GameConstants.h"
#include "Gamepad.h"
#include "CameraManipulator.h"
#include "InterceptorHelper.h"
#include "InputHooker.h"
#include "input.h"
#include "CameraManipulator.h"
#include "GameImageHooker.h"
#include "D3D11Hooker.h"
#include "OverlayConsole.h"
#include "OverlayControl.h"
#include "MinHook.h"
namespace IGCS
{
using namespace IGCS::GameSpecific;
System::System()
{
}
System::~System()
{
}
void System::start(LPBYTE hostBaseAddress, DWORD hostImageSize)
{
Globals::instance().systemActive(true);
_hostImageAddress = (LPBYTE)hostBaseAddress;
_hostImageSize = hostImageSize;
Globals::instance().gamePad().setInvertLStickY(CONTROLLER_Y_INVERT);
Globals::instance().gamePad().setInvertRStickY(CONTROLLER_Y_INVERT);
initialize(); // will block till camera is found
mainLoop();
}
// Core loop of the system
void System::mainLoop()
{
while (Globals::instance().systemActive())
{
Sleep(FRAME_SLEEP);
updateFrame();
}
}
// updates the data and camera for a frame
void System::updateFrame()
{
handleUserInput();
writeNewCameraValuesToCameraStructs();
}
void System::writeNewCameraValuesToCameraStructs()
{
if (!g_cameraEnabled)
{
return;
}
DirectX::XMVECTOR newLookQuaternion = _camera.calculateLookQuaternion();
DirectX::XMFLOAT3 newCoords;
DirectX::XMFLOAT3 currentCoords;
if (GameSpecific::CameraManipulator::isCameraFound())
{
currentCoords = GameSpecific::CameraManipulator::initialiseCamera();
newCoords = _camera.calculateNewCoords(currentCoords, newLookQuaternion);
GameSpecific::CameraManipulator::writeNewCameraValuesToGameData(newCoords, newLookQuaternion);
}
}
void System::handleUserInput()
{
Globals::instance().gamePad().update();
if (_applyHammerPrevention)
{
_applyHammerPrevention = false;
// sleep main thread for 200ms so key repeat delay is simulated.
Sleep(300);
}
if (Input::isActionActivated(ActionType::SlowMo))
{
CameraManipulator::sloMoFunc(Globals::instance().settings().slowmoMult, _timeStopped);
Sleep(350);
}
if (Input::isActionActivated(ActionType::SpeedUp))
{
_speeduptoggle = !_speeduptoggle;
CameraManipulator::speedUp(Globals::instance().settings().speedMult, _speeduptoggle);
OverlayControl::addNotification(_speeduptoggle ? "Speed Up Activated" : "Speed Up Deactivated");
Sleep(350);
}
if (Input::isActionActivated(ActionType::ToggleOverlay))
{
OverlayControl::toggleOverlay();
_applyHammerPrevention = true;
}
if (!_cameraStructFound)
{
// camera not found yet, can't proceed.
return;
}
if (OverlayControl::isMainMenuVisible() && !Globals::instance().settings().allowCameraMovementWhenMenuIsUp)
{
// stop here, so keys used in the camera system won't affect anything of the camera
return;
}
if (Input::isActionActivated(ActionType::CameraEnable))
{
if (g_cameraEnabled)
{
//going to be disabled
CameraManipulator::restoreOriginalValuesAfterCameraDisable();
toggleCameraMovementLockState(false);
}
else
{
// it's going to be enabled, so cache the original values before we enable it so we can restore it afterwards
CameraManipulator::cacheOriginalValuesBeforeCameraEnable();
_camera.resetAngles();
}
g_cameraEnabled = g_cameraEnabled == 0 ? (BYTE)1 : (BYTE)0;
displayCameraState();
_applyHammerPrevention = true;
}
if (Input::isActionActivated(ActionType::FovReset) && Globals::instance().keyboardMouseControlCamera())
{
CameraManipulator::resetFoV();
}
if (Input::isActionActivated(ActionType::FovDecrease) && Globals::instance().keyboardMouseControlCamera())
{
CameraManipulator::changeFoV(-Globals::instance().settings().fovChangeSpeed);
}
if (Input::isActionActivated(ActionType::FovIncrease) && Globals::instance().keyboardMouseControlCamera())
{
CameraManipulator::changeFoV(Globals::instance().settings().fovChangeSpeed);
}
if (Input::isActionActivated(ActionType::Timestop))
{
toggleTimestopState();
_applyHammerPrevention = true;
}
if (Input::isActionActivated(ActionType::HudToggle))
{
toggleHudRenderState();
_applyHammerPrevention = true;
}
if (!g_cameraEnabled)
{
// camera is disabled. We simply disable all input to the camera movement, by returning now.
return;
}
if (Input::isActionActivated(ActionType::BlockInput))
{
toggleInputBlockState(!Globals::instance().inputBlocked());
_applyHammerPrevention = true;
}
_camera.resetMovement();
Settings& settings = Globals::instance().settings();
if (Input::isActionActivated(ActionType::CameraLock))
{
toggleCameraMovementLockState(!_cameraMovementLocked);
_applyHammerPrevention = true;
}
if (_cameraMovementLocked)
{
// no movement allowed, simply return
return;
}
bool altPressed = Utils::altPressed();
bool rcontrolPressed = Utils::keyDown(VK_RCONTROL);
float multiplier = altPressed ? settings.fastMovementMultiplier : rcontrolPressed ? settings.slowMovementMultiplier : 1.0f;
handleKeyboardCameraMovement(multiplier);
handleMouseCameraMovement(multiplier);
handleGamePadMovement(multiplier);
}
void System::handleGamePadMovement(float multiplierBase)
{
if(!Globals::instance().controllerControlsCamera())
{
return;
}
auto gamePad = Globals::instance().gamePad();
if (gamePad.isConnected())
{
Settings& settings = Globals::instance().settings();
float multiplier = gamePad.isButtonPressed(IGCS_BUTTON_FASTER) ? settings.fastMovementMultiplier
: gamePad.isButtonPressed(IGCS_BUTTON_SLOWER) ? settings.slowMovementMultiplier : multiplierBase;
vec2 rightStickPosition = gamePad.getRStickPosition();
_camera.pitch(rightStickPosition.y * multiplier);
_camera.yaw(rightStickPosition.x * multiplier);
vec2 leftStickPosition = gamePad.getLStickPosition();
_camera.moveUp((gamePad.getLTrigger() - gamePad.getRTrigger()) * multiplier);
_camera.moveForward(leftStickPosition.y * multiplier);
_camera.moveRight(leftStickPosition.x * multiplier);
if (gamePad.isButtonPressed(IGCS_BUTTON_TILT_LEFT))
{
_camera.roll(multiplier);
}
if (gamePad.isButtonPressed(IGCS_BUTTON_TILT_RIGHT))
{
_camera.roll(-multiplier);
}
if (gamePad.isButtonPressed(IGCS_BUTTON_RESET_FOV))
{
CameraManipulator::resetFoV();
}
if (gamePad.isButtonPressed(IGCS_BUTTON_FOV_DECREASE))
{
CameraManipulator::changeFoV(-Globals::instance().settings().fovChangeSpeed);
}
if (gamePad.isButtonPressed(IGCS_BUTTON_FOV_INCREASE))
{
CameraManipulator::changeFoV(Globals::instance().settings().fovChangeSpeed);
}
}
}
void System::handleMouseCameraMovement(float multiplier)
{
if (!Globals::instance().keyboardMouseControlCamera())
{
return;
}
long mouseDeltaX = Input::getMouseDeltaX();
long mouseDeltaY = Input::getMouseDeltaY();
if (abs(mouseDeltaY) > 1)
{
_camera.pitch(-(static_cast<float>(mouseDeltaY) * MOUSE_SPEED_CORRECTION * multiplier));
}
if (abs(mouseDeltaX) > 1)
{
_camera.yaw(static_cast<float>(mouseDeltaX) * MOUSE_SPEED_CORRECTION * multiplier);
}
Input::resetMouseDeltas();
}
void System::handleKeyboardCameraMovement(float multiplier)
{
if (!Globals::instance().keyboardMouseControlCamera())
{
return;
}
if (Input::isActionActivated(ActionType::MoveForward, true))
{
_camera.moveForward(multiplier);
}
if (Input::isActionActivated(ActionType::MoveBackward, true))
{
_camera.moveForward(-multiplier);
}
if (Input::isActionActivated(ActionType::MoveRight, true))
{
_camera.moveRight(multiplier);
}
if (Input::isActionActivated(ActionType::MoveLeft, true))
{
_camera.moveRight(-multiplier);
}
if (Input::isActionActivated(ActionType::MoveUp, true))
{
_camera.moveUp(multiplier);
}
if (Input::isActionActivated(ActionType::MoveDown, true))
{
_camera.moveUp(-multiplier);
}
if (Input::isActionActivated(ActionType::RotateDown, true))
{
_camera.pitch(-multiplier);
}
if (Input::isActionActivated(ActionType::RotateUp, true))
{
_camera.pitch(multiplier);
}
if (Input::isActionActivated(ActionType::RotateRight, true))
{
_camera.yaw(multiplier);
}
if (Input::isActionActivated(ActionType::RotateLeft, true))
{
_camera.yaw(-multiplier);
}
if (Input::isActionActivated(ActionType::TiltLeft, true))
{
_camera.roll(multiplier);
}
if (Input::isActionActivated(ActionType::TiltRight, true))
{
_camera.roll(-multiplier);
}
}
// Initializes system. Will block till camera struct is found.
void System::initialize()
{
MH_Initialize();
OverlayControl::init();
// first grab the window handle
Globals::instance().mainWindowHandle(Utils::findMainWindow(GetCurrentProcessId()));
// then initialize imgui and the rest.
OverlayControl::initImGui();
InputHooker::setInputHooks();
Input::registerRawInput();
D3D11Hooker::initializeHook();
GameSpecific::InterceptorHelper::initializeAOBBlocks(_hostImageAddress, _hostImageSize, _aobBlocks);
GameSpecific::InterceptorHelper::setCameraStructInterceptorHook(_aobBlocks);
waitForCameraStructAddresses(); // blocks till camera is found.
GameSpecific::InterceptorHelper::setPostCameraStructHooks(_aobBlocks);
// camera struct found, init our own camera object now and hook into game code which uses camera.
_cameraStructFound = true;
_camera.setPitch(INITIAL_PITCH_RADIANS);
_camera.setRoll(INITIAL_ROLL_RADIANS);
_camera.setYaw(INITIAL_YAW_RADIANS);
// apply initial settings
CameraManipulator::applySettingsToGameState();
}
// Waits for the interceptor to pick up the camera struct address. Should only return if address is found
void System::waitForCameraStructAddresses()
{
OverlayConsole::instance().logLine("Waiting for camera struct interception...");
while(!GameSpecific::CameraManipulator::isCameraFound())
{
handleUserInput();
Sleep(100);
}
OverlayControl::addNotification("Camera found.");
GameSpecific::CameraManipulator::displayCameraStructAddress();
}
void System::toggleCameraMovementLockState(bool newValue)
{
if (_cameraMovementLocked == newValue)
{
// already in this state. Ignore
return;
}
_cameraMovementLocked = newValue;
OverlayControl::addNotification(_cameraMovementLocked ? "Camera movement is locked" : "Camera movement is unlocked");
}
void System::toggleInputBlockState(bool newValue)
{
if (Globals::instance().inputBlocked() == newValue)
{
// already in this state. Ignore
return;
}
Globals::instance().inputBlocked(newValue);
OverlayControl::addNotification(newValue ? "Input to game blocked" : "Input to game enabled");
}
void System::displayCameraState()
{
OverlayControl::addNotification(g_cameraEnabled ? "Camera enabled" : "Camera disabled");
}
void System::toggleTimestopState()
{
_timeStopped = !_timeStopped;
OverlayControl::addNotification(_timeStopped ? "Game paused" : "Game unpaused");
CameraManipulator::timeStop();
}
void System::toggleHudRenderState()
{
_hudToggled = !_hudToggled;
BYTE hudNOP[3] = { 0xC3, 0x90, 0x90 };
InterceptorHelper::SaveBytesWrite(_aobBlocks[HUD_RENDER_INTERCEPT_KEY], 3, hudNOP, _hudToggled);
}
}
|
#ifndef RELU_HPP
#define RELU_HPP
#include "xtensor/xmath.hpp"
auto relu(auto x)
{
return xt::maximum(0, x);
}
#endif
|
#include <iostream>
#include <vector>
using namespace std;
bool IsVectorEven(vector<int> myVec);
bool IsVectorOdd(vector<int> myVec);
int GetNumbers(vector<int> &myVec);
void PrintVector(const vector<int> &myVec);
int main()
{
vector<int> numArr;
int count = GetNumbers(numArr);
if (count <= 0)
{
cout << "Did not get any number\n";
return 1;
}
if (IsVectorEven(numArr))
{
cout << "all even\n";
}
else if (IsVectorOdd(numArr))
{
cout << "all odd\n";
}
else
{
cout << "not even or odd\n";
}
return 0;
}
bool IsVectorEven(vector<int> myVec)
{
for (auto n : myVec)
{
if (n % 2 == 1)
{
return false;
}
}
return true;
}
bool IsVectorOdd(vector<int> myVec)
{
for (auto n : myVec)
{
if (n % 2 == 0)
{
return false;
}
}
return true;
}
void PrintVector(const vector<int> &myVec)
{
for (auto v : myVec)
{
cout << v << " ";
}
cout << endl;
}
int GetNumbers(vector<int> &myVec)
{
int total;
cin >> total;
myVec.resize(total);
for (auto &e : myVec)
{
cin >> e;
}
return total;
}
|
#include <ossimPlanet/ossimPlanetTerrain.h>
#include <osg/NodeVisitor>
#include <ossimPlanet/ossimPlanetTerrainTechnique.h>
#include <ossim/elevation/ossimElevSourceFactory.h>
#include <ossimPlanet/ossimPlanet.h>
#include <ossimPlanet/ossimPlanetTerrainGeometryTechnique.h>
#include <ossimPlanet/ossimPlanetGeoRefModel.h>
#include <ossimPlanet/ossimPlanetTerrainTechnique.h>
#include <ossimPlanet/ossimPlanetElevationRegistry.h>
#include <ossimPlanet/ossimPlanetViewer.h>
#include <ossimPlanet/ossimPlanetOssimElevationDatabase.h>
#include <osg/io_utils>
#include <osg/GraphicsContext>
#include <osgGA/EventVisitor>
#include <osgUtil/IntersectionVisitor>
#include <osgUtil/IntersectVisitor>
#include <osgUtil/IncrementalCompileOperation>
#include <stack>
#include <set>
#include <mutex>
struct ossimPlanetDatabasePagerCompileCompletedCallback : public osgUtil::IncrementalCompileOperation::CompileCompletedCallback
{
ossimPlanetDatabasePagerCompileCompletedCallback(ossimPlanetTerrain* terrain, ossimPlanetTileRequest* request)
:m_terrain(terrain), m_request(request){}
virtual bool compileCompleted(osgUtil::IncrementalCompileOperation::CompileSet* /* compileSet */)
{
//std::cout << "COMPILE COMPLETED\n";
m_terrain->addRequestToReadyToApplyQueue(m_request.get());
return true;
}
osg::ref_ptr<ossimPlanetTerrain> m_terrain;
osg::ref_ptr<ossimPlanetTileRequest> m_request;
};
class ossimPlanetTerrain::TextureCallback : public ossimPlanetTextureLayerCallback
{
public:
TextureCallback(ossimPlanetTerrain* terrain)
:theTerrain(terrain)
{
}
void setTerrain(ossimPlanetTerrain* value)
{
theTerrain = value;
}
virtual void refreshExtent(osg::ref_ptr<ossimPlanetExtents> extent)
{
if(theTerrain)
{
theTerrain->refreshImageLayers(extent.get());
}
}
virtual void layerAdded(osg::ref_ptr<ossimPlanetTextureLayer> layer)
{
if(theTerrain)
{
refreshExtent(layer->getExtents().get());
}
}
virtual void layerRemoved(osg::ref_ptr<ossimPlanetTextureLayer> layer,
osg::ref_ptr<ossimPlanetTextureLayer> parent)
{
if(theTerrain)
{
// only refresh if it was originally enabled
if(layer->getEnableFlag())
{
osg::ref_ptr<ossimPlanetExtents> extents = new ossimPlanetExtents(*layer->getExtents());
if(parent.valid())
{
osg::ref_ptr<ossimPlanetExtents> parentExtents = parent->getExtents();
if(parentExtents.valid())
{
extents->combineScale(parentExtents->getMinScale(),
parentExtents->getMaxScale());
}
}
refreshExtent(extents.get());
}
}
}
virtual void propertyChanged(const ossimString& name,
const ossimPlanetTextureLayer* object)
{
if(object&&name.contains("enable"))
{
if(object->getExtents().valid())
{
osg::ref_ptr<ossimPlanetExtents> extents = new ossimPlanetExtents(*object->getExtents());
const ossimPlanetTextureLayerGroup* parent = object->getParent(0);
if(parent)
{
osg::ref_ptr<ossimPlanetExtents> parentExtents = parent->getExtents();
if(parentExtents.valid())
{
extents->combineScale(parentExtents->getMinScale(),
parentExtents->getMaxScale());
}
}
refreshExtent(extents);
}
}
}
protected:
ossimPlanetTerrain* theTerrain;
};
class CountVisitor : public osg::NodeVisitor
{
public:
CountVisitor()
:osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN)
{
theCullCount = 0;
theNodeCount = 0;
}
virtual void apply(osg::Node& node)
{
#if 0
ossimPlanetTerrainTile* tile = dynamic_cast<ossimPlanetTerrainTile*>(&node);
if(tile)
{
if(tile->culledFlag())
{
++theCullCount;
}
++theNodeCount;
}
#else
ossimPlanetTerrainTile* tile = dynamic_cast<ossimPlanetTerrainTile*>(&node);
if(tile&&tile->culledFlag())
{
std::stack<ossimPlanetTerrainTile*> tileStack;
tileStack.push(tile);
ossimPlanetTerrainTile* current;
ossim_uint32 idx = 0;
while(!tileStack.empty())
{
current = tileStack.top();
tileStack.pop();
for(idx = 0; idx < current->getNumChildren();++idx)
{
ossimPlanetTerrainTile* t = (ossimPlanetTerrainTile*)current->getChild(idx);
if(t)
{
tileStack.push(t);
++ theCullCount;
++theNodeCount;
}
}
}
++theNodeCount;
++theCullCount;
return;
}
if(tile)
{
++theNodeCount;
}
#endif
traverse(node);
}
ossim_uint32 theCullCount;
ossim_uint32 theNodeCount;
};
class GatherChildrenVisitor : public osg::NodeVisitor
{
public:
GatherChildrenVisitor()
:osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN)
{
}
typedef std::stack<osg::ref_ptr<ossimPlanetTerrainTile> > TileStack;
virtual void apply(osg::Node& node)
{
ossimPlanetTerrainTile* tile = dynamic_cast<ossimPlanetTerrainTile*>(&node);
if(tile)
{
theGatheredChildren.push(tile);
}
traverse(node);
}
TileStack& gatheredChildren()
{
return theGatheredChildren;
}
protected:
TileStack theGatheredChildren;
};
class RemoveChildrenFromGraphVisitor : public osg::NodeVisitor
{
public:
RemoveChildrenFromGraphVisitor(ossimPlanetTerrain* terrain, ossim_int64 frameNumber, ossim_int64 delta=2)
:osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
theTerrain(terrain),
theFrameNumber(frameNumber),
theCullDelta(delta)
{
}
virtual void apply(osg::Node& node)
{
ossimPlanetTerrainTile* tile = dynamic_cast<ossimPlanetTerrainTile*>(&node);
if(tile)
{
if(ossim::abs((tile->frameNumber()-theFrameNumber)) > theCullDelta)
{
theTerrain->removeTerrainTileFromGraph(tile);
return;
}
}
traverse(node);
}
void setFrameNumber(ossim_int64 num)
{
theFrameNumber = num;
}
protected:
ossimPlanetTerrain* theTerrain;
ossim_int64 theFrameNumber;
ossim_int64 theCullDelta;
};
void ossimPlanetTerrain::UpdateTileCallback::operator()(osg::Node* node, osg::NodeVisitor* nv)
{
traverse(node,nv);
update(dynamic_cast<ossimPlanetTerrainTile*>(node), nv);
}
void ossimPlanetTerrain::UpdateTileCallback::update(ossimPlanetTerrainTile* /* tile */,
osg::NodeVisitor* /* nv */)
{
}
void ossimPlanetTerrain::CullTileCallback::operator()(osg::Node* node, osg::NodeVisitor* nv)
{
traverse(node,nv);
}
void ossimPlanetTerrain::CullTileCallback::cull(ossimPlanetTerrainTile* /* tile */,
osg::NodeVisitor* /* nv */)
{
}
ossimPlanetTerrain::ossimPlanetTerrain()
:theResetRootsFlag(true),
theLastFrameNumber(-1),
theTextureTileWidth(256),
theTextureTileHeight(256),
theElevationTileWidth(9),//2^n + 1
theElevationTileHeight(9), //2^n + 1
theSplitMergeLodScale(3.0),
theElevationExaggeration(1.0),
theMinimumTimeToCompilePerFrame(.003),// 3 milliseconds
thePrecompileEnabledFlag(true),
theElevationEnabledFlag(true),
theFalseEyeFlag(false),
theFalseEye(0.0,0.0,0.0),
thePriorityPointFlag(false),
thePriorityPoint(0.0,0.0,0.0)
{
theElevationCacheShrinkOperation = new ossimPlanetImageCacheShrinkOperation;
theCacheShrinkThreadQueue = new ossimPlanetOperationThreadQueue;
theElevationLayer = new ossimPlanetElevationDatabaseGroup;
theElevationLayer->setFillNullWithGeoidOffsetFlag(true);
theElevationLayer->setGeoRefModel(theModel.get());
theLastApplyToGraphFrameNumber = -1;
theMaxNumberOfOperationsToApplyToGraphPerFrame = 5;
theTextureCallback = new ossimPlanetTerrain::TextureCallback(this);
theTerrainTechnique = new ossimPlanetTerrainGeometryTechnique();
theElevationQueue = new ossimPlanetTileRequestThreadQueue;
theTextureQueue = new ossimPlanetTileRequestThreadQueue;
theTextureLayers.push_back(new ossimPlanetTextureLayerGroup());
theTextureLayers[0]->addCallback(theTextureCallback.get());
theSplitQueue = new ossimPlanetTileRequestThreadQueue();
theMergeQueue = new ossimPlanetTileRequestQueue();
theMaxTimeToSplit = 0.0;
theMaxTimeToMerge = 2.5;
setGrid(new ossimPlanetAdjustableCubeGrid());
theSplitMergeMetricType = DISTANCE_METRIC;
theSplitPixelMetric = 8;
theMergePixelMetric = 4;
setCullAmountType(HIGH_CULL);
}
ossimPlanetTerrain::ossimPlanetTerrain(ossimPlanetGrid* grid)
:theResetRootsFlag(true),
theGrid(grid),
theLastFrameNumber(-1),
theTextureTileWidth(256),
theTextureTileHeight(256),
theElevationTileWidth(9),//2^n + 1
theElevationTileHeight(9), //2^n + 1
theSplitMergeLodScale(3.0),
theElevationExaggeration(1.0),
theMinimumTimeToCompilePerFrame(.003),// 3 milliseconds
thePrecompileEnabledFlag(true),
theElevationEnabledFlag(true),
theFalseEyeFlag(false),
theFalseEye(0.0,0.0,0.0),
thePriorityPointFlag(false),
thePriorityPoint(0.0,0.0,0.0)
{
theElevationCacheShrinkOperation = new ossimPlanetImageCacheShrinkOperation;
theCacheShrinkThreadQueue = new ossimPlanetOperationThreadQueue;
theElevationLayer = new ossimPlanetElevationDatabaseGroup;
theElevationLayer->setFillNullWithGeoidOffsetFlag(true);
theElevationLayer->setGeoRefModel(theModel.get());
theLastApplyToGraphFrameNumber = -1;
theMaxNumberOfOperationsToApplyToGraphPerFrame= 5;
theTextureCallback = new ossimPlanetTerrain::TextureCallback(this);
theTerrainTechnique = new ossimPlanetTerrainGeometryTechnique();
theTextureLayers.push_back(new ossimPlanetTextureLayerGroup());
theTextureLayers[0]->addCallback(theTextureCallback.get());
theElevationQueue = new ossimPlanetTileRequestThreadQueue;
theTextureQueue = new ossimPlanetTileRequestThreadQueue;
// make these support priority queues
//
theSplitQueue = new ossimPlanetTileRequestThreadQueue();
theMergeQueue = new ossimPlanetTileRequestQueue();
theMaxTimeToSplit = 0.0;
theMaxTimeToMerge = 2.5;
theSplitMergeMetricType = DISTANCE_METRIC;
theSplitPixelMetric = 8;
theMergePixelMetric = 4;
setCullAmountType(HIGH_CULL);
}
ossimPlanetTerrain::~ossimPlanetTerrain()
{
theTextureLayers[0]->removeCallback(theTextureCallback.get());
if(theElevationQueue.valid())
{
std::lock_guard<std::recursive_mutex> lockElevationQueue(theElevationQueueMutex);
theElevationQueue->removeAllOperations();
theElevationQueue->cancel();
theElevationQueue = 0;
}
if(theTextureQueue.valid())
{
std::lock_guard<std::recursive_mutex> lockTextureQueue(theTextureQueueMutex);
theTextureQueue->removeAllOperations();
theTextureQueue->cancel();
theTextureQueue = 0;
}
if(theSplitQueue.valid())
{
std::lock_guard<std::recursive_mutex> lockSplitQueue(theSplitQueueMutex);
theSplitQueue->removeAllOperations();
theSplitQueue->cancel();
theSplitQueue = 0;
}
if(theMergeQueue.valid())
{
std::lock_guard<std::recursive_mutex> lockMergeQueue(theMergeQueueMutex);
theMergeQueue->removeAllOperations();
theMergeQueue = 0;
}
theNeedToCompileQueue.clear();
theReadyToApplyToGraphQueue.clear();
theReadyToApplyToGraphNewNodesQueue.clear();
{
osg::Group::removeChildren(0, getNumChildren());
//std::lock_guard<std::recursive_mutex> lockTileSet(theTileSetMutex);
theTileSet.clear();
}
if(theElevationCache.valid())
{
theElevationCache->clean();
theElevationCache = 0;
}
}
void ossimPlanetTerrain::setTerrainTechnique(ossimPlanetTerrainTechnique* technique)
{
std::lock_guard<std::mutex> lock(thePropertyMutex);
theResetRootsFlag = true;
theTerrainTechnique = technique;
}
ossimPlanetTerrainTechnique* ossimPlanetTerrain::newTechnique()
{
ossimPlanetTerrainTechnique* result = 0;
if(theTerrainTechnique.valid())
{
theTerrainTechnique->setGrid(theGrid.get());
if(thePlanet)
{
theTerrainTechnique->setModel(thePlanet->model().get());
}
result = (ossimPlanetTerrainTechnique*)theTerrainTechnique->clone(osg::CopyOp::SHALLOW_COPY);
}
return result;
}
void ossimPlanetTerrain::setElevationEnabledFlag(bool flag)
{
bool refresh = elevationEnabledFlag()!=flag;
{
std::lock_guard<std::mutex> lock(thePropertyMutex);
theElevationEnabledFlag = flag;
}
if(refresh)
{
elevationLayer()->setEnableFlag(theElevationEnabledFlag);
theElevationCache->setEnabledFlag(flag);
}
}
bool ossimPlanetTerrain::elevationEnabledFlag()const
{
std::lock_guard<std::mutex> lock(thePropertyMutex);
return theElevationEnabledFlag;
}
void ossimPlanetTerrain::setDatabasePager(osgDB::DatabasePager* pager)
{
thePager = pager;
}
void ossimPlanetTerrain::initElevation()
{
#if 1
ossim_uint32 numberOfDatabases = ossimElevManager::instance()->getNumberOfElevationDatabases();
ossim_uint32 idx = 0;
for(idx = 0; idx < numberOfDatabases; ++idx)
{
ossimRefPtr<ossimElevationDatabase> database = ossimElevManager::instance()->getElevationDatabase(idx);
if(database.valid())
{
ossimPlanetOssimElevationDatabase* planetDatabase = new ossimPlanetOssimElevationDatabase;
planetDatabase->setDatabase(database.get());
addElevation(planetDatabase);
}
}
#else
ossim_uint32 idx = 0;
ossim_uint32 numberOfDatabases = ossimElevManager::instance()->getNumberOfElevationDatabases();
for(idx = 0; idx < numberOfDatabases; ++idx)
{
const ossimRefPtr<ossimElevationDatabase> database = ossimElevManager::instance()->getElevationDatabase(idx);
if(database.valid())
{
ossimFilename directory = ossimFilename(database->getConnectionString());
addElevation(directory, false);
}
}
if(theElevationLayer.valid())
{
theElevationLayer->sortByGsd();
}
#endif
}
bool ossimPlanetTerrain::addElevation(const ossimFilename& file, bool sortFlag)
{
osg::ref_ptr<ossimPlanetElevationDatabase> database = ossimPlanetElevationRegistry::instance()->openDatabase(file);
return addElevation(database.get(), sortFlag);
}
bool ossimPlanetTerrain::addElevation(osg::ref_ptr<ossimPlanetElevationDatabase> database, bool sortFlag)
{
bool result = false;
if(database.valid()&&theElevationLayer.valid())
{
database->setGeoRefModel(theModel.get());
theElevationLayer->addBottom(database.get());
result = true;
if(sortFlag)
{
// make sure the highest accuracy is on top
theElevationLayer->sortByGsd();
}
}
return result;
}
void ossimPlanetTerrain::setNumberOfTextureLayers(ossim_uint32 size)
{
TextureLayers temp = theTextureLayers;
theTextureLayers.resize(size);
ossim_uint32 idx = 0;
ossim_uint32 minBound = ossim::min(size, (ossim_uint32)temp.size());
for(idx = 0; idx < minBound;++idx)
{
theTextureLayers[idx] = temp[idx];
}
resetImageLayers();
}
bool ossimPlanetTerrain::setTextureLayer(ossim_uint32 idx,
ossimPlanetTextureLayer* layer)
{
bool result = true;
if(idx < theTextureLayers.size())
{
if(theTextureLayers[idx].valid())
{
theTextureLayers[idx]->removeCallback(theTextureCallback.get());
}
theTextureLayers[idx] = layer;
if(layer)
{
layer->addCallback(theTextureCallback.get());
}
refreshImageLayers();
}
else if(idx == theTextureLayers.size())
{
theTextureLayers.push_back(layer);
if(layer)
{
layer->addCallback(theTextureCallback.get());
}
refreshImageLayers();
}
else
{
result = false;
}
return result;
}
ossim_uint32 ossimPlanetTerrain::numberOfTextureLayers()const
{
return theTextureLayers.size();
}
ossimPlanetTextureLayer* ossimPlanetTerrain::textureLayer(ossim_uint32 idx)
{
if(idx < theTextureLayers.size())
{
return theTextureLayers[idx].get();
}
return 0;
}
ossimPlanetElevationDatabaseGroup* ossimPlanetTerrain::elevationLayer()
{
return theElevationLayer.get();
}
const ossimPlanetElevationDatabaseGroup* ossimPlanetTerrain::elevationLayer()const
{
return theElevationLayer.get();
}
void ossimPlanetTerrain::traverse(osg::NodeVisitor &nv)
{
// first mark any tile for refresh
{
std::lock_guard<std::mutex> lock(thePropertyMutex);
if(theElevationCache.valid()&&theElevationCache->exceedsMaxCacheSize())
{
if(theElevationCacheShrinkOperation->referenceCount() == 1)
{
theElevationCacheShrinkOperation->reset();
theElevationCacheShrinkOperation->setCache(theElevationCache.get());
theCacheShrinkThreadQueue->add(theElevationCacheShrinkOperation.get());
}
}
}
// osgUtil::IntersectionVisitor* iv = dynamic_cast<osgUtil::IntersectionVisitor*>(&nv);
// if(iv)
// {
// iv->setUseKdTreeWhenAvailable(true);
// }
// osg::Timer_t tick = osg::Timer::instance()->tick();
int savedCullSettings = 0;
// int savedCullMask = 0;
osgUtil::CullVisitor* cv = dynamic_cast<osgUtil::CullVisitor*>(&nv);
if(cv)
{
// savedCullMask = cv->getCurrentCullingSet().getCullingMask();
savedCullSettings = cv->getCullingMode();
cv->getCurrentCullingSet().setCullingMask((osg::CullingSet::MaskValues)theCullSettings);
cv->setCullingMode(theCullSettings);
}
// bool frameNumberChanged = false;
if(nv.getFrameStamp())
{
// frameNumberChanged = nv.getFrameStamp()->getFrameNumber() != theLastFrameNumber;
theLastFrameNumber = nv.getFrameStamp()->getFrameNumber();
}
switch(nv.getVisitorType())
{
case osg::NodeVisitor::EVENT_VISITOR:
{
return;
}
case osg::NodeVisitor::UPDATE_VISITOR:
{
refreshExtents();
theTextureQueue->setCurrentFrameNumber(theLastFrameNumber);
theElevationQueue->setCurrentFrameNumber(theLastFrameNumber);
theSplitQueue->setCurrentFrameNumber(theLastFrameNumber);
theMergeQueue->setCurrentFrameNumber(theLastFrameNumber);
theTextureQueue->operationQueue()->removeStoppedOperations();
theElevationQueue->operationQueue()->removeStoppedOperations();
// osg::Timer_t startTick = osg::Timer::instance()->tick();
// double delta =0.0;
if(resetRootsFlag())
{
buildRoot();
}
bool needToRedraw = (!theTextureQueue->empty()||
!theElevationQueue->empty()||
!theSplitQueue->empty());
{
std::lock_guard<std::recursive_mutex> lock(theReadyToApplyToGraphQueueMutex);
if(!theReadyToApplyToGraphQueue.empty()||
!theReadyToApplyToGraphNewNodesQueue.empty())
{
needToRedraw = true;
}
}
{
std::lock_guard<std::recursive_mutex> lock(theNeedToCompileQueueMutex);
if(!theNeedToCompileQueue.empty())
{
needToRedraw = true;
}
}
if(needToRedraw)
{
setRedrawFlag(true); // request a new frame if not empty
}
pruneNeedToCompileAndAddToGraphThreadQueues();
removeTerrainChildren();
if(nv.getFrameStamp()&&(nv.getFrameStamp()->getFrameNumber()!=theLastApplyToGraphFrameNumber))
{
applyRequestsToGraph(1.25);
theLastApplyToGraphFrameNumber = nv.getFrameStamp()->getFrameNumber();
}
break;
}
default:
{
break;
}
}
#if 0
ossim_uint32 idx = 0;
CountVisitor count;
for(idx = 0; idx < getNumChildren(); ++idx)
{
getChild(idx)->accept(count);
}
std::cout << "CULL COUNT ===== " << coun std::cout << "NODE COUNT ===== " << count.theNodeCount << std::endl;
t.theCullCount << std::endl;
#endif
ossimPlanetLayer::traverse(nv);
if(cv)
{
cv->getCurrentCullingSet().setCullingMask((osg::CullingSet::MaskValues) savedCullSettings);
cv->setCullingMode( (osg::CullSettings::CullingModeValues) savedCullSettings);
}
//std::cout << "f = " << theCurrentFrameNumber << std::endl;
if((nv.getVisitorType() == osg::NodeVisitor::CULL_VISITOR))
{
RemoveChildrenFromGraphVisitor visitor(this, nv.getFrameStamp()->getFrameNumber());
ossim_uint32 idx = 0;
ossim_uint32 maxIdx = getNumChildren();
for(idx = 0; idx < maxIdx; ++idx)
{
getChild(idx)->accept(visitor);
}
}
}
void ossimPlanetTerrain::setGrid(ossimPlanetGrid* grid)
{
std::lock_guard<std::mutex> lock(thePropertyMutex);
theResetRootsFlag = true;
theGrid = grid;
}
const ossimPlanetGrid* ossimPlanetTerrain::grid()const
{
std::lock_guard<std::mutex> lock(thePropertyMutex);
return theGrid.get();
}
ossimPlanetGrid* ossimPlanetTerrain::grid()
{
std::lock_guard<std::mutex> lock(thePropertyMutex);
return theGrid.get();
}
void ossimPlanetTerrain::removeTerrainTileFromGraph(ossimPlanetTerrainTile* tile)
{
removeTerrainChildren(tile);
}
void ossimPlanetTerrain::removeTerrainChildren(ossimPlanetTerrainTile* tile)
{
if(tile)
{
theChildrenToRemoveMutex.lock();
osg::ref_ptr<ossimPlanetTerrainTile> currentTile = tile;
// flatten graph to a single list of children
//
std::queue<osg::ref_ptr<ossimPlanetTerrainTile> > tiles;
ossim_uint32 idx = 0;
for(idx = 0; idx < currentTile->getNumChildren(); ++idx)
{
tiles.push((ossimPlanetTerrainTile*)currentTile->getChild(idx));
}
currentTile->removeChildren(0, currentTile->getNumChildren());
// now let's flatten the graph out and add to the remove tile list
//
while(!tiles.empty())
{
currentTile = tiles.front().get();
currentTile->cancelAllOperations();
tiles.pop();
//currentTile->setState(ossimPlanetTerrainTile::NEED_MERGING);
theChildrenToRemove.push_back(currentTile.get());
for(idx = 0; idx < currentTile->getNumChildren(); ++idx)
{
tiles.push((ossimPlanetTerrainTile*)currentTile->getChild(idx));
}
currentTile->removeChildren(0, currentTile->getNumChildren());
}
theChildrenToRemoveMutex.unlock();
}
}
void ossimPlanetTerrain::requestSplit(ossimPlanetTerrainTile* tile,
ossim_float64 priority,
const osg::FrameStamp* framestamp,
ossimPlanetOperation* request)
{
if(theResetRootsFlag) return;
ossimPlanetTileRequest* tileRequest = dynamic_cast<ossimPlanetTileRequest*>(request);
if(tileRequest)
{
if(tileRequest->referenceCount() == 1)
{
tileRequest->setState(ossimPlanetOperation::READY_STATE);
tileRequest->setTimestampFirstRequest(framestamp->getReferenceTime());
tileRequest->setTile(tile);
theSplitQueue->add(tileRequest);
}
tileRequest->setPriority(priority);
tileRequest->setFrameNumberOfLastRequest(framestamp->getFrameNumber());
tileRequest->setTimestampLastRequest(framestamp->getReferenceTime());
}
}
void ossimPlanetTerrain::requestMerge(ossimPlanetTerrainTile* tile,
ossim_float64 priority,
const osg::FrameStamp* framestamp,
ossimPlanetOperation* request)
{
ossimPlanetTileRequest* tileRequest = dynamic_cast<ossimPlanetTileRequest*>(request);
if(tileRequest)
{
tileRequest->reset();
tileRequest->setTile(tile);
tileRequest->setPriority(priority);
tileRequest->setFrameNumberOfLastRequest(framestamp->getFrameNumber());
theMergeQueue->add(tileRequest);
}
}
void ossimPlanetTerrain::requestTexture(ossimPlanetTerrainTile* tile,
ossim_float64 priority,
const osg::FrameStamp* framestamp,
const std::vector<ossim_uint32>& indices,
ossimPlanetOperation* request)
{
if(theResetRootsFlag) return;
ossimPlanetTextureRequest* tileRequest = dynamic_cast<ossimPlanetTextureRequest*>(request);
if(tileRequest)
{
if(tileRequest->referenceCount() == 1)
{
tileRequest->reset();
tileRequest->setTimestampFirstRequest(framestamp->getReferenceTime());
tileRequest->setTile(tile);
tileRequest->setTextureLayerIndices(indices);
theTextureQueue->add(tileRequest);
}
tileRequest->setPriority(priority);
tileRequest->setFrameNumberOfLastRequest(framestamp->getFrameNumber());
tileRequest->setTimestampLastRequest(framestamp->getReferenceTime());
}
}
void ossimPlanetTerrain::requestElevation(ossimPlanetTerrainTile* tile,
ossim_float64 priority,
const osg::FrameStamp* framestamp,
ossimPlanetOperation* request)
{
if(theResetRootsFlag) return;
ossimPlanetTileRequest* tileRequest = dynamic_cast<ossimPlanetTileRequest*>(request);
if(tileRequest)
{
if(tileRequest->referenceCount() == 1)
{
tileRequest->reset();
tileRequest->setTile(tile);
tileRequest->setTimestampFirstRequest(framestamp->getReferenceTime());
theElevationQueue->add(tileRequest);
}
tileRequest->setPriority(priority);
tileRequest->setFrameNumberOfLastRequest(framestamp->getFrameNumber());
tileRequest->setTimestampLastRequest(framestamp->getReferenceTime());
}
}
void ossimPlanetTerrain::compileGLObjects(osg::State& state, double compileTime)
{
std::lock_guard<std::recursive_mutex> lock(theNeedToCompileQueueMutex);
osg::Timer_t startT = osg::Timer::instance()->tick();
double delta = 0.0;
double deltaNextTest = 0.0;
double diff = 0.0;
bool done = theNeedToCompileQueue.empty();
if(!done)
{
setRedrawFlag(true);
}
osg::RenderInfo renderInfo;
renderInfo.setState(&state);
while(!done)
{
// returns false if no more objects in the request need compiling
if(theNeedToCompileQueue.front()->compileObjects(renderInfo, compileTime))
{
addRequestToReadyToApplyQueue(theNeedToCompileQueue.front().get());
theNeedToCompileQueue.pop_front();
}
osg::Timer_t testT = osg::Timer::instance()->tick();
delta = osg::Timer::instance()->delta_s(startT, testT);
diff = delta - deltaNextTest;
if((delta > (compileTime-diff))||
theNeedToCompileQueue.empty())
{
done = true;
}
deltaNextTest = delta;
}
}
bool ossimPlanetTerrain::resetRootsFlag()const
{
std::lock_guard<std::mutex> lock(thePropertyMutex);
return theResetRootsFlag;
}
void ossimPlanetTerrain::buildRoot()
{
if(!theGrid.valid()) return;
theReadyToApplyToGraphQueue.clear();
theReadyToApplyToGraphNewNodesQueue.clear();
theNeedToCompileQueue.clear();
theSplitQueue->removeAllOperations();
theElevationQueue->removeAllOperations();
theTextureQueue->removeAllOperations();
bool hasActiveOperations = false;
{
std::lock_guard<std::recursive_mutex> lock(theTileSetMutex);
TileSet::iterator iter = theTileSet.begin();
while(iter != theTileSet.end())
{
(*iter)->cancelAllOperations();
if((*iter)->hasActiveOperations())
{
hasActiveOperations = true;
}
++iter;
}
if(!hasActiveOperations)
{
theTileSet.clear();
removeChildren(0, getNumChildren());
}
}
if(!hasActiveOperations)
{
ossimPlanetGrid::TileIds rootIds;
theGrid->getRootIds(rootIds);
ossim_uint32 idx = 0;
for(idx = 0; idx < rootIds.size(); ++idx)
{
ossimPlanetTerrainTile* tile = new ossimPlanetTerrainTile(rootIds[idx]);
tile->setTerrain(this);
tile->init();
addChild(tile);
}
theResetRootsFlag = false;
setRedrawFlag(true);
}
}
ossimPlanetTerrain* ossimPlanetTerrain::findTerrain(osg::NodePath& currentNodePath)
{
if(currentNodePath.empty())
{
return 0;
}
for(osg::NodePath::reverse_iterator itr = currentNodePath.rbegin();
itr != currentNodePath.rend();
++itr)
{
ossimPlanetTerrain* ts = dynamic_cast<ossimPlanetTerrain*>(*itr);
if (ts)
{
return ts;
}
}
return 0;
}
double ossimPlanetTerrain::maxTimeToSplit()const
{
return theMaxTimeToSplit;
}
double ossimPlanetTerrain::maxTimeToMerge()const
{
return theMaxTimeToMerge;
}
void ossimPlanetTerrain::registerTile(ossimPlanetTerrainTile* tile)
{
{
std::lock_guard<std::recursive_mutex> lock(theTileSetMutex);
if(tile)
{
theTileSet.insert(tile);
}
}
}
void ossimPlanetTerrain::unregisterTile(ossimPlanetTerrainTile* tile)
{
{
std::lock_guard<std::recursive_mutex> lock(theTileSetMutex);
TileSet::iterator iter = theTileSet.find(tile);
if(iter != theTileSet.end())
{
theTileSet.erase(iter);
}
}
}
ossimPlanetTerrainTile* ossimPlanetTerrain::findTile(const ossimPlanetTerrainTileId& id)
{
#if 0
std::lock_guard<std::recursive_mutex> lock(theTileSetMapMutex);
TileSetMap::iterator iter = theTileSetMap.find(id);
if(iter != theTileSetMap.end())
{
return iter->second;
}
#endif
return 0;
}
const ossimPlanetTerrainTile* ossimPlanetTerrain::findTile(const ossimPlanetTerrainTileId& id)const
{
#if 0
std::lock_guard<std::recursive_mutex> lock(theTileSetMapMutex);
TileSetMap::const_iterator iter = theTileSetMap.find(id);
if(iter != theTileSetMap.end())
{
return iter->second;
}
#endif
return 0;
}
void ossimPlanetTerrain::refreshImageAndElevationLayers(ossimPlanetExtents* extents)
{
refreshImageLayers(extents);
refreshElevationLayers(extents);
#if 0
std::lock_guard<std::recursive_mutex> lock(theTileSetMutex);
TileSet::iterator iter = theTileSet.begin();
bool imageIntersects = true;
bool elevationIntersects = true;
osg::ref_ptr<ossimPlanetExtents> imageExtent = new ossimPlanetExtents;
osg::ref_ptr<ossimPlanetExtents> elevExtent = new ossimPlanetExtents;
ossim_uint32 idx;
while(iter != theTileSet.end())
{
ossim_uint32 bound = (*iter)->numberOfImageLayers();
if(extents)
{
theGrid->convertToGeographicExtents((*iter)->tileId(),
*imageExtent,
textureTileWidth(),
textureTileHeight());
theGrid->convertToGeographicExtents((*iter)->tileId(),
*elevExtent,
elevationTileWidth(),
elevationTileHeight());
if(extents->intersectsLatLon(*imageExtent.get())&&
extents->intersectsScale(*imageExtent.get()))
{
imageIntersects = true;
}
else
{
imageIntersects = false;
}
if(extents->intersectsLatLon(*elevExtent.get()))
{
elevationIntersects = true;
}
else
{
elevationIntersects = false;
}
}
if(elevationIntersects)
{
(*iter)->elevationLayer()->setRefreshFlag(true);
(*iter)->elevationLayer()->setNoMoreDataFlag(false);
}
if(imageIntersects)
{
for(idx = 0; idx < bound; ++idx)
{
(*iter)->imageLayer(idx)->setRefreshFlag(true);
(*iter)->imageLayer(idx)->setNoMoreDataFlag(false);
if(textureLayer(idx)&&((*iter)->tileId().level()>0))
{
bool hasDataFlag = textureLayer(idx)->hasTexture(textureTileWidth(),
textureTileHeight(),
(*iter)->tileId(),
*grid());
(*iter)->imageLayer(idx)->setNoMoreDataFlag(!hasDataFlag);
}
}
}
++iter;
}
setRedrawFlag(true);
#endif
}
void ossimPlanetTerrain::refreshImageLayers(ossimPlanetExtents* extents)
{
std::lock_guard<std::recursive_mutex> lock(theRefreshExtentsMutex);
if(theRefreshImageExtent.valid())
{
if(extents)
{
theRefreshImageExtent->combine(extents);
}
}
else if(extents)
{
theRefreshImageExtent = new ossimPlanetExtents(*extents);
}
else
{
theRefreshImageExtent = new ossimPlanetExtents();
}
setRedrawFlag(true);
}
void ossimPlanetTerrain::refreshElevationLayers(ossimPlanetExtents* extents)
{
std::lock_guard<std::recursive_mutex> lock(theRefreshExtentsMutex);
if(theRefreshElevationExtent.valid())
{
if(extents)
{
theRefreshElevationExtent->combine(extents);
}
}
else if(extents)
{
theRefreshElevationExtent = new ossimPlanetExtents(*extents);
}
else
{
theRefreshElevationExtent = new ossimPlanetExtents();
}
setRedrawFlag(true);
}
void ossimPlanetTerrain::refreshExtents()
{
{
std::lock_guard<std::recursive_mutex> lock(theRefreshExtentsMutex);
std::lock_guard<std::recursive_mutex> lock2(theTileSetMutex);
if(!theRefreshElevationExtent.valid()&&
!theRefreshImageExtent.valid())
{
return;
}
ossim_uint32 idx = 0;
TileSet::iterator iter = theTileSet.begin();
osg::ref_ptr<ossimPlanetExtents> tileExtent = new ossimPlanetExtents;
while(iter != theTileSet.end())
{
theGrid->convertToGeographicExtents((*iter)->tileId(),
*tileExtent,
textureTileWidth(),
textureTileHeight());
if(theRefreshImageExtent.valid())
{
if(theRefreshImageExtent->intersectsLatLon(*tileExtent.get()))//&&
// theRefreshImageExtent->intersectsScale(*tileExtent.get()))
{
(*iter)->textureRequest()->cancel();
ossim_uint32 bound = (*iter)->numberOfImageLayers();
for(idx = 0; idx < bound; ++idx)
{
(*iter)->imageLayer(idx)->setRefreshFlag(true);
(*iter)->imageLayer(idx)->setNoMoreDataFlag(false);
if(textureLayer(idx)&&((*iter)->tileId().level()>0))
{
bool hasDataFlag = textureLayer(idx)->hasTexture(textureTileWidth(),
textureTileHeight(),
(*iter)->tileId(),
*grid());
(*iter)->imageLayer(idx)->setNoMoreDataFlag(!hasDataFlag);
}
}
}
}
if(theRefreshElevationExtent.valid())
{
if(theRefreshElevationExtent->intersectsLatLon(*tileExtent.get()))
{
(*iter)->elevationRequest()->cancel();
(*iter)->elevationLayer()->setRefreshFlag(true);
(*iter)->elevationLayer()->setNoMoreDataFlag(false);
if(elevationLayer()&&((*iter)->tileId().level()>0))
{
#if 0
bool hasDataFlag = elevationLayer()->hasTexture(elevationTileWidth(),
elevationTileHeight(),
(*iter)->tileId(),
*grid());
(*iter)->elevationLayer()->setNoMoreDataFlag(!hasDataFlag);
#else
(*iter)->elevationLayer()->setNoMoreDataFlag(false);
#endif
}
}
}
++iter;
}
theRefreshElevationExtent = 0;
theRefreshImageExtent = 0;
}
setRedrawFlag(true);
}
void ossimPlanetTerrain::resetImageLayers()
{
std::lock_guard<std::recursive_mutex> lock(theTileSetMutex);
TileSet::iterator iter = theTileSet.begin();
while(iter != theTileSet.end())
{
ossim_uint32 idx = 0;
ossim_uint32 bound = (*iter)->numberOfImageLayers();
for(idx = 0; idx < bound; ++idx)
{
(*iter)->resetImageLayers();
}
++iter;
}
setRedrawFlag(true);
}
void ossimPlanetTerrain::resetGraph()
{
std::lock_guard<std::mutex> lock(thePropertyMutex);
theResetRootsFlag = true;
}
void ossimPlanetTerrain::setModel(ossimPlanetGeoRefModel* model)
{
ossimPlanetLayer::setModel(model);
if(theElevationLayer.valid())
{
theElevationLayer->setGeoRefModel(model);
}
}
void ossimPlanetTerrain::addRequestToReadyToApplyQueue(ossimPlanetTileRequest* request)
{
std::lock_guard<std::recursive_mutex> lock(theReadyToApplyToGraphQueueMutex);
if(dynamic_cast<ossimPlanetSplitRequest*>(request))
{
theReadyToApplyToGraphNewNodesQueue.push_back(request);
}
else
{
theReadyToApplyToGraphQueue.push_back(request);
}
setRedrawFlag(true);
}
void ossimPlanetTerrain::addRequestToNeedToCompileQueue(ossimPlanetTileRequest* request)
{
if(thePager.valid())
{
osg::ref_ptr<osgUtil::IncrementalCompileOperation::CompileSet> compileSet = new osgUtil::IncrementalCompileOperation::CompileSet();
osgUtil::IncrementalCompileOperation* compileOperation = thePager->getIncrementalCompileOperation();
if(compileOperation&&!compileOperation->getContextSet().empty())
{
//osgUtil::StateToCompile stateToCompile(osgUtil::GLObjectsVisitor::COMPILE_DISPLAY_LISTS|osgUtil::GLObjectsVisitor::COMPILE_STATE_ATTRIBUTES);
//compileSet->buildCompileMap(compileOperation->getContextSet());
request->populateCompileSet(compileOperation->getContextSet(), *compileSet.get());
compileSet->_compileCompletedCallback = new ossimPlanetDatabasePagerCompileCompletedCallback(this, request);
compileOperation->add(compileSet.get(), false);
}
else
{
addRequestToReadyToApplyQueue(request);
}
//std::cout << compileOperation << std::endl;
}
}
void ossimPlanetTerrain::applyRequestsToGraph(double maxTime)
{
std::lock_guard<std::recursive_mutex> lock(theReadyToApplyToGraphQueueMutex);
if(theReadyToApplyToGraphQueue.empty()&&theReadyToApplyToGraphNewNodesQueue.empty()) return;
osg::ref_ptr<ossimPlanetTileRequest> request;
bool doneFlag = false;
ossim_uint32 operationCount = 0;
osg::Timer_t startTick = osg::Timer::instance()->tick();
while(!doneFlag)
{
if(!theReadyToApplyToGraphQueue.empty())
{
// theReadyToApplyToGraphQueue.sort(ossimPlanetTileRequest::SortFunctor());
if((*theReadyToApplyToGraphQueue.begin())->isRequestCurrent(theTextureQueue->currentFrameNumber()))
{
(*theReadyToApplyToGraphQueue.begin())->applyToGraph();
++operationCount;
theReadyToApplyToGraphQueue.pop_front();
}
else
{
theReadyToApplyToGraphQueue.pop_front();
}
}
#if 1
if(!theReadyToApplyToGraphNewNodesQueue.empty())
{
//theReadyToApplyToGraphNewNodesQueue.sort(ossimPlanetTileRequest::SortFunctor());
if((*theReadyToApplyToGraphNewNodesQueue.begin())->isRequestCurrent(theTextureQueue->currentFrameNumber()))
{
(*theReadyToApplyToGraphNewNodesQueue.begin())->applyToGraph();
++operationCount;
theReadyToApplyToGraphNewNodesQueue.pop_front();
}
else
{
theReadyToApplyToGraphNewNodesQueue.pop_front();
}
}
#endif
double delta = osg::Timer::instance()->delta_m(startTick, osg::Timer::instance()->tick());
#if 1
doneFlag = ((theReadyToApplyToGraphQueue.empty()&&theReadyToApplyToGraphNewNodesQueue.empty())||
(delta > maxTime)||
(operationCount>=theMaxNumberOfOperationsToApplyToGraphPerFrame));
#else
doneFlag = ((theReadyToApplyToGraphQueue.empty())||
(delta > maxTime)||
(operationCount>=theMaxNumberOfOperationsToApplyToGraphPerFrame));
#endif
}
setRedrawFlag(true);
}
void ossimPlanetTerrain::pruneNeedToCompileAndAddToGraphThreadQueues()
{
{
std::lock_guard<std::recursive_mutex> lock(theReadyToApplyToGraphQueueMutex);
ossimPlanetTileRequest::List::iterator iter = theReadyToApplyToGraphQueue.begin();
while(iter != theReadyToApplyToGraphQueue.end())
{
if(((*iter)->state() == ossimPlanetOperation::CANCELED_STATE)||
(!(*iter)->isRequestCurrent(theTextureQueue->currentFrameNumber())))
{
iter = theReadyToApplyToGraphQueue.erase(iter);
}
else
{
++iter;
}
}
}
#if 1
{
std::lock_guard<std::recursive_mutex> lock(theReadyToApplyToGraphQueueMutex);
ossimPlanetTileRequest::List::iterator iter = theReadyToApplyToGraphNewNodesQueue.begin();
while(iter != theReadyToApplyToGraphNewNodesQueue.end())
{
if(((*iter)->state() == ossimPlanetOperation::CANCELED_STATE)||
(!(*iter)->isRequestCurrent(theTextureQueue->currentFrameNumber())))
{
iter = theReadyToApplyToGraphNewNodesQueue.erase(iter);
}
else
{
++iter;
}
}
}
#endif
{
std::lock_guard<std::recursive_mutex> lock(theNeedToCompileQueueMutex);
ossimPlanetTileRequest::List::iterator iter = theNeedToCompileQueue.begin();
while(iter != theNeedToCompileQueue.end())
{
if(((*iter)->state() == ossimPlanetOperation::CANCELED_STATE)||
(!(*iter)->isRequestCurrent(theTextureQueue->currentFrameNumber())))
{
iter = theNeedToCompileQueue.erase(iter);
}
else
{
++iter;
}
}
}
}
void ossimPlanetTerrain::removeTerrainChildren(double maxTime)
{
std::lock_guard<std::recursive_mutex> lock(theChildrenToRemoveMutex);
osg::Timer_t startTick = osg::Timer::instance()->tick();
// osgUtil::GLObjectsVisitor visitor(osgUtil::GLObjectsVisitor::RELEASE_DISPLAY_LISTS|
// osgUtil::GLObjectsVisitor::RELEASE_STATE_ATTRIBUTES);
RemoveChildrenList::iterator iter = theChildrenToRemove.begin();
while(iter!=theChildrenToRemove.end())
{
if((*iter)->hasActiveOperations())
{
(*iter)->cancelAllOperations();
++iter;
}
else
{
(*iter)->releaseGLObjects();
iter = theChildrenToRemove.erase(iter);
}
double delta = osg::Timer::instance()->delta_m(startTick, osg::Timer::instance()->tick());
if(delta > maxTime)
{
break;
}
}
if(theChildrenToRemove.size()>0)
{
iter = theChildrenToRemove.begin();
//std::cout << "_____________" << std::endl;
while(iter!=theChildrenToRemove.end())
{
//std::cout << (*iter)->tileId() << std::endl;
// std::cout << "elevationRequest = " << (*iter)->elevationRequest()->referenceCount() << std::endl;
// std::cout << "textureRequest = " << (*iter)->textureRequest()->referenceCount() << std::endl;
// std::cout << "splitRequest = " << (*iter)->splitRequest()->referenceCount() << std::endl;
++iter;
}
//std::cout << "Elevation queue size = " << theElevationQueue->operationQueue()->size() << std::endl;
//std::cout << "List size = " << theChildrenToRemove.size() << std::endl;
}
}
void ossimPlanetTerrain::setMaxNumberOfOperationsToApplyToGraphPerFrame(ossim_uint32 value)
{
theMaxNumberOfOperationsToApplyToGraphPerFrame = value;
}
void ossimPlanetTerrain::setCullAmountType(CullAmountType cullAmount)
{
switch(cullAmount)
{
case NO_CULL:
{
theCullSettings = osg::CullSettings::NO_CULLING;
break;
}
case LOW_CULL:
{
theCullSettings = osg::CullSettings::SMALL_FEATURE_CULLING;
break;
}
case MEDIUM_LOW_CULL:
{
theCullSettings = static_cast<osg::CullSettings::CullingModeValues>(osg::CullSettings::SMALL_FEATURE_CULLING|
osg::CullSettings::CLUSTER_CULLING);
break;
}
case MEDIUM_CULL:
{
theCullSettings = static_cast<osg::CullSettings::CullingModeValues>(osg::CullSettings::SMALL_FEATURE_CULLING|
osg::CullSettings::CLUSTER_CULLING|
osg::CullSettings::VIEW_FRUSTUM_SIDES_CULLING);
break;
}
case MEDIUM_HIGH_CULL:
{
theCullSettings = static_cast<osg::CullSettings::CullingModeValues>(osg::CullSettings::SMALL_FEATURE_CULLING|
osg::CullSettings::CLUSTER_CULLING|
osg::CullSettings::VIEW_FRUSTUM_CULLING);
break;
}
case HIGH_CULL:
{
theCullSettings = static_cast<osg::CullSettings::CullingModeValues>(osg::CullSettings::ENABLE_ALL_CULLING);
break;
}
}
setRedrawFlag(true);
}
void ossimPlanetTerrain::setTextureTileSize(ossim_uint32 width,
ossim_uint32 height)
{
theTextureTileWidth = width;
theTextureTileHeight = height;
}
ossim_uint32 ossimPlanetTerrain::textureTileWidth()const
{
return theTextureTileWidth;
}
ossim_uint32 ossimPlanetTerrain::textureTileHeight()const
{
return theTextureTileHeight;
}
void ossimPlanetTerrain::setElevationTileSize(ossim_uint32 width,
ossim_uint32 height)
{
theElevationTileWidth = width|1; // make sure that it's odd number
theElevationTileHeight = height|1; // make sure that it's an odd number
}
ossim_uint32 ossimPlanetTerrain::elevationTileWidth()const
{
return theElevationTileWidth;
}
ossim_uint32 ossimPlanetTerrain::elevationTileHeight()const
{
return theElevationTileHeight;
}
void ossimPlanetTerrain::setElevationDensityType(ElevationDensityType type)
{
switch(type)
{
case LOW_ELEVATION_DENSITY:
{
setElevationTileSize(9, 9);
break;
}
case MEDIUM_LOW_ELEVATION_DENSITY:
{
setElevationTileSize(17, 17);
break;
}
case MEDIUM_ELEVATION_DENSITY:
{
setElevationTileSize(33, 33);
break;
}
case MEDIUM_HIGH_ELEVATION_DENSITY:
{
setElevationTileSize(65, 65);
break;
}
case HIGH_ELEVATION_DENSITY:
{
setElevationTileSize(129, 129);
break;
}
}
if(theElevationCache.valid())
{
theElevationCache->clean();
}
}
void ossimPlanetTerrain::setTextureDensityType(TextureDensityType type)
{
switch(type)
{
case LOW_TEXTURE_DENSITY:
{
setTextureTileSize(64, 64);
break;
}
case MEDIUM_LOW_TEXTURE_DENSITY:
{
setTextureTileSize(128, 128);
break;
}
case MEDIUM_TEXTURE_DENSITY:
{
setTextureTileSize(256, 256);
break;
}
case MEDIUM_HIGH_TEXTURE_DENSITY:
{
setTextureTileSize(512, 512);
break;
}
case HIGH_TEXTURE_DENSITY:
{
setTextureTileSize(1024, 1024);
break;
}
}
}
ossimPlanetTerrain::ElevationDensityType ossimPlanetTerrain::elevationDensityType()const
{
ossim_int32 size = ossim::max(elevationTileHeight(), elevationTileWidth());
if(size <=9)
{
return LOW_ELEVATION_DENSITY;
}
else if(size <=17)
{
return MEDIUM_LOW_ELEVATION_DENSITY;
}
else if(size <=33)
{
return MEDIUM_ELEVATION_DENSITY;
}
else if(size <=64)
{
return MEDIUM_HIGH_ELEVATION_DENSITY;
}
return HIGH_ELEVATION_DENSITY;
}
ossimPlanetTerrain::TextureDensityType ossimPlanetTerrain::textureDensityType()const
{
ossim_int32 size = ossim::max(textureTileWidth(), textureTileHeight());
if(size <=64)
{
return LOW_TEXTURE_DENSITY;
}
else if(size <=128)
{
return MEDIUM_LOW_TEXTURE_DENSITY;
}
else if(size <=256)
{
return MEDIUM_TEXTURE_DENSITY;
}
else if(size <=512)
{
return MEDIUM_HIGH_TEXTURE_DENSITY;
}
return HIGH_TEXTURE_DENSITY;
}
void ossimPlanetTerrain::setSplitMergePixelMetricParameters(ossim_float64 mergeMetric,
ossim_float64 splitMetric)
{
theSplitPixelMetric = splitMetric;
theMergePixelMetric = mergeMetric;
}
void ossimPlanetTerrain::setSplitMergeMetricType(SplitMergeMetricType type)
{
theSplitMergeMetricType = type;
}
ossimPlanetTerrain::SplitMergeMetricType ossimPlanetTerrain::splitMergeMetricType()const
{
return theSplitMergeMetricType;
}
ossim_float64 ossimPlanetTerrain::splitPixelMetric()const
{
return theSplitPixelMetric;
}
ossim_float64 ossimPlanetTerrain::mergePixelMetric()const
{
return theMergePixelMetric;
}
void ossimPlanetTerrain::setSplitMergeSpeedType(SplitMergeSpeedType type)
{
switch(type)
{
case LOW_SPEED:
{
setSplitMergeLodScale(1.5);
theSplitPixelMetric = 16;
theMergePixelMetric = 8;
break;
}
case MEDIUM_LOW_SPEED:
{
setSplitMergeLodScale(3.0);
theSplitPixelMetric = 10;
theMergePixelMetric = 5;
break;
}
case MEDIUM_SPEED:
{
setSplitMergeLodScale(5.0);
theSplitPixelMetric = 8;
theMergePixelMetric = 4;
break;
}
case MEDIUM_HIGH_SPEED:
{
setSplitMergeLodScale(6.5);
theSplitPixelMetric = 6;
theMergePixelMetric = 3;
break;
}
case HIGH_SPEED:
{
setSplitMergeLodScale(8.0);
theSplitPixelMetric = 4;
theMergePixelMetric = 2;
break;
}
}
}
void ossimPlanetTerrain::setSplitMergeLodScale(ossim_float64 ratio)
{
theSplitMergeLodScale = ratio;
}
ossim_float64 ossimPlanetTerrain::splitMergeLodScale()const
{
return theSplitMergeLodScale;
}
void ossimPlanetTerrain::setElevationExaggeration(ossim_float64 exaggeration)
{
theElevationExaggeration = exaggeration;
}
ossim_float64 ossimPlanetTerrain::elevationExaggeration()const
{
return theElevationExaggeration;
}
void ossimPlanetTerrain::setMinimumTimeToCompilePerFrameInSeconds(double timeInSeconds)
{
theMinimumTimeToCompilePerFrame = timeInSeconds;
}
ossim_float64 ossimPlanetTerrain::minimumTimeToCompilePerFrame()const
{
return theMinimumTimeToCompilePerFrame;
}
void ossimPlanetTerrain::setPrecompileEnabledFlag(bool flag)
{
thePrecompileEnabledFlag = flag;
}
bool ossimPlanetTerrain::precompileEnabledFlag()const
{
return thePrecompileEnabledFlag;
}
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: Valve.VR.IVRRenderModels
#include "Valve/VR/IVRRenderModels.hpp"
// Including type: System.MulticastDelegate
#include "System/MulticastDelegate.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: Valve::VR
namespace Valve::VR {
// Forward declaring type: EVRRenderModelError
struct EVRRenderModelError;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: IAsyncResult
class IAsyncResult;
// Forward declaring type: AsyncCallback
class AsyncCallback;
}
// Completed forward declares
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::Valve::VR::IVRRenderModels::_GetRenderModelErrorNameFromEnum);
DEFINE_IL2CPP_ARG_TYPE(::Valve::VR::IVRRenderModels::_GetRenderModelErrorNameFromEnum*, "Valve.VR", "IVRRenderModels/_GetRenderModelErrorNameFromEnum");
// Type namespace: Valve.VR
namespace Valve::VR {
// Size: 0x70
#pragma pack(push, 1)
// Autogenerated type: Valve.VR.IVRRenderModels/Valve.VR._GetRenderModelErrorNameFromEnum
// [TokenAttribute] Offset: FFFFFFFF
// [UnmanagedFunctionPointerAttribute] Offset: 12087A0
class IVRRenderModels::_GetRenderModelErrorNameFromEnum : public ::System::MulticastDelegate {
public:
// public System.Void .ctor(System.Object object, System.IntPtr method)
// Offset: 0x2215480
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static IVRRenderModels::_GetRenderModelErrorNameFromEnum* New_ctor(::Il2CppObject* object, ::System::IntPtr method) {
static auto ___internal__logger = ::Logger::get().WithContext("::Valve::VR::IVRRenderModels::_GetRenderModelErrorNameFromEnum::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<IVRRenderModels::_GetRenderModelErrorNameFromEnum*, creationType>(object, method)));
}
// public System.IntPtr Invoke(Valve.VR.EVRRenderModelError error)
// Offset: 0x2215490
::System::IntPtr Invoke(::Valve::VR::EVRRenderModelError error);
// public System.IAsyncResult BeginInvoke(Valve.VR.EVRRenderModelError error, System.AsyncCallback callback, System.Object object)
// Offset: 0x2215708
::System::IAsyncResult* BeginInvoke(::Valve::VR::EVRRenderModelError error, ::System::AsyncCallback* callback, ::Il2CppObject* object);
// public System.IntPtr EndInvoke(System.IAsyncResult result)
// Offset: 0x2215794
::System::IntPtr EndInvoke(::System::IAsyncResult* result);
}; // Valve.VR.IVRRenderModels/Valve.VR._GetRenderModelErrorNameFromEnum
#pragma pack(pop)
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: Valve::VR::IVRRenderModels::_GetRenderModelErrorNameFromEnum::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: Valve::VR::IVRRenderModels::_GetRenderModelErrorNameFromEnum::Invoke
// Il2CppName: Invoke
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::IntPtr (Valve::VR::IVRRenderModels::_GetRenderModelErrorNameFromEnum::*)(::Valve::VR::EVRRenderModelError)>(&Valve::VR::IVRRenderModels::_GetRenderModelErrorNameFromEnum::Invoke)> {
static const MethodInfo* get() {
static auto* error = &::il2cpp_utils::GetClassFromName("Valve.VR", "EVRRenderModelError")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Valve::VR::IVRRenderModels::_GetRenderModelErrorNameFromEnum*), "Invoke", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{error});
}
};
// Writing MetadataGetter for method: Valve::VR::IVRRenderModels::_GetRenderModelErrorNameFromEnum::BeginInvoke
// Il2CppName: BeginInvoke
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::IAsyncResult* (Valve::VR::IVRRenderModels::_GetRenderModelErrorNameFromEnum::*)(::Valve::VR::EVRRenderModelError, ::System::AsyncCallback*, ::Il2CppObject*)>(&Valve::VR::IVRRenderModels::_GetRenderModelErrorNameFromEnum::BeginInvoke)> {
static const MethodInfo* get() {
static auto* error = &::il2cpp_utils::GetClassFromName("Valve.VR", "EVRRenderModelError")->byval_arg;
static auto* callback = &::il2cpp_utils::GetClassFromName("System", "AsyncCallback")->byval_arg;
static auto* object = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Valve::VR::IVRRenderModels::_GetRenderModelErrorNameFromEnum*), "BeginInvoke", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{error, callback, object});
}
};
// Writing MetadataGetter for method: Valve::VR::IVRRenderModels::_GetRenderModelErrorNameFromEnum::EndInvoke
// Il2CppName: EndInvoke
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::IntPtr (Valve::VR::IVRRenderModels::_GetRenderModelErrorNameFromEnum::*)(::System::IAsyncResult*)>(&Valve::VR::IVRRenderModels::_GetRenderModelErrorNameFromEnum::EndInvoke)> {
static const MethodInfo* get() {
static auto* result = &::il2cpp_utils::GetClassFromName("System", "IAsyncResult")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Valve::VR::IVRRenderModels::_GetRenderModelErrorNameFromEnum*), "EndInvoke", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result});
}
};
|
/*
//@HEADER
// ************************************************************************
//
// Kokkos v. 3.0
// Copyright (2020) National Technology & Engineering
// Solutions of Sandia, LLC (NTESS).
//
// Under the terms of Contract DE-NA0003525 with NTESS,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY NTESS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL NTESS OR THE
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Questions? Contact Siva Rajamanickam (srajama@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
/// \file KokkosSparse_sptrsv.hpp
/// \brief Parallel sparse triangular solve
///
/// This file provides KokkosSparse::sptrsv. This function performs a
/// local (no MPI) sparse triangular solve on matrices stored in
/// compressed row sparse ("Crs") format.
#ifndef KOKKOSSPARSE_SPTRSV_SUPERNODE_HPP_
#define KOKKOSSPARSE_SPTRSV_SUPERNODE_HPP_
// trmm & trtri are called on Host
#if defined(KOKKOSKERNELS_ENABLE_TPL_BLAS)
#include "KokkosBlas3_trmm.hpp"
#include "KokkosBlas_trtri.hpp"
#include "KokkosBatched_Trtri_Decl.hpp"
#include "KokkosBatched_Trtri_Serial_Impl.hpp"
#include "KokkosBatched_Trmm_Decl.hpp"
#include "KokkosBatched_Trmm_Serial_Impl.hpp"
#include "KokkosSparse_sptrsv.hpp"
namespace KokkosSparse {
namespace Experimental {
template<typename ordinal_type>
class sort_indices {
public:
sort_indices(ordinal_type* rowinds) : rowinds_(rowinds){}
bool operator()(int i, int j) const { return rowinds_[i] < rowinds_[j]; }
private:
ordinal_type* rowinds_; // rowindices
};
/* ========================================================================================= */
template <typename host_graph_t, typename graph_t>
graph_t deep_copy_graph (host_graph_t &host_graph) {
// load graph on host
auto row_map = host_graph.row_map;
auto entries = host_graph.entries;
auto nrows = host_graph.numRows ();
auto nnz = row_map (nrows);
// create graph on device
using row_map_view_t = typename graph_t::row_map_type::non_const_type;
using cols_view_t = typename graph_t::entries_type::non_const_type;
row_map_view_t rowmap_view ("rowmap_view", nrows+1);
cols_view_t column_view ("colmap_view", nnz);
// copy graph to device
Kokkos::deep_copy (rowmap_view, row_map);
Kokkos::deep_copy (column_view, entries);
graph_t static_graph (column_view, rowmap_view);
return static_graph;
}
/* ========================================================================================= */
template <typename graph_t, typename ptr_type, typename size_type, typename ordinal_type, typename KernelHandle>
graph_t
read_supernodal_graphL(KernelHandle kernelHandle, int n, int nsuper, int nnzA, bool ptr_by_column,
ptr_type *mb, size_type *nb, ordinal_type *rowind) {
using row_map_view_t = typename graph_t::row_map_type::non_const_type;
using cols_view_t = typename graph_t::entries_type::non_const_type;
using integer_view_host_t = Kokkos::View<ordinal_type*, Kokkos::HostSpace>;
// load parameters
auto *handle = kernelHandle->get_sptrsv_handle ();
bool merge = handle->get_merge_supernodes ();
row_map_view_t rowmap_view ("rowmap_view", n+1);
cols_view_t column_view ("colmap_view", nnzA);
auto hr = Kokkos::create_mirror_view (rowmap_view);
auto hc = Kokkos::create_mirror_view (column_view);
// compute offset for each row
int j = 0;
int max_nnz_per_row = 0;
hr(j) = 0;
for (int s = 0 ; s < nsuper ; s++) {
int j1 = nb[s];
int j2 = nb[s+1];
// number of columns in the s-th supernode column
int nscol = j2 - j1;
int i1, i2;
if (ptr_by_column) {
i1 = mb[j1];
i2 = mb[j1+1];
} else {
i1 = mb[s];
i2 = mb[s+1];
}
// "total" number of rows in all the supernodes (diagonal+off-diagonal)
int nsrow = i2 - i1;
for (int jj = 0; jj < nscol; jj++) {
hr(j+1) = hr(j) + nsrow;
j++;
}
if (nsrow > max_nnz_per_row) {
max_nnz_per_row = nsrow;
}
}
integer_view_host_t sorted_rowind_view ("sorted_rowind", max_nnz_per_row);
ordinal_type *sorted_rowind = sorted_rowind_view.data ();
// store L in csr
for (int s = 0 ; s < nsuper ; s++) {
int j1 = nb[s];
int j2 = nb[s+1];
int nscol = j2 - j1; // number of columns in the s-th supernode column
int i1, i2;
if (ptr_by_column) {
i1 = mb[j1];
i2 = mb[j1+1];
} else {
i1 = mb[s];
i2 = mb[s+1];
}
int nsrow = i2 - i1; // "total" number of rows in all the supernodes (diagonal+off-diagonal)
int nsrow2 = nsrow - nscol; // "total" number of rows in all the off-diagonal supernodes
int ps2 = i1 + nscol; // offset into rowind
/* diagonal block */
for (int ii = 0; ii < nscol; ii++) {
// lower-triangular part
for (int jj = 0; jj < ii; jj++) {
hc(hr(j1+jj)) = j1+ii;
hr(j1+jj) ++;
}
// diagonal
hc(hr(j1+ii)) = j1+ii;
hr(j1+ii) ++;
// explicitly store zeros in upper-part
for (int jj = ii+1; jj < nscol; jj++) {
hc(hr(j1+jj)) = j1+ii;
hr(j1+jj) ++;
}
}
/* off-diagonal blocks */
if (merge) {
// sort rowind (to merge supernodes)
for (int ii = 0; ii < nsrow2; ii++) {
sorted_rowind[ii] = ii;
}
std::sort(&(sorted_rowind[0]), &(sorted_rowind[nsrow2]), sort_indices<ordinal_type>(&rowind[ps2]));
}
for (int kk = 0; kk < nsrow2; kk++) {
int ii = (merge ? sorted_rowind[kk] : kk); // sorted rowind
int i = rowind[ps2 + ii];
for (int jj = 0; jj < nscol; jj++) {
hc(hr(j1+jj)) = i;
hr(j1+jj) ++;
}
}
}
// fix hr
for (int i = n; i >= 1; i--) {
hr(i) = hr(i-1);
}
hr(0) = 0;
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
std::cout << " * Matrix size = " << n << std::endl;
std::cout << " * Total nnz = " << hr (n) << std::endl;
std::cout << " * nnz / n = " << hr (n)/n << std::endl;
#endif
// deepcopy
Kokkos::deep_copy (rowmap_view, hr);
Kokkos::deep_copy (column_view, hc);
// create crs
graph_t static_graph (column_view, rowmap_view);
return static_graph;
}
/* ========================================================================================= */
template <typename graph_t, typename ptr_type, typename size_type, typename ordinal_type, typename KernelHandle>
graph_t
read_supernodal_graphLt(KernelHandle kernelHandle, int n, int nsuper, bool ptr_by_column,
ptr_type *mb, size_type *nb, ordinal_type *rowind) {
using row_map_view_t = typename graph_t::row_map_type::non_const_type;
using cols_view_t = typename graph_t::entries_type::non_const_type;
using integer_view_host_t = Kokkos::View<int*, Kokkos::HostSpace>;
// load parameters
auto *handle = kernelHandle->get_sptrsv_handle ();
bool merge = handle->get_merge_supernodes ();
/* create a map from row id to supernode id */
integer_view_host_t map ("map", n);
int supid = 0;
for (int k = 0; k < nsuper; k++) {
int j1 = nb[k];
int j2 = nb[k+1];
for (int j = j1; j < j2; j++) {
map (j) = supid;
}
supid ++;
}
row_map_view_t rowmap_view ("rowmap_view", n+1);
auto hr = Kokkos::create_mirror_view (rowmap_view);
Kokkos::deep_copy (hr, 0);
integer_view_host_t sup ("sup", nsuper);
integer_view_host_t check ("check", nsuper);
Kokkos::deep_copy (check, 0);
// compute offset for each row
int nnzA = 0;
for (int s = 0; s < nsuper; s++) {
int j1 = nb[s];
int j2 = nb[s+1];
// number of columns in the s-th supernode column
int nscol = j2 - j1;
int i1, i2;
if (ptr_by_column) {
i1 = mb[j1];
i2 = mb[j1+1];
} else {
i1 = mb[s];
i2 = mb[s+1];
}
// diagonal blocks
for (int ii = j1; ii < j2; ii++) {
hr(ii+1) += nscol;
nnzA += nscol;
}
// offdiagonal blocks
int nsup = 0;
int ps2 = i1 + nscol; // offset into rowind
int nsrow = i2 - i1;
int nsrow2 = nsrow-nscol;
for (int kk = 0; kk < nsrow2; kk++) {
int irow = rowind[ps2 + kk];
supid = map (irow);
if (check (supid) == 0) {
for (int ii = nb[supid]; ii < nb[supid+1]; ii++) {
hr (ii + 1) += nscol;
nnzA += nscol;
}
check (supid) = 1;
sup (nsup) = supid;
nsup ++;
}
}
// reset check
for (int i = 0; i < nsup; i++ ) {
check (sup (i)) = 0;
}
}
for (int i = 0; i < n; i++) {
hr(i+1) += hr(i);
}
cols_view_t column_view ("colmap_view", nnzA);
auto hc = Kokkos::create_mirror_view (column_view);
// pointer to off-diagonals (diagonal comes first)
integer_view_host_t off ("off", 1+n);
for (int s = 0; s < nsuper; s++) {
int i1 = nb[s];
int i2 = nb[s+1];
// number of columns in the s-th supernode column
int nscol = i2 - i1;
for (int ii = i1; ii < i2; ii++) {
off (ii) = hr (ii) + nscol;
}
}
// store L in csr
for (int s = 0; s < nsuper; s++) {
int j1 = nb[s];
int j2 = nb[s+1];
int nscol = j2 - j1; // number of columns in the s-th supernode column
int i1, i2;
if (ptr_by_column) {
i1 = mb[j1];
i2 = mb[j1+1];
} else {
i1 = mb[s];
i2 = mb[s+1];
}
int nsrow = i2 - i1; // "total" number of rows in all the supernodes (diagonal+off-diagonal)
int nsrow2 = nsrow - nscol; // "total" number of rows in all the off-diagonal supernodes
int ps2 = i1 + nscol; // offset into rowind
/* diagonal block */
for (int ii = 0; ii < nscol; ii++) {
// explicitly store zeros in upper-part
for (int jj = 0; jj < nscol; jj++) {
hc(hr(j1+ii)+jj) = j1+jj;
}
}
/* off-diagonal blocks */
int nsup = 0;
for (int kk = 0; kk < nsrow2; kk++) {
int irow = rowind[ps2 + kk];
supid = map (irow);
if (check (supid) == 0) {
for (int ii = nb[supid]; ii < nb[supid+1]; ii++) {
for (int jj = 0; jj < nscol; jj++) {
hc (off(ii)+jj) = j1+jj;
}
off(ii) += nscol;
}
check (supid) = 1;
sup (nsup) = supid;
nsup ++;
}
}
// reset check
for (int i = 0; i < nsup; i++ ) {
check (sup (i)) = 0;
}
}
if (merge) {
// they should be sorted?
}
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
std::cout << " * Matrix size = " << n << std::endl;
std::cout << " * Total nnz = " << hr (n) << std::endl;
std::cout << " * nnz / n = " << hr (n)/n << std::endl;
#endif
// deepcopy
Kokkos::deep_copy (rowmap_view, hr);
Kokkos::deep_copy (column_view, hc);
// create crs
graph_t static_graph (column_view, rowmap_view);
return static_graph;
}
/* ========================================================================================= */
template <typename input_graph_t, typename input_size_type>
void check_supernode_sizes(const char *title, int n, int nsuper, input_size_type *nb, input_graph_t &graph) {
auto rowmap_view = graph.row_map;
auto hr = Kokkos::create_mirror_view (rowmap_view);
Kokkos::deep_copy (hr, rowmap_view);
int min_nsrow = 0, max_nsrow = 0, tot_nsrow = 0;
int min_nscol = 0, max_nscol = 0, tot_nscol = 0;
for (int s = 0; s <nsuper; s++) {
int j1 = nb[s];
int j2 = nb[s+1];
int nscol = j2 - j1;
int nsrow = hr(j1+1) - hr(j1);
if (s == 0) {
min_nscol = max_nscol = tot_nscol = nscol;
min_nsrow = max_nsrow = tot_nsrow = nsrow;
} else {
if (min_nsrow > nsrow) {
min_nsrow = nsrow;
}
if (max_nsrow < nsrow) {
max_nsrow = nsrow;
}
tot_nsrow += nsrow;
if (min_nscol > nscol) {
min_nscol = nscol;
}
if (max_nscol < nscol) {
max_nscol = nscol;
}
tot_nscol += nscol;
}
}
std::cout << std::endl
<< " ------------------------------------- "
<< std::endl << std::endl;
std::cout << " " << title << std::endl;
std::cout << " + nsuper = " << nsuper << std::endl;
std::cout << " > nsrow: min = " << min_nsrow << ", max = " << max_nsrow
<< ", avg = " << tot_nsrow/nsuper << std::endl;
std::cout << " > nscol: min = " << min_nscol << ", max = " << max_nscol
<< ", avg = " << tot_nscol/nsuper << std::endl;
std::cout << " + Matrix size = " << n << std::endl;
std::cout << " + Total nnz = " << hr(n) << std::endl;
std::cout << " + nnz / n = " << hr(n)/n << std::endl;
}
/* ========================================================================================= */
template <typename host_graph_t, typename graph_t, typename input_size_type>
host_graph_t
generate_supernodal_graph(bool col_major, graph_t &graph, int nsuper, const input_size_type *nb) {
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
double time_seconds = 0.0;
Kokkos::Timer timer;
#endif
using size_type = typename graph_t::size_type;
using cols_view_host_t = typename host_graph_t::entries_type::non_const_type;
using row_map_view_host_t = typename host_graph_t::row_map_type::non_const_type;
using integer_view_host_t = Kokkos::View<int*, Kokkos::HostSpace>;
int n = graph.numRows ();
auto row_map = graph.row_map;
auto entries = graph.entries;
auto row_map_host = Kokkos::create_mirror_view (row_map);
auto entries_host = Kokkos::create_mirror_view (entries);
Kokkos::deep_copy (row_map_host, row_map);
Kokkos::deep_copy (entries_host, entries);
// map col/row to supernode
integer_view_host_t map ("map", n);
for (int s = 0; s < nsuper; s++) {
for (int j = nb[s]; j < nb[s+1]; j++) {
map (j) = s;
}
}
// count non-empty supernodal blocks
row_map_view_host_t hr ("rowmap_view", nsuper+1);
integer_view_host_t check ("check", nsuper);
integer_view_host_t idxs ("idxs", nsuper);
Kokkos::deep_copy (hr, 0);
Kokkos::deep_copy (check, 0);
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
timer.reset ();
#endif
int nblocks = 0;
for (int s = 0; s < nsuper; s++) {
int j1 = nb[s];
int j2 = j1+1; // based on the first row
size_type nidxs = 0;
for (size_type i = row_map_host (j1); i < row_map_host (j2); i++) {
int s2 = map (entries_host (i));
// supernodal blocks may not be filled with zeros
// so need to check by each row
// (also rowids are not sorted)
if (check (s2) == 0) {
check (s2) = 1;
nblocks ++;
// count blocks per row for col_major
hr (s2+1) ++;
// keep track of non-zero block ids
idxs (nidxs) = s2;
nidxs ++;
}
}
// reset check
//Kokkos::deep_copy (check, 0);
for (size_type i = 0; i < nidxs; i++) {
check (idxs(i)) = 0;
}
}
cols_view_host_t hc ("colmap_view", nblocks);
if (col_major) {
// convert to offset
for (int s = 0; s < nsuper; s++) {
hr (s+1) += hr (s);
}
}
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
time_seconds = timer.seconds ();
std::cout << " > Generate Supernodal Graph: count blocks : " << time_seconds << std::endl;
timer.reset ();
#endif
nblocks = 0;
for (int s = 0; s < nsuper; s++) {
int j1 = nb[s];
int j2 = j1+1; // based on the first row
size_type nidxs = 0;
for (size_type i = row_map_host (j1); i < row_map_host (j2); i++) {
int s2 = map (entries_host (i));
// supernodal blocks may not be filled with zeros
// so need to check by each row
// (also rowids are not sorted)
if (check (s2) == 0) {
check (s2) = 1;
if (col_major) {
hc (hr (s2)) = s;
hr (s2) ++;
} else {
hc (nblocks) = s2;
}
nblocks ++;
// keep track of non-zero block ids
idxs (nidxs) = s2;
nidxs ++;
}
}
if (!col_major) {
hr (s+1) = nblocks;
}
// reset check
/*if (!col_major) {
for (size_type s2 = hr(s); s2 < hr(s+1); s2++) {
check (hc(s2)) = 0;
}
} else {
// NOTE: nonzero supernodes in s-th col are not stored
Kokkos::deep_copy (check, 0);
}*/
for (size_type i = 0; i < nidxs; i++) {
check (idxs(i)) = 0;
}
}
// fix hr
if (col_major) {
for (int s = nsuper; s > 0; s--) {
hr (s) = hr (s-1);
}
hr (0) = 0;
}
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
time_seconds = timer.seconds ();
std::cout << " > Generate Supernodal Graph: compress graph : " << time_seconds
<< " (col_major = " << col_major << ")" << std::endl;
timer.reset ();
#endif
// sort column ids per row
for (int s = 0; s < nsuper; s++) {
std::sort(&(hc (hr (s))), &(hc (hr (s+1))));
}
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
time_seconds = timer.seconds ();
std::cout << " > Generate Supernodal Graph: sort graph : " << time_seconds << std::endl << std::endl;
#endif
host_graph_t static_graph (hc, hr);
return static_graph;
}
template <typename graph_t>
graph_t generate_supernodal_dag(int nsuper, graph_t &supL, graph_t &supU) {
// graph_t is assumed to be on the host
auto row_mapL = supL.row_map;
auto entriesL = supL.entries;
auto row_mapU = supU.row_map;
auto entriesU = supU.entries;
// compute dag
int totedges = 0;
using size_type = typename graph_t::size_type;
using row_map_view_t = typename graph_t::row_map_type::non_const_type;
using cols_view_t = typename graph_t::entries_type::non_const_type;
row_map_view_t colptr ("rowind", nsuper+1);
cols_view_t rowind ("colptr", row_mapL (nsuper)); // over-estimate
cols_view_t edges ("edges", nsuper); // workspace
cols_view_t check ("edges", nsuper); // workspace
Kokkos::deep_copy (check, 0);
colptr (0) = totedges;
for (int s = 0; s < nsuper; s ++) {
// count # of edges (search for first matching nonzero)
size_type nedges = 0;
size_type k1 = 1 + row_mapL (s); // skip diagonal
size_type k2 = 1 + row_mapU (s); // skip diagonal
for (; k1 < row_mapL (s+1); k1++) {
// look for match
while (k2+1 < row_mapU (s+1) && entriesL (k1) > entriesU (k2)) {
k2 ++;
}
if (k2+1 >= row_mapU (s+1) || entriesL (k1) <= entriesU (k2)) {
edges (nedges) = entriesL (k1);
nedges ++;
if (entriesL (k1) == entriesU (k2)) {
#if 0
// make sure entriesU(k2) rows include the sparsity structure of s?
for (int k = row_mapL (entriesU (k2)); k < row_mapL (entriesU (k2) + 1); k++) {
check (entriesL (k)) = 1;
}
for (int k = k1 + 1; k < row_mapL (s+1); k++) {
if (check (entriesL (k)) != 1) {
edges (nedges) = entriesL (k1);
nedges ++;
}
}
for (int k = row_mapL (entriesU (k2)); k < row_mapL (entriesU (k2) + 1); k++) {
check (entriesL (k)) = 0;
}
#endif
break;
}
}
}
// store the edges
for (size_type k = 0; k < nedges; k++) {
rowind (totedges) = edges (k);
totedges ++;
}
colptr (s+1) = totedges;
}
// compress dag into graph
cols_view_t hc ("colmap_view", totedges);
for (size_type k = colptr (0); k < colptr (nsuper); k++) {
hc (k) = rowind (k);
}
graph_t static_graph (hc, colptr);
return static_graph;
}
/* ========================================================================================= */
template <typename input_graph_t, typename input_size_type>
void merge_supernodal_graph(int *p_nsuper, input_size_type *nb,
bool col_majorL, input_graph_t &graphL,
bool col_majorU, input_graph_t &graphU,
int *etree) {
int nsuper = *p_nsuper;
// ---------------------------------------------------------------
// looking for supernodes to merge (i.e., dense diagonal blocks)
int nsuper2 = 0;
auto supL = generate_supernodal_graph<input_graph_t, input_graph_t> (!col_majorL, graphL, nsuper, nb);
auto supU = generate_supernodal_graph<input_graph_t, input_graph_t> ( col_majorU, graphU, nsuper, nb);
auto row_mapL = supL.row_map;
auto entriesL = supL.entries;
auto row_mapU = supU.row_map;
auto entriesU = supU.entries;
// map the first supernode
using integer_view_host_t = Kokkos::View<int*, Kokkos::HostSpace>;
integer_view_host_t map ("map", nsuper); // map old to new supernodes
map (0) = 0;
for (int s = 0; s < nsuper-1; s++) {
int s2 = s;
bool merged = false;
do {
// check if L(s2+1:end, s2) and L(s2+1:end, s2+1)are the same
bool mergedL = false;
int k1 = row_mapL[s2+1] - row_mapL[s2];
int k2 = row_mapL[s2+2] - row_mapL[s2+1];
if (k1 == k2+1) {
mergedL = true;
for (int k = 0; k < k2 && mergedL; k++) {
if (entriesL[row_mapL[s2]+k+1] != entriesL[row_mapL[s2+1]+k]) {
mergedL = false;
}
}
}
// check if U(s2+1:end, s2) and U(s2+1:end, s2+1) are the same
bool mergedU = false;
k1 = row_mapU[s2+1] - row_mapU[s2];
k2 = row_mapU[s2+2] - row_mapU[s2+1];
if (k1 == k2+1) {
mergedU = true;
for (int k = 0; k < k2 && mergedU; k++) {
if (entriesU[row_mapU[s2]+k+1] != entriesU[row_mapU[s2+1]+k]) {
mergedU = false;
}
}
}
merged = (mergedL && mergedU);
if (merged) {
//printf( " >> merge s2+1=%d(%dx%d, row=%d:%d) with s=%d(%dx%d) <\n",
// s2+1,nb[s2+2]-nb[s2+1],nb[s2+2]-nb[s2+1], nb[s2+1],nb[s2+2]-1,
// s,nb[s+1]-nb[s],nb[s+1]-nb[s]);
map (s2+1) = nsuper2;
s2 ++;
} else {
//printf( " -- not merge s2+1=%d(%dx%d, row=%d:%d) with s=%d(%dx%d) --\n",
// s2+1,nb[s2+2]-nb[s2+1],nb[s2+2]-nb[s2+1],nb[s2+1],nb[s2+2]-1,
// s,nb[s+1]-nb[s],nb[s+1]-nb[s]);
map (s2+1) = nsuper2+1;
}
} while (merged && s2 < nsuper-1);
s = s2;
nsuper2 ++;
}
nsuper2 = map (nsuper-1)+1;
//printf( " nsuper2 = %d\n",nsuper2 );
//printf( " map:\n" );
//for (int s = 0; s < nsuper; s++) printf( " %d %d\n",s,map (s) );
// ----------------------------------------------------------
// make sure each of the merged supernodes has the same parent in the etree
int nsuper3 = 0;
integer_view_host_t map2;
if (etree != nullptr) {
nsuper3 = 0;
map2 = integer_view_host_t ("map2", nsuper); // map old to new supernodes
for (int s2 = 0, s = 0; s2 < nsuper2; s2++) {
// look for parent of the first supernode
int s3 = s;
while (etree[s3] != -1 && map (etree[s3]) == map (s3)) {
s3 ++;
}
map2 (s) = nsuper3;
int p = (etree[s3] == -1 ? -1 : map (etree[s3]));
// go through the rest of the supernode in this merged supernode
s++;
while (s < nsuper && map (s) == s2) {
int q = (etree[s3] == -1 ? -1 : map (etree[s3]));
while (etree[s3] != -1 && map (etree[s3]) == map (s3)) {
s3 ++;
q = (etree[s3] == -1 ? -1 : map (etree[s3]));
}
if (q != p) {
p = q;
nsuper3 ++;
}
map2 (s) = nsuper3;
s ++;
}
nsuper3 ++;
}
} else {
nsuper3 = nsuper2;
map2 = map;
}
//printf( " nsuper3 = %d\n",nsuper3 );
//printf( " map:\n" );
//for (int s = 0; s < nsuper; s++) printf( " %d %d\n",s,map2 (s) );
// ----------------------------------------------------------
// construct new supernodes
integer_view_host_t nb2 ("nb2", 1+nsuper3);
for (int s2 = 0, s = 0; s2 < nsuper3; s2++) {
nb2 (1+s2) = 0;
// merging supernodal rows
while(s < nsuper && map2 (s) == s2) {
nb2 (1+s2) += (nb[s+1]-nb[s]);
s ++;
}
}
// copy back the new supernodes "offsets"
nb2 (0) = 0;
for (int s = 0; s < nsuper3; s++) {
nb2 (s+1) = nb2 (s) + nb2 (s+1);
}
// copy nb
for (int s = 0; s <nsuper3; s++) {
nb[s+1] = nb2 (s+1);
}
// ----------------------------------------------------------
// construct new etree
if (etree != nullptr) {
integer_view_host_t etree2 ("etree2", nsuper3);
for (int s = 0; s < nsuper; s++) {
// etree
int s2 = map2 (s);
int p = (etree[s] == -1 ? -1 : map2 (etree[s]));
if (p != s2) {
etree2 (s2) = p;
}
}
// copy etree
for (int s = 0; s <nsuper3; s++) {
etree[s] = etree2 (s);
}
}
*p_nsuper = nsuper3;
}
/* ========================================================================================= */
template <typename output_graph_t, typename input_graph_t, typename input_size_type>
output_graph_t
generate_merged_supernodal_graph(bool lower,
int nsuper, const input_size_type *nb,
int nsuper2, input_size_type *nb2,
input_graph_t &graph, int *nnz) {
using cols_view_t = typename output_graph_t::entries_type::non_const_type;
using row_map_view_t = typename output_graph_t::row_map_type::non_const_type;
using size_type = typename input_graph_t::size_type;
// ----------------------------------------------------------
// now let me find nsrow for the merged supernode
auto row_map = graph.row_map;
auto entries = graph.entries;
int n = graph.numRows ();
using integer_view_host_t = Kokkos::View<int*, Kokkos::HostSpace>;
integer_view_host_t mb2 ("mb2", nsuper2);
integer_view_host_t work1 ("work1", n);
integer_view_host_t work2 ("work2", n);
Kokkos::deep_copy (work1, 0);
int nnzS = 0;
int nnzA = 0;
integer_view_host_t rowind ("rowind", row_map(n)); // over-estimate
integer_view_host_t colptr ("colptr", nsuper2+1);
colptr (0) = nnzS;
for (int s2 = 0, s = 0; s2 < nsuper2; s2++) {
mb2 (s2) = 0;
// merging supernodal rows
// NOTE: SuperLU may not fill zeros to fill the supernodes
// So, these rows may be just subset of the supernodal rows
while (s < nsuper && nb[s+1] <= nb2[s2+1]) {
input_size_type j1 = nb[s];
for (size_type k = row_map (j1); k < row_map (j1+1); k++) {
// just taking union of rows
if (work1 (entries[k]) == 0) {
work1 (entries[k]) = 1;
work2 (mb2 (s2)) = entries[k];
mb2 (s2) ++;
}
}
s++;
}
// sort such that diagonal come on the top
std::sort(work2.data (), work2.data () + mb2 (s2));
// save nonzero row ids
if (lower) {
// lower in csc, diagonal come on top
for (int k = 0; k < mb2 (s2); k++) {
rowind (nnzS) = work2 (k);
work1 (work2 (k)) = 0;
nnzS ++;
}
} else {
// upper in csc, diagonal block is on bottom right now, but move it to top
int nd = nb2[s2+1]-nb2[s2]; // size of diagonal block
// > diagonal block
for (int k = mb2 (s2) - nd; k < mb2 (s2); k++) {
rowind (nnzS) = work2 (k);
work1 (work2 (k)) = 0;
nnzS ++;
}
// > offdiagonal blocks
for (int k = 0; k < mb2 (s2) - nd; k++) {
rowind (nnzS) = work2 (k);
work1 (work2 (k)) = 0;
nnzS ++;
}
}
colptr (s2+1) = nnzS;
nnzA += (nb2[s2+1]-nb2[s2]) * mb2 (s2);
}
// ----------------------------------------------------------
// now let's create crs graph
row_map_view_t rowmap_view ("rowmap_view", n+1);
cols_view_t column_view ("colmap_view", nnzA);
auto hr = Kokkos::create_mirror_view (rowmap_view);
auto hc = Kokkos::create_mirror_view (column_view);
nnzA = 0;
hr(0) = 0;
for (int s2 = 0; s2 < nsuper2; s2++) {
for (int j = nb2[s2]; j < nb2[s2+1]; j++) {
for (int k = colptr (s2); k < colptr (s2+1); k++) {
hc(nnzA) = rowind (k);
nnzA ++;
}
hr(j+1) = nnzA;
}
}
*nnz = nnzA;
// deepcopy
Kokkos::deep_copy (rowmap_view, hr);
Kokkos::deep_copy (column_view, hc);
// create crs
output_graph_t static_graph (column_view, rowmap_view);
return static_graph;
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* For symbolic analysis */
template <typename host_graph_t, typename KernelHandle>
void sptrsv_supernodal_symbolic(
int nsuper, int *supercols, int *etree,
host_graph_t graphL_host, KernelHandle *kernelHandleL,
host_graph_t graphU_host, KernelHandle *kernelHandleU) {
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
int nrows = graphL_host.numRows ();
double time_seconds = 0.0;
Kokkos::Timer timer;
Kokkos::Timer tic;
timer.reset ();
#endif
// ===================================================================
// load sptrsv-handles
auto *handleL = kernelHandleL->get_sptrsv_handle ();
auto *handleU = kernelHandleU->get_sptrsv_handle ();
// store arguments to handle
handleL->set_graph_host (graphL_host);
handleU->set_graph_host (graphU_host);
handleL->set_supernodes (nsuper, supercols, etree);
handleU->set_supernodes (nsuper, supercols, etree);
// ===================================================================
// load options
bool col_majorL = handleL->is_column_major ();
bool col_majorU = handleU->is_column_major ();
bool merge = handleL->get_merge_supernodes ();
bool UinCSC = handleU->is_column_major ();
bool needEtree = (handleL->get_algorithm () == SPTRSVAlgorithm::SUPERNODAL_SPMV ||
handleL->get_algorithm () == SPTRSVAlgorithm::SUPERNODAL_ETREE);
if (needEtree && etree == nullptr) {
std::cout << std::endl
<< " ** etree needs to be set before calling sptrsv_symbolic with SuperLU **"
<< std::endl << std::endl;
return;
}
// ===================================================================
// > make a copy of supercols (merge needs both original and merged supercols)
using integer_view_host_t = typename KernelHandle::SPTRSVHandleType::integer_view_host_t;
integer_view_host_t supercols_view ("supercols view", 1+nsuper);
int *supercols_merged = supercols_view.data ();
for (int i = 0; i <= nsuper; i++) {
supercols_merged[i] = supercols[i];
}
if (merge) {
// =================================================================
// merge supernodes
int nsuper_merged = nsuper;
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
tic.reset ();
check_supernode_sizes("Original L-structure", nrows, nsuper, supercols_merged, graphL_host);
check_supernode_sizes("Original U-structure", nrows, nsuper, supercols_merged, graphU_host);
#endif
// etree will be updated
merge_supernodal_graph (&nsuper_merged, supercols_merged,
col_majorL, graphL_host, col_majorU, graphU_host,
etree);
// =================================================================
// generate merged graph for L-solve
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
int nnzL = graphL_host.row_map (nrows);
#endif
int nnzL_merged;
bool lower = true;
handleL->set_original_graph_host (graphL_host); // save graph before merge
graphL_host = generate_merged_supernodal_graph<host_graph_t> (lower, nsuper, supercols,
nsuper_merged, supercols_merged,
graphL_host, &nnzL_merged);
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
time_seconds = tic.seconds ();
check_supernode_sizes ("After Merge", nrows, nsuper_merged, supercols_merged, graphL_host);
std::cout << " for L factor:" << std::endl;
std::cout << " Merge Supernodes Time: " << time_seconds << std::endl;
std::cout << " Number of nonzeros : " << nnzL << " -> " << nnzL_merged
<< " : " << double(nnzL_merged) / double(nnzL) << "x" << std::endl;
#endif
// =================================================================
// generate merged graph for U-solve
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
tic.reset ();
int nnzU = graphU_host.row_map (nrows);
#endif
int nnzU_merged;
lower = (UinCSC ? false : true);
handleU->set_original_graph_host (graphU_host); // save graph before merge
graphU_host = generate_merged_supernodal_graph<host_graph_t> (lower, nsuper, supercols,
nsuper_merged, supercols_merged,
graphU_host, &nnzU_merged);
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
time_seconds = tic.seconds ();
check_supernode_sizes("After Merge", nrows, nsuper_merged, supercols_merged, graphU_host);
std::cout << " for U factor:" << std::endl;
std::cout << " Merge Supernodes Time: " << time_seconds << std::endl;
std::cout << " Number of nonzeros : " << nnzU << " -> " << nnzU_merged
<< " : " << double(nnzU_merged) / double(nnzU) << "x" << std::endl;
#endif
// update the number of supernodes
nsuper = nsuper_merged;
}
// replace the supernodal info with the merged ones
supercols = supercols_merged;
// ===================================================================
// copy graph to device
using graph_t = typename KernelHandle::SPTRSVHandleType::graph_t;
auto graphL = deep_copy_graph<host_graph_t, graph_t> (graphL_host);
auto graphU = deep_copy_graph<host_graph_t, graph_t> (graphU_host);
// ===================================================================
// save the supernodal info in the handles for L/U solves
handleL->set_supernodes (nsuper, supercols_view, etree);
handleU->set_supernodes (nsuper, supercols_view, etree);
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
time_seconds = tic.seconds ();
std::cout << " Deep-copy graph Time: " << time_seconds << std::endl;
tic.reset ();
#endif
if (handleL->get_algorithm () == SPTRSVAlgorithm::SUPERNODAL_DAG ||
handleL->get_algorithm () == SPTRSVAlgorithm::SUPERNODAL_SPMV_DAG) {
// generate supernodal graphs for DAG scheduling
auto supL = generate_supernodal_graph<host_graph_t> (!col_majorL, graphL_host, nsuper, supercols);
auto supU = generate_supernodal_graph<host_graph_t> ( col_majorU, graphU_host, nsuper, supercols);
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
time_seconds = tic.seconds ();
std::cout << " Compute Supernodal Graph Time: " << time_seconds << std::endl;
tic.reset ();
#endif
auto dagL = generate_supernodal_dag<host_graph_t> (nsuper, supL, supU);
auto dagU = generate_supernodal_dag<host_graph_t> (nsuper, supU, supL);
handleL->set_supernodal_dag (dagL);
handleU->set_supernodal_dag (dagU);
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
time_seconds = tic.seconds ();
std::cout << " Compute DAG Time: " << time_seconds << std::endl;
tic.reset ();
#endif
}
// ===================================================================
// do symbolic for L solve on the host
auto row_mapL = graphL.row_map;
auto entriesL = graphL.entries;
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
tic.reset();
std::cout << std::endl;
#endif
sptrsv_symbolic (kernelHandleL, row_mapL, entriesL);
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
time_seconds = tic.seconds ();
std::cout << " > Lower-TRI: " << std::endl;
std::cout << " Symbolic Time: " << time_seconds << std::endl;
tic.reset ();
#endif
// ===================================================================
// do symbolic for U solve on the host
auto row_mapU = graphU.row_map;
auto entriesU = graphU.entries;
sptrsv_symbolic (kernelHandleU, row_mapU, entriesU);
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
time_seconds = tic.seconds ();
std::cout << " > Upper-TRI: " << std::endl;
std::cout << " Symbolic Time: " << time_seconds << std::endl;
#endif
// ===================================================================
// save options
handleL->set_merge_supernodes (merge);
handleU->set_merge_supernodes (merge);
// ===================================================================
// save graphs
handleL->set_graph (graphL);
handleU->set_graph (graphU);
// graph on host (merged)
handleL->set_graph_host (graphL_host);
handleU->set_graph_host (graphU_host);
// ===================================================================
handleL->set_symbolic_complete ();
handleU->set_symbolic_complete ();
handleL->set_etree (etree);
handleU->set_etree (etree);
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
time_seconds = timer.seconds ();
std::cout << " Total Symbolic Time: " << time_seconds << std::endl << std::endl;
std::cout << " Total nnz: " << graphL_host.row_map (nrows) << " + " << graphU_host.row_map (nrows) << std::endl;
#endif
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* Auxiliary functions for numeric computation */
/* ========================================================================================= */
struct Tag_SupTrtriFunctor{};
struct Tag_SupTrtriTrmmFunctor{};
template <typename UploType, typename DiagType, typename integer_view_host_t,
typename input_size_type, typename row_map_type, typename index_type, typename values_type>
struct TriSupernodalTrtriFunctor {
integer_view_host_t supernode_ids;
const input_size_type *nb;
row_map_type hr;
index_type hc;
values_type hv;
KOKKOS_INLINE_FUNCTION
TriSupernodalTrtriFunctor(integer_view_host_t supernode_ids_, const input_size_type *nb_,
row_map_type& hr_, index_type& hc_, values_type& hv_) :
supernode_ids(supernode_ids_),
nb(nb_),
hr(hr_),
hc(hc_),
hv(hv_)
{}
// functor: just invert diagonal
KOKKOS_INLINE_FUNCTION
void operator() (const Tag_SupTrtriFunctor&, const int i) const {
using execution_space = typename values_type::execution_space;
using memory_space = typename execution_space::memory_space;
using values_view_t = typename values_type::non_const_type;
using scalar_t = typename values_view_t::value_type;
using range_type = Kokkos::pair<int, int>;
using TrtriAlgoType = KokkosBatched::Algo::Trtri::Unblocked;
int s = supernode_ids(i);
int j1 = nb[s];
int nsrow = hr(j1+1) - hr(j1);
int nscol = nb[s +1] - nb[s];
// invert diagonal
auto nnzD = hr (j1);
Kokkos::View<scalar_t**, Kokkos::LayoutLeft, memory_space, Kokkos::MemoryUnmanaged>
viewL (&hv(nnzD), nsrow, nscol);
auto Ljj = Kokkos::subview (viewL, range_type (0, nscol), Kokkos::ALL ());
KokkosBatched::SerialTrtri<UploType, DiagType, TrtriAlgoType>::invoke(Ljj);
}
// functor: invert diagonal + apply inverse to off-diagonal
KOKKOS_INLINE_FUNCTION
void operator() (const Tag_SupTrtriTrmmFunctor&, const int i) const {
using execution_space = typename values_type::execution_space;
using memory_space = typename execution_space::memory_space;
using values_view_t = typename values_type::non_const_type;
using scalar_t = typename values_view_t::value_type;
using range_type = Kokkos::pair<int, int>;
using TrtriAlgoType = KokkosBatched::Algo::Trtri::Unblocked;
using Side = KokkosBatched::Side;
using Trans = KokkosBatched::Trans;
int s = supernode_ids(i);
int j1 = nb[s];
int nsrow = hr(j1+1) - hr(j1);
int nscol = nb[s +1] - nb[s];
// invert diagonal
auto nnzD = hr (j1);
Kokkos::View<scalar_t**, Kokkos::LayoutLeft, memory_space, Kokkos::MemoryUnmanaged>
viewL (&hv(nnzD), nsrow, nscol);
auto Ljj = Kokkos::subview (viewL, range_type (0, nscol), Kokkos::ALL ());
KokkosBatched::SerialTrtri<UploType, DiagType, TrtriAlgoType>::invoke(Ljj);
// apply invse to off-diagonal
//if (nsrow > nscol && invert_offdiag)
{
const scalar_t one (1.0);
auto Lij = Kokkos::subview (viewL, range_type (nscol, nsrow), Kokkos::ALL ());
KokkosBatched::SerialTrmm<Side::Right, UploType, Trans::NoTranspose, DiagType, TrtriAlgoType>::
invoke(one, Ljj, Lij);
}
}
};
/* ========================================================================================= */
template <typename KernelHandle, typename input_size_type,
typename row_map_type, typename index_type, typename values_type>
void
invert_supernodal_columns(KernelHandle kernelHandle, bool unit_diag, int nsuper, const input_size_type *nb,
row_map_type& hr, index_type& hc, values_type& hv) {
using execution_space = typename values_type::execution_space;
using memory_space = typename execution_space::memory_space;
using values_view_t = typename values_type::non_const_type;
using scalar_t = typename values_view_t::value_type;
using range_type = Kokkos::pair<int, int>;
using integer_view_host_t = Kokkos::View<int*, Kokkos::HostSpace>;
const scalar_t one (1.0);
// load parameters
auto *handle = kernelHandle->get_sptrsv_handle ();
bool invert_diag = handle->get_invert_diagonal ();
bool invert_offdiag = handle->get_invert_offdiagonal ();
// lower is always in CSC, if UinCSC, then lower=false, else lower=true
bool lower_tri = kernelHandle->is_sptrsv_lower_tri ();
bool lower = ((lower_tri && handle->is_column_major ()) || (!lower_tri && !handle->is_column_major ()));
// quick return
if (!invert_diag) return;
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
Kokkos::Timer timer;
double time1 = 0.0;
double time2 = 0.0;
double time3 = 0.0;
#endif
// ----------------------------------------------------------
// now let's invert some blocks
// > first go through all the supernode columns
// > use KokkosBlas on large blocks, and keep track of small blocks
// > to call batchedBlas on them
int num_batchs = 0;
int size_unblocked = handle->get_supernode_size_unblocked();
integer_view_host_t supernode_ids ("supernode_batch", nsuper);
for (int s2 = 0; s2 < nsuper; s2++) {
int nscol = nb[s2+1] - nb[s2];
if (nscol >= size_unblocked) {
int j1 = nb[s2];
int nsrow = hr(j1+1) - hr(j1);
auto nnzD = hr (j1);
char uplo_char = (lower ? 'L' : 'U');
char diag_char = (unit_diag ? 'U' : 'N');
Kokkos::View<scalar_t**, Kokkos::LayoutLeft, memory_space, Kokkos::MemoryUnmanaged>
viewL (&hv(nnzD), nsrow, nscol);
auto Ljj = Kokkos::subview (viewL, range_type (0, nscol), Kokkos::ALL ());
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
timer.reset ();
#endif
KokkosBlas::trtri(&uplo_char, &diag_char, Ljj);
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
time1 += timer.seconds ();
#endif
if (nsrow > nscol && invert_offdiag) {
char side_char = 'R';
char tran_char = 'N';
auto Lij = Kokkos::subview (viewL, range_type (nscol, nsrow), Kokkos::ALL ());
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
timer.reset ();
#endif
KokkosBlas::trmm (&side_char, &uplo_char,
&tran_char, &diag_char,
one, Ljj, Lij);
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
time2 += timer.seconds ();
#endif
}
}
else {
supernode_ids (num_batchs) = s2;
num_batchs ++;
}
}
// now call batchedBLAS
if (num_batchs > 0) {
using Uplo = KokkosBatched::Uplo;
using Diag = KokkosBatched::Diag;
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
timer.reset ();
#endif
if (lower) {
if (unit_diag) {
if (invert_offdiag) {
using range_policy = Kokkos::RangePolicy<Tag_SupTrtriTrmmFunctor, execution_space>;
TriSupernodalTrtriFunctor<Uplo::Lower, Diag::Unit, integer_view_host_t, input_size_type, row_map_type, index_type, values_type>
sptrsv_tritri_functor (supernode_ids, nb, hr, hc, hv);
Kokkos::parallel_for("TriSupernodalTrtriFunctor", range_policy(0, num_batchs), sptrsv_tritri_functor);
} else {
using range_policy = Kokkos::RangePolicy<Tag_SupTrtriFunctor, execution_space>;
TriSupernodalTrtriFunctor<Uplo::Lower, Diag::Unit, integer_view_host_t, input_size_type, row_map_type, index_type, values_type>
sptrsv_tritri_functor (supernode_ids, nb, hr, hc, hv);
Kokkos::parallel_for("TriSupernodalTrtriFunctor", range_policy(0, num_batchs), sptrsv_tritri_functor);
}
} else {
if (invert_offdiag) {
using range_policy = Kokkos::RangePolicy<Tag_SupTrtriTrmmFunctor, execution_space>;
TriSupernodalTrtriFunctor<Uplo::Lower, Diag::NonUnit, integer_view_host_t, input_size_type, row_map_type, index_type, values_type>
sptrsv_tritri_functor (supernode_ids, nb, hr, hc, hv);
Kokkos::parallel_for("TriSupernodalTrtriFunctor", range_policy(0, num_batchs), sptrsv_tritri_functor);
} else {
using range_policy = Kokkos::RangePolicy<Tag_SupTrtriFunctor, execution_space>;
TriSupernodalTrtriFunctor<Uplo::Lower, Diag::NonUnit, integer_view_host_t, input_size_type, row_map_type, index_type, values_type>
sptrsv_tritri_functor (supernode_ids, nb, hr, hc, hv);
Kokkos::parallel_for("TriSupernodalTrtriFunctor", range_policy(0, num_batchs), sptrsv_tritri_functor);
}
}
} else {
if (unit_diag) {
if (invert_offdiag) {
using range_policy = Kokkos::RangePolicy<Tag_SupTrtriTrmmFunctor, execution_space>;
TriSupernodalTrtriFunctor<Uplo::Upper, Diag::Unit, integer_view_host_t, input_size_type, row_map_type, index_type, values_type>
sptrsv_tritri_functor (supernode_ids, nb, hr, hc, hv);
Kokkos::parallel_for("TriSupernodalTrtriFunctor", range_policy(0, num_batchs), sptrsv_tritri_functor);
} else {
using range_policy = Kokkos::RangePolicy<Tag_SupTrtriFunctor, execution_space>;
TriSupernodalTrtriFunctor<Uplo::Upper, Diag::Unit, integer_view_host_t, input_size_type, row_map_type, index_type, values_type>
sptrsv_tritri_functor (supernode_ids, nb, hr, hc, hv);
Kokkos::parallel_for("TriSupernodalTrtriFunctor", range_policy(0, num_batchs), sptrsv_tritri_functor);
}
} else {
if (invert_offdiag) {
using range_policy = Kokkos::RangePolicy<Tag_SupTrtriTrmmFunctor, execution_space>;
TriSupernodalTrtriFunctor<Uplo::Upper, Diag::NonUnit, integer_view_host_t, input_size_type, row_map_type, index_type, values_type>
sptrsv_tritri_functor (supernode_ids, nb, hr, hc, hv);
Kokkos::parallel_for("TriSupernodalTrtriFunctor", range_policy(0, num_batchs), sptrsv_tritri_functor);
} else {
using range_policy = Kokkos::RangePolicy<Tag_SupTrtriFunctor, execution_space>;
TriSupernodalTrtriFunctor<Uplo::Upper, Diag::NonUnit, integer_view_host_t, input_size_type, row_map_type, index_type, values_type>
sptrsv_tritri_functor (supernode_ids, nb, hr, hc, hv);
Kokkos::parallel_for("TriSupernodalTrtriFunctor", range_policy(0, num_batchs), sptrsv_tritri_functor);
}
}
}
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
time3 = timer.seconds ();
#endif
}
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
std::cout << " invert_supernodes" << std::endl;
std::cout << " + num supernodes = " << nsuper << " num batchs = " << num_batchs << std::endl;
std::cout << " > Time for inversion::trtri : " << time1 << std::endl;
std::cout << " > Time for inversion::trmm : " << time2 << std::endl;
std::cout << " > Time for batchs : " << time3 << std::endl;
#endif
}
/* ========================================================================================= */
template <typename crsmat_t, typename input_crsmat_t, typename input_ptr_type, typename graph_t,
typename KernelHandle>
crsmat_t
read_merged_supernodes(KernelHandle kernelHandle, int nsuper, const input_ptr_type *mb,
bool unit_diag, input_crsmat_t &L, graph_t &static_graph) {
using values_view_t = typename crsmat_t::values_type::non_const_type;
using scalar_t = typename values_view_t::value_type;
using scalar_view_host_t = Kokkos::View<scalar_t*, Kokkos::HostSpace>;
const scalar_t zero (0.0);
// original matrix
auto graphL = L.graph; // in_graph
auto row_mapL = graphL.row_map;
auto entriesL = graphL.entries;
auto valuesL = L.values;
Kokkos::Timer timer;
timer.reset ();
// merged graph
auto rowmap_view = static_graph.row_map;
auto column_view = static_graph.entries;
auto hr = Kokkos::create_mirror_view (rowmap_view);
auto hc = Kokkos::create_mirror_view (column_view);
Kokkos::deep_copy (hr, rowmap_view);
Kokkos::deep_copy (hc, column_view);
// ----------------------------------------------------------
// now let's merge supernodes
int n = graphL.numRows ();
scalar_view_host_t dwork ("dwork", n);
Kokkos::deep_copy (dwork, zero);
auto nnzA = hr (n);
values_view_t values_view ("values_view", nnzA);
auto hv = Kokkos::create_mirror_view (values_view);
for (int s2 = 0; s2 < nsuper; s2++) {
for (int j = mb[s2]; j < mb[s2+1]; j++) {
for (int k = row_mapL[j]; k < row_mapL[j+1]; k++) {
dwork (entriesL[k]) = valuesL[k];
}
for (int k = hr (j); k < hr (j+1); k++) {
hv(k) = dwork (hc(k));
}
for (int k = row_mapL[j]; k < row_mapL[j+1]; k++) {
dwork (entriesL[k]) = zero;
}
}
}
// invert blocks (TODO done on host for now)
invert_supernodal_columns (kernelHandle, unit_diag, nsuper, mb, hr, hc, hv);
// deepcopy
Kokkos::deep_copy (values_view, hv);
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
double time = timer.seconds ();
std::cout << " read_merged_supernodes" << std::endl;
std::cout << " > Time : " << time << std::endl;
#endif
// create crs
crsmat_t crsmat("CrsMatrix", n, values_view, static_graph);
return crsmat;
}
/* ========================================================================================= */
template <typename crsmat_t, typename graph_t, typename scalar_t,
typename input_size_type, typename input_ptr_type,
typename size_type, typename ordinal_type, typename KernelHandle>
crsmat_t
read_supernodal_valuesL(KernelHandle kernelHandle,
int n, int nsuper, bool ptr_by_column, const input_size_type *mb, const input_ptr_type *nb,
const size_type *colptr, ordinal_type *rowind, scalar_t *Lx, graph_t &static_graph) {
using values_view_t = typename crsmat_t::values_type::non_const_type;
using integer_view_host_t = Kokkos::View<ordinal_type*, Kokkos::HostSpace>;
const scalar_t zero (0.0);
const scalar_t one (1.0);
Kokkos::Timer timer;
timer.reset ();
// load parameters
auto *handle = kernelHandle->get_sptrsv_handle ();
bool unit_diag = handle->is_unit_diagonal ();
bool merge = handle->get_merge_supernodes ();
// load graph
auto rowmap_view = static_graph.row_map;
auto column_view = static_graph.entries;
auto hr = Kokkos::create_mirror_view (rowmap_view);
auto hc = Kokkos::create_mirror_view (column_view);
Kokkos::deep_copy (hr, rowmap_view);
Kokkos::deep_copy (hc, column_view);
// total nnz
int nnzL = hr (n);
values_view_t values_view ("values_view", nnzL);
auto hv = Kokkos::create_mirror_view (values_view);
Kokkos::deep_copy (hv, zero); // seems to be needed (instead of zeroing out upper)
// compute max nnz per row
int max_nnz_per_row = 0;
for (int s = 0; s < nsuper; s++) {
int i1, i2;
if (ptr_by_column) {
int j1 = nb[s];
i1 = mb[j1];
i2 = mb[j1+1];
} else {
i1 = mb[s];
i2 = mb[s+1];
}
// "total" number of rows in all the supernodes (diagonal+off-diagonal)
int nsrow = i2 - i1;
if (nsrow > max_nnz_per_row) {
max_nnz_per_row = nsrow;
}
}
integer_view_host_t sorted_rowind ("sorted_rowind", max_nnz_per_row);
// store L in csr
for (int s = 0; s < nsuper; s++) {
int j1 = nb[s];
int j2 = nb[s+1];
int nscol = j2 - j1; // number of columns in the s-th supernode column
int i1, i2;
if (ptr_by_column) {
i1 = mb[j1];
i2 = mb[j1+1];
} else {
i1 = mb[s];
i2 = mb[s+1];
}
int nsrow = i2 - i1; // "total" number of rows in all the supernodes (diagonal+off-diagonal)
int nsrow2 = nsrow - nscol; // "total" number of rows in all the off-diagonal supernodes
int ps2 = i1 + nscol; // offset into rowind
int psx; // offset into data, Lx[s][s]
if (ptr_by_column) {
psx = colptr[j1];
} else {
psx = colptr[s];
}
/* diagonal block */
// for each column (or row due to symmetry), the diagonal supernodal block is stored (in ascending order of row indexes) first
// so that we can do TRSM on the diagonal block
for (int jj = 0; jj < nscol; jj++) {
// shift for explicitly store zeros in upper-part
hr(j1+jj) += jj;
// diagonal
if (unit_diag) {
hv(hr(j1+jj)) = one;
} else {
hv(hr(j1+jj)) = Lx[psx + (jj + jj*nsrow)];
}
hr(j1+jj) ++;
// lower-triangular part
for (int ii = jj+1; ii < nscol; ii++) {
hv(hr(j1+jj)) = Lx[psx + (ii + jj*nsrow)];
hr(j1+jj) ++;
}
}
/* off-diagonal blocks */
if (merge) {
// sort rowind (to merge supernodes)
for (int ii = 0; ii < nsrow2; ii++) {
sorted_rowind (ii) = ii;
}
std::sort(sorted_rowind.data (), sorted_rowind.data () + nsrow2, sort_indices<ordinal_type>(&rowind[ps2]));
}
for (int jj = 0; jj < nscol; jj++) {
for (int kk = 0; kk < nsrow2; kk++) {
int ii = (merge ? sorted_rowind (kk) : kk); // sorted rowind
hv(hr(j1+jj)) = Lx[psx + (nscol+ii + jj*nsrow)];
hr(j1+jj) ++;
}
}
}
// fix hr
for (int i = n; i >= 1; i--) {
hr(i) = hr(i-1);
}
hr(0) = 0;
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
std::cout << " read_supernodal_valuesL" << std::endl;
std::cout << " * Matrix size = " << n << std::endl;
std::cout << " * Total nnz = " << hr (n) << std::endl;
std::cout << " * nnz / n = " << hr (n)/n << std::endl;
double time = timer.seconds ();
std::cout << " > Time : " << time << std::endl;
#endif
// invert blocks (TODO done on host for now)
invert_supernodal_columns (kernelHandle, unit_diag, nsuper, nb, hr, hc, hv);
// deepcopy
Kokkos::deep_copy (values_view, hv);
// create crs
crsmat_t crsmat ("CrsMatrix", n, values_view, static_graph);
return crsmat;
}
/* ========================================================================================= */
template <typename crsmat_t, typename graph_t, typename scalar_t,
typename input_size_type, typename input_ptr_type,
typename size_type, typename ordinal_type, typename KernelHandle>
crsmat_t
read_supernodal_valuesLt(KernelHandle kernelHandle,
int n, int nsuper, bool ptr_by_column, const input_size_type *mb, const input_ptr_type *nb,
const size_type *colptr, ordinal_type *rowind, scalar_t *Lx, graph_t &static_graph) {
using values_view_t = typename crsmat_t::values_type::non_const_type;
using integer_view_host_t = Kokkos::View<int*, Kokkos::HostSpace>;
const scalar_t zero (0.0);
const scalar_t one (1.0);
Kokkos::Timer timer;
timer.reset ();
// load parameters
auto *handle = kernelHandle->get_sptrsv_handle ();
bool unit_diag = handle->is_unit_diagonal ();
// load graph
auto rowmap_view = static_graph.row_map;
auto column_view = static_graph.entries;
auto hr = Kokkos::create_mirror_view (rowmap_view);
auto hc = Kokkos::create_mirror_view (column_view);
Kokkos::deep_copy (hr, rowmap_view);
Kokkos::deep_copy (hc, column_view);
// total nnz
int nnzL = hr (n);
values_view_t values_view ("values_view", nnzL);
auto hv = Kokkos::create_mirror_view (values_view);
Kokkos::deep_copy (hv, zero); // seems to be needed (instead of zeroing out upper)
/* create a map from row id to supernode id */
integer_view_host_t map ("map", n);
int supid = 0;
for (int k = 0; k < nsuper; k++) {
int j1 = nb[k];
int j2 = nb[k+1];
for (int j = j1; j < j2; j++) {
map (j) = supid;
}
supid ++;
}
// pointer to off-diagonals (diagonal comes first)
integer_view_host_t off ("off", n+1);
for (int s = 0; s < nsuper; s++) {
int i1 = nb[s];
int i2 = nb[s+1];
// number of columns in the s-th supernode column
int nscol = i2 - i1;
for (int ii = i1; ii < i2; ii++) {
off (ii) = hr (ii) + nscol;
}
}
// store L in csr
integer_view_host_t sup ("sup", nsuper);
integer_view_host_t check ("check", nsuper);
Kokkos::deep_copy (check, 0);
for (int s = 0; s < nsuper; s++) {
int j1 = nb[s];
int j2 = nb[s+1];
int nscol = j2 - j1; // number of columns in the s-th supernode column
int i1, i2;
if (ptr_by_column) {
i1 = mb[j1];
i2 = mb[j1+1];
} else {
i1 = mb[s];
i2 = mb[s+1];
}
int nsrow = i2 - i1; // "total" number of rows in all the supernodes (diagonal+off-diagonal)
int nsrow2 = nsrow - nscol; // "total" number of rows in all the off-diagonal supernodes
int ps2 = i1 + nscol; // offset into rowind
int psx; // offset into data, Lx[s][s]
if (ptr_by_column) {
psx = colptr[j1];
} else {
psx = colptr[s];
}
/* diagonal block */
// for each column (or row due to symmetry), the diagonal supernodal block is stored (in ascending order of row indexes) first
// so that we can do TRSM on the diagonal block
for (int ii = 0; ii < nscol; ii++) {
// lower-triangular part
for (int jj = 0; jj < ii; jj++) {
hv(hr(j1+ii)+jj) = Lx[psx + (ii + jj*nsrow)];
}
// diagonal
if (unit_diag) {
hv(hr(j1+ii)+ii) = one;
} else {
hv(hr(j1+ii)+ii) = Lx[psx + (ii + ii*nsrow)];
}
}
/* off-diagonal blocks */
int nsup = 0;
for (int jj = 0; jj < nscol; jj++) {
for (int kk = 0; kk < nsrow2; kk++) {
int irow = rowind[ps2 + kk];
hv(off(irow)+jj) = Lx[psx + (nscol+kk + jj*nsrow)];
supid = map (irow);
if (check (supid) == 0) {
check (supid) = 1;
sup (nsup) = supid;
nsup ++;
}
}
}
// shift pointers, and reset check
for (int i = 0; i < nsup; i++ ) {
supid = sup (i);
for (int ii = nb[supid]; ii < nb[supid+1]; ii++) {
off (ii) += nscol;
}
check (supid) = 0;
}
}
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
std::cout << " read_supernodal_valuesL" << std::endl;
std::cout << " * Matrix size = " << n << std::endl;
std::cout << " * Total nnz = " << hr (n) << std::endl;
std::cout << " * nnz / n = " << hr (n)/n << std::endl;
double time = timer.seconds ();
std::cout << " > Time : " << time << std::endl;
#endif
// invert blocks (TODO done on host for now)
invert_supernodal_columns (kernelHandle, unit_diag, nsuper, nb, hr, hc, hv);
// deepcopy
Kokkos::deep_copy (values_view, hv);
// create crs
crsmat_t crsmat ("CrsMatrix", n, values_view, static_graph);
return crsmat;
}
/* ========================================================================================= */
template <typename crsmat_t, typename KernelHandle, typename host_crsmat_t>
void split_crsmat(KernelHandle *kernelHandleL, host_crsmat_t superluL) {
using graph_t = typename crsmat_t::StaticCrsGraphType;
using row_map_view_t = typename graph_t::row_map_type::non_const_type;
using cols_view_t = typename graph_t::entries_type::non_const_type;
using values_view_t = typename crsmat_t::values_type::non_const_type;
using row_map_view_host_t = typename row_map_view_t::HostMirror;
using cols_view_host_t = typename cols_view_t::HostMirror;
using values_view_host_t = typename values_view_t::HostMirror;
using scalar_t = typename KernelHandle::nnz_scalar_t;
using size_type = typename KernelHandle::size_type;
const scalar_t zero (0.0);
// get sparse-triangular solve handle
auto *handleL = kernelHandleL->get_sptrsv_handle ();
Kokkos::Timer timer;
double time1 = 0.0;
double time2 = 0.0;
// ===================================================================
// number of supernodes per level
auto nodes_per_level = handleL->get_nodes_per_level ();
auto hnodes_per_level = Kokkos::create_mirror_view (nodes_per_level);
Kokkos::deep_copy (hnodes_per_level, nodes_per_level);
// id of supernodes at each level
auto nodes_grouped_by_level = handleL->get_nodes_grouped_by_level ();
auto nodes_grouped_by_level_host = Kokkos::create_mirror_view (nodes_grouped_by_level);
Kokkos::deep_copy (nodes_grouped_by_level_host, nodes_grouped_by_level);
// load graphs
auto graphL = handleL->get_graph_host ();
// crsgraph for L
int nrows = graphL.numRows ();
auto row_mapL = graphL.row_map;
auto entriesL = graphL.entries;
auto values = superluL.values;
auto valuesL = Kokkos::create_mirror_view (values);
Kokkos::deep_copy (valuesL, values);
int node_count = 0; // number of supernodes processed
int nlevels = handleL->get_num_levels ();
bool invert_offdiag = handleL->get_invert_offdiagonal ();
const int* supercols_host = handleL->get_supercols_host ();
// form crsgraph for each submatrix at each level
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
int oldNnz = row_mapL (nrows);
#endif
int newNnz = 0;
std::vector <crsmat_t> sub_crsmats (nlevels);
std::vector <crsmat_t> diag_blocks (nlevels);
for (int lvl = 0; lvl < nlevels; ++lvl) {
timer.reset ();
// > count nnz
int nnzL = 0;
int nnzD = 0;
int lvl_nodes = hnodes_per_level (lvl); // number of supernodes at this level
for (int league_rank = 0; league_rank < lvl_nodes; league_rank++) {
auto s = nodes_grouped_by_level_host (node_count + league_rank);
// supernodal column size
int j1 = supercols_host[s];
int j2 = supercols_host[s+1];
int nscol = j2 - j1 ; // number of columns in the s-th supernode column
for (int j = j1; j < j2; j++) {
for (size_type k = row_mapL (j); k < row_mapL (j+1); k++) {
if (valuesL (k) != zero) {
if (invert_offdiag || k >= row_mapL (j) + nscol) {
nnzL ++;
} else {
nnzD ++;
}
}
}
}
}
// allocate subgraph
row_map_view_t rowmap_view ("rowmap_view", nrows+1);
cols_view_t column_view ("colmap_view", nnzL);
values_view_t values_view ("values_view", nnzL);
row_map_view_host_t hr = Kokkos::create_mirror_view (rowmap_view);
cols_view_host_t hc = Kokkos::create_mirror_view (column_view);
values_view_host_t hv = Kokkos::create_mirror_view (values_view);
// allocate subgraph, just for diagonal blocks
row_map_view_t rowmapD_view ("rowmapD_view", nrows+1);
cols_view_t columnD_view ("colmapD_view", nnzD);
values_view_t valuesD_view ("valuesD_view", nnzD);
row_map_view_host_t hrD = Kokkos::create_mirror_view (rowmapD_view);
cols_view_host_t hcD = Kokkos::create_mirror_view (columnD_view);
values_view_host_t hvD = Kokkos::create_mirror_view (valuesD_view);
// create subgraph
hr (0) = 0;
hrD (0) = 0;
if (handleL->transpose_spmv()) { // NOTE: it always transpose, for now
// >> store submatrix with transpose (CSR -> CSC or CSC -> CSR) <<
// count nnz / row
for (int j = 0; j <= nrows; j++) {
hr (j) = 0;
hrD (j) = 0;
}
nnzL = 0;
nnzD = 0;
for (int league_rank = 0; league_rank < lvl_nodes; league_rank++) {
auto s = nodes_grouped_by_level_host (node_count + league_rank);
int j1 = supercols_host[s]; // start of this supernode
int j2 = supercols_host[s+1]; // start of next supernode
int nscol = j2 - j1 ; // number of columns in the s-th supernode column
for (int j = j1; j < j2; j++) {
for (size_type k = row_mapL (j); k < row_mapL (j+1); k++) {
if (valuesL (k) != zero) {
if (invert_offdiag || k >= row_mapL (j) + nscol) {
hr (1 + entriesL (k)) ++;
nnzL ++;
} else {
hrD (1 + entriesL (k)) ++;
nnzD ++;
}
}
}
}
}
for (int j = 0; j < nrows; j++) {
hr (j+1) += hr (j);
hrD (j+1) += hrD (j);
}
// insert nzs
for (int league_rank = 0; league_rank < lvl_nodes; league_rank++) {
auto s = nodes_grouped_by_level_host (node_count + league_rank);
// start/end column id for this supernodal column at this level
// (these column ids are sorted in ascending order at each level)
int j1 = supercols_host[s]; // start of this supernode
int j2 = supercols_host[s+1]; // start of next supernode
int nscol = j2 - j1 ; // number of columns in the s-th supernode column
for (int j = j1; j < j2; j++) {
// diagonals
for (size_type k = row_mapL (j); k < row_mapL (j) + nscol; k++) {
// remove zeros
if (valuesL (k) != zero) {
if (invert_offdiag) {
hc (hr (entriesL (k))) = j;
hv (hr (entriesL (k))) = valuesL (k);
hr (entriesL (k)) ++;
} else {
hcD (hrD (entriesL (k))) = j;
hvD (hrD (entriesL (k))) = valuesL (k);
hrD (entriesL (k)) ++;
}
}
}
// off-diagonals
for (size_type k = row_mapL (j) + nscol; k < row_mapL (j+1); k++) {
// remove zeros, and minus for updating off-diagonal elements with Spmv
if (valuesL (k) != zero) {
hc (hr (entriesL (k))) = j;
hv (hr (entriesL (k))) = -valuesL (k);
hr (entriesL (k)) ++;
}
}
}
}
// fix pointers
for (int j = nrows; j > 0; j--) {
hr (j) = hr (j-1);
hrD (j) = hrD (j-1);
}
hr (0) = 0;
hrD (0) = 0;
} else {
// >> store submatrix without transpose (CSC -> CSC or CSR -> CSR) <<
nnzL = 0;
nnzD = 0;
int j0 = 0; // end of previous supernode at this level (not including this column)
for (int league_rank = 0; league_rank < lvl_nodes; league_rank++) {
auto s = nodes_grouped_by_level_host (node_count + league_rank);
// start/end column id for this supernodal column at this level
// (these column ids are sorted in ascending order at each level)
int j1 = supercols_host[s]; // start of this supernode
int j2 = supercols_host[s+1]; // start of next supernode
int nscol = j2 - j1 ; // number of columns in the s-th supernode column
// insert empty columns for the columns skipped (between the previous and this supernodes)
for (int j = j0+1; j <= j1; j++) {
hr (j) = hr (j-1);
hrD (j) = hrD (j-1);
}
// insert the columns in this supernode
for (int j = j1; j < j2; j++) {
// diagonals
for (size_type k = row_mapL (j); k < row_mapL (j) + nscol; k++) {
// remove zeros
if (valuesL (k) != zero) {
if (invert_offdiag) {
hc (nnzL) = entriesL (k);
hv (nnzL) = valuesL (k);
nnzL ++;
} else {
hcD (nnzD) = entriesL (k);
hvD (nnzD) = valuesL (k);
nnzD ++;
}
}
}
// off-diagonals
for (size_type k = row_mapL (j) + nscol; k < row_mapL (j+1); k++) {
// remove zeros, and minus for updating off-diagonal elements with Spmv
if (valuesL (k) != zero) {
hc (nnzL) = entriesL (k);
hv (nnzL) = -valuesL (k);
nnzL ++;
}
}
hr (j+1) = nnzL;
hrD (j+1) = nnzD;
}
j0 = j2; // update the last column of the processed supernode (not including this column)
}
// insert empty columns at the end
for (int j = j0+1; j <= nrows; j++) {
hr (j) = hr (j-1);
hrD (j) = hrD (j-1);
}
}
newNnz += nnzL+nnzD;
time1 += timer.seconds ();
// create crs-graph
timer.reset ();
Kokkos::deep_copy (rowmap_view, hr);
Kokkos::deep_copy (column_view, hc);
Kokkos::deep_copy (values_view, hv);
graph_t sub_graph(column_view, rowmap_view);
sub_crsmats[lvl] = crsmat_t("CrsMatrix", nrows, values_view, sub_graph);
if (!invert_offdiag) {
Kokkos::deep_copy (rowmapD_view, hrD);
Kokkos::deep_copy (columnD_view, hcD);
Kokkos::deep_copy (valuesD_view, hvD);
graph_t diag_graph(columnD_view, rowmapD_view);
diag_blocks[lvl] = crsmat_t("DiagMatrix", nrows, valuesD_view, diag_graph);
}
//std::cout << " > split nnz(" << lvl << ") = " << nnzL+nnzD << std::endl;
time2 += timer.seconds ();
// update the number of supernodes processed
node_count += lvl_nodes;
}
handleL->set_submatrices (sub_crsmats);
if (!invert_offdiag) {
handleL->set_diagblocks (diag_blocks);
}
#ifdef KOKKOS_SPTRSV_SUPERNODE_PROFILE
std::cout << " split_crsmat" << std::endl;
std::cout << " > Time to split to submatrices : " << time1 << std::endl;
std::cout << " > Time to copy submatrices to device: " << time2 << std::endl;
std::cout << " > Total NNZ : " << oldNnz << " -> " << newNnz
<< std::endl << std::endl;
#endif
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* For numeric computation */
template <typename crsmat_input_t,
typename KernelHandle>
void sptrsv_compute(
KernelHandle *kernelHandleL,
crsmat_input_t L)
{
// ===================================================================
// load sptrsv-handles
auto *handleL = kernelHandleL->get_sptrsv_handle ();
if (!(handleL->is_symbolic_complete())) {
std::cout << std::endl
<< " ** needs to call sptrsv_symbolic before calling sptrsv_numeric **"
<< std::endl << std::endl;
return;
}
bool merged = handleL->get_merge_supernodes ();
if (merged) {
// TODO: follow what's done in sptrsv_compute in superlu
std::cout << std::endl
<< " ** merge is not supported through this interface, yet **"
<< std::endl << std::endl;
return;
}
// ===================================================================
// load supernodes
int nsuper = handleL->get_num_supernodes ();
const int *supercols = handleL->get_supercols_host ();
// ==============================================
// load crsGraph
//auto graph = handleL->get_original_graph_host (); // graph stored in handle (before merge)
auto graph = handleL->get_graph (); // graph stored in handle (before merge)
auto graph_host = handleL->get_graph_host (); // graph stored in handle (before merge)
auto row_map = graph_host.row_map;
auto entries = graph_host.entries;
auto nrows = graph_host.numRows ();
// from input CrsMatrix
auto values = L.values; // numerical values from input (host), output will be stored in handle
// ==============================================
// read numerical values of L from Cholmod
using crsmat_t = typename KernelHandle::SPTRSVHandleType::crsmat_t;
bool ptr_by_column = true;
auto crsmatL = read_supernodal_valuesL<crsmat_t> (kernelHandleL, nrows, nsuper, ptr_by_column, row_map.data (), supercols,
row_map.data (), entries.data (), values.data (), graph);
// ===================================================================
bool useSpMV = (handleL->get_algorithm () == SPTRSVAlgorithm::SUPERNODAL_SPMV ||
handleL->get_algorithm () == SPTRSVAlgorithm::SUPERNODAL_SPMV_DAG);
if (useSpMV) {
// ----------------------------------------------------
// split the matrix into submatrices for spmv at each level
split_crsmat<crsmat_t> (kernelHandleL, crsmatL);
}
// ==============================================
// save crsmat
handleL->set_crsmat (crsmatL);
// ===================================================================
handleL->set_numeric_complete ();
}
} // namespace Experimental
} // namespace KokkosSparse
#endif // KOKKOSKERNELS_ENABLE_TPL_BLAS
#endif // KOKKOSSPARSE_SPTRSV_SUPERNODE_HPP_
|
/* Copyright 2020 Stanford University
* Copyright 2020 Los Alamos National Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <cstring>
#include <unistd.h>
#include <time.h>
#include "task_throughput.h"
#include <realm/cmdline.h>
namespace TestConfig {
int tasks_per_processor = 256;
int launching_processors = 1;
int task_argument_size = 0;
bool remote_tasks = false;
bool chain_tasks = false;
bool with_profiling = false;
bool skip_launch_procs = false;
bool use_posttriger_barrier = false;
bool group_procs = false;
};
// TASK IDs
enum {
TOP_LEVEL_TASK = Processor::TASK_ID_FIRST_AVAILABLE+0,
TASK_LAUNCHER,
DUMMY_TASK,
DUMMY_GPU_TASK,
PROFILER_TASK,
};
Logger log_app("app");
// dummy tasks are marked as either "first", "middle", or "last", and prioritized the same way
enum TaskOrder {
FIRST_TASK = 10,
MIDDLE_TASK = 9,
LAST_TASK = 8,
};
struct TestTaskArgs {
int which_task;
RegionInstance instance;
Barrier posttrigger_barrier;
Barrier finish_barrier;
};
struct TestTaskData {
int first_count;
int last_count;
int total_tasks;
double start_time;
};
namespace FieldIDs {
enum {
TASKDATA,
};
};
void dummy_task_body(const void *args, size_t arglen,
const void *userdata, size_t userlen, Processor p)
{
const TestTaskArgs& ta = *(const TestTaskArgs *)args;
int task_type = ta.which_task;
// quick out for most tasks
if(task_type == MIDDLE_TASK) return;
if(TestConfig::use_posttriger_barrier && (task_type == FIRST_TASK)) {
#if 0
// need scheduler lock stuff
Processor::enable_scheduler_lock();
ta.posttrigger_barrier.wait();
Processor::disable_scheduler_lock();
#else
while(!ta.posttrigger_barrier.has_triggered());
#endif
}
AffineAccessor<TestTaskData, 1> ra(ta.instance, FieldIDs::TASKDATA);
TestTaskData& mydata = ra[0];
if(task_type == FIRST_TASK) {
double t = Clock::current_time();
log_app.debug() << "first task on " << p << ": " << t;
assert(mydata.last_count == 0);
if(mydata.first_count == 0)
mydata.start_time = t;
mydata.first_count++;
}
if(task_type == LAST_TASK) {
double t = Clock::current_time();
log_app.debug() << "last task on " << p << ": " << t;
assert(mydata.last_count < mydata.first_count);
mydata.last_count++;
if(mydata.last_count == mydata.first_count) {
double elapsed = t - mydata.start_time;
double per_task = elapsed / (mydata.last_count *
TestConfig::tasks_per_processor);
log_app.print() << "tasks complete on " << p << ": "
<< (1e6 * per_task) << " us/task, "
<< (1.0 / per_task) << " tasks/s";
ta.finish_barrier.arrive();
}
}
}
void dummy_cpu_task(const void *args, size_t arglen,
const void *userdata, size_t userlen, Processor p)
{
dummy_task_body(args, arglen, userdata, userlen, p);
}
void profiler_task(const void *args, size_t arglen,
const void *userdata, size_t userlen, Processor p)
{
// do nothing with the data
}
struct LauncherArgs {
Barrier start_barrier;
Barrier posttrigger_barrier;
Barrier finish_barrier;
std::map<Processor, RegionInstance> instances;
};
template<typename S>
bool serdez(S& s, const LauncherArgs& t)
{
return ((s & t.start_barrier) &&
(s & t.posttrigger_barrier) &&
(s & t.finish_barrier) &&
(s & t.instances));
}
void task_launcher(const void *args, size_t arglen,
const void *userdata, size_t userlen, Processor p)
{
Serialization::FixedBufferDeserializer fbd(args, arglen);
LauncherArgs la;
bool ok = fbd >> la;
assert(ok);
Machine::ProcessorQuery pq(Machine::get_machine());
if(!TestConfig::remote_tasks)
pq = pq.same_address_space_as(p);
ProfilingRequestSet prs;
if(TestConfig::with_profiling) {
using namespace Realm::ProfilingMeasurements;
prs.add_request(p, PROFILER_TASK).add_measurement<OperationTimeline>();
}
// allocate some space for our test arguments
int argsize = sizeof(TestTaskArgs);
if(TestConfig::task_argument_size > argsize)
argsize = TestConfig::task_argument_size;
TestTaskArgs *tta = (TestTaskArgs *)(alloca(argsize));
// time how long this takes us
double t1 = Clock::current_time();
int total_tasks = 0;
std::vector<Processor> targets;
for(Machine::ProcessorQuery::iterator it = pq.begin(); it != pq.end(); ++it)
if(!(TestConfig::skip_launch_procs && ((*it) == p)))
targets.push_back(*it);
if(TestConfig::group_procs && !targets.empty()) {
Processor p = ProcessorGroup::create_group(targets);
la.instances[p] = la.instances[targets[0]];
if(targets.size() > 1)
la.finish_barrier.arrive(targets.size() - 1);
targets.clear();
targets.push_back(p);
}
// round-robin tasks across target processors in case barrier trigger
// is slower than task execution rate
std::map<Processor, Event> preconds;
// always have to have at least 2 tasks - one FIRST and one LAST
if(TestConfig::tasks_per_processor < 2)
TestConfig::tasks_per_processor = 2;
for(int i = 0; i < TestConfig::tasks_per_processor; i++) {
int which = ((i == 0) ? FIRST_TASK :
(i == (TestConfig::tasks_per_processor - 1)) ? LAST_TASK :
MIDDLE_TASK);
tta->which_task = which;
tta->posttrigger_barrier = la.posttrigger_barrier;
tta->finish_barrier = la.finish_barrier;
for(std::vector<Processor>::const_iterator it = targets.begin(); it != targets.end(); ++it) {
tta->instance = la.instances[*it];
assert(tta->instance.exists());
Processor::TaskFuncID task_id = DUMMY_TASK;
#ifdef REALM_USE_CUDA
if((*it).kind() == Processor::TOC_PROC)
task_id = DUMMY_GPU_TASK;
#endif
if(i == 0)
preconds[*it] = la.start_barrier;
Event e = (*it).spawn(task_id, tta, argsize, prs, preconds[*it], which);
if(TestConfig::chain_tasks)
preconds[*it] = e;
total_tasks++;
}
}
double t2 = Clock::current_time();
double spawn_rate = total_tasks / (t2 - t1);
log_app.print() << "spawn rate on " << p << ": " << spawn_rate << " tasks/s";
// we're all done - we can arrive at the start barrier and then finish this task
double t3 = Clock::current_time();
la.start_barrier.arrive();
double t4 = Clock::current_time();
if(!TestConfig::chain_tasks) {
double trigger_rate = total_tasks / (t4 - t3);
log_app.print() << "trigger rate on " << p << ": " << trigger_rate << " tasks/s";
}
if(TestConfig::use_posttriger_barrier)
la.posttrigger_barrier.arrive();
if(TestConfig::skip_launch_procs)
la.finish_barrier.arrive();
}
void top_level_task(const void *args, size_t arglen,
const void *userdata, size_t userlen, Processor p)
{
LauncherArgs launch_args;
// go through all processors and organize by address space
std::map<AddressSpace, std::vector<Processor> > all_procs;
std::map<AddressSpace, std::vector<Processor> > loc_procs;
int total_procs = 0;
{
std::set<Event> events;
Machine::ProcessorQuery pq(Machine::get_machine());
for(Machine::ProcessorQuery::iterator it = pq.begin(); it != pq.end(); ++it) {
Processor p = *it;
AddressSpace a = p.address_space();
all_procs[a].push_back(p);
if(p.kind() == Processor::LOC_PROC)
loc_procs[a].push_back(p);
total_procs++;
Memory m = Machine::MemoryQuery(Machine::get_machine())
.has_affinity_to(p)
.first();
#ifdef REALM_USE_CUDA
// instance is used by host-side code, so pick a sysmem for GPUs
if(p.kind() == Processor::TOC_PROC)
m = Machine::MemoryQuery(Machine::get_machine())
.same_address_space_as(p)
.only_kind(Memory::SYSTEM_MEM)
.first();
#endif
assert(m.exists());
Rect<1> r(0, 0);
RegionInstance i;
std::map<FieldID, size_t> field_sizes;
field_sizes[FieldIDs::TASKDATA] = sizeof(TestTaskData);
RegionInstance::create_instance(i, m, r,
field_sizes,
0, // SOA
ProfilingRequestSet()).wait();
assert(i.exists());
launch_args.instances[p] = i;
{
std::vector<CopySrcDstField> dsts(1);
dsts[0].inst = i;
dsts[0].field_id = FieldIDs::TASKDATA;
dsts[0].size = sizeof(TestTaskData);
TestTaskData ival;
ival.first_count = 0;
ival.last_count = 0;
ival.start_time = 0;
r.fill(dsts, ProfilingRequestSet(),
&ival, sizeof(ival)).wait();
}
}
}
// two barriers will coordinate the running of the test tasks
// 1) one triggered by each of the launcher tasks that starts the tasks running
// 2) one triggered by each processor when all task launches have been seen
launch_args.start_barrier = Barrier::create_barrier(all_procs.size() *
TestConfig::launching_processors);
launch_args.posttrigger_barrier = Barrier::create_barrier(all_procs.size() *
TestConfig::launching_processors);
launch_args.finish_barrier = Barrier::create_barrier(total_procs);
// serialize the launcher args
void *args_data;
size_t args_size;
{
Serialization::DynamicBufferSerializer dbs(256);
bool ok = dbs << launch_args;
assert(ok);
args_size = dbs.bytes_used();
args_data = dbs.detach_buffer();
}
// spawn launcher tasks in each address space
for(std::map<AddressSpace, std::vector<Processor> >::const_iterator it = all_procs.begin();
it != all_procs.end();
++it) {
const std::vector<Processor>& lp = loc_procs[it->first];
assert(lp.size() >= (size_t)(TestConfig::launching_processors));
for(int i = 0; i < TestConfig::launching_processors; i++) {
Processor p = lp[i];
// no need to grab the finish event - we wait indirectly via the barrier
p.spawn(TASK_LAUNCHER, args_data, args_size);
}
}
free(args_data);
// all done - wait for everything to finish via the finish_barrier
launch_args.finish_barrier.wait();
}
int main(int argc, char **argv)
{
Runtime r;
bool ok = r.init(&argc, &argv);
assert(ok);
CommandLineParser cp;
cp.add_option_int("-tpp", TestConfig::tasks_per_processor)
.add_option_int("-lp", TestConfig::launching_processors)
.add_option_int("-args", TestConfig::task_argument_size)
.add_option_bool("-remote", TestConfig::remote_tasks)
.add_option_bool("-chain", TestConfig::chain_tasks)
.add_option_bool("-noself", TestConfig::skip_launch_procs)
.add_option_bool("-post", TestConfig::use_posttriger_barrier)
.add_option_bool("-prof", TestConfig::with_profiling)
.add_option_bool("-group", TestConfig::group_procs);
ok = cp.parse_command_line(argc, (const char **)argv);
assert(ok);
r.register_task(TOP_LEVEL_TASK, top_level_task);
r.register_task(TASK_LAUNCHER, task_launcher);
r.register_task(DUMMY_TASK, dummy_cpu_task);
r.register_task(PROFILER_TASK, profiler_task);
#ifdef REALM_USE_CUDA
Processor::register_task_by_kind(Processor::TOC_PROC,
false /*!global*/,
DUMMY_GPU_TASK,
CodeDescriptor(dummy_gpu_task),
ProfilingRequestSet()).wait();
#endif
// select a processor to run the top level task on
Processor p = Machine::ProcessorQuery(Machine::get_machine())
.only_kind(Processor::LOC_PROC)
.first();
assert(p.exists());
// collective launch of a single task - everybody gets the same finish event
Event e = r.collective_spawn(p, TOP_LEVEL_TASK, 0, 0);
// request shutdown once that task is complete
r.shutdown(e);
// now sleep this thread until that shutdown actually happens
r.wait_for_shutdown();
return 0;
}
|
/*
* Copyright (C) 2020 Smirnov Vladimir / mapron1@gmail.com
* SPDX-License-Identifier: MIT
* See LICENSE file for details.
*/
#pragma once
#include <QString>
#include <QSettings>
class QWidget;
namespace FreeHeroes::Gui {
class IAppSettings {
public:
virtual ~IAppSettings() = default;
struct Sound {
int musicVolumePercent = 20;
int effectsVolumePercent = 20;
};
struct Battle {
int walkTimePercent = 100;
int otherTimePercent = 100;
int shiftSpeedPercent = 50;
bool displayGrid = true;
bool displayPath = false;
bool logMoves = false;
bool retaliationHint = true;
bool massDamageHint = true;
bool counterDamageHint = true;
};
struct AppGlobal {
int logLevel = 6;
QString localeId = "";
QStringList localeItems;
QString databaseId = "FH_HotA";
QStringList databaseItems;
};
struct UI {
bool displayAbsMoraleLuck = true;
bool clampAbsMoraleLuck = true;
};
struct AllSettings {
Sound sound;
Battle battle;
AppGlobal global;
UI ui;
};
virtual const Sound& sound() const noexcept = 0;
virtual const Battle& battle() const noexcept = 0;
virtual const AppGlobal& global() const noexcept = 0;
virtual const UI& ui() const noexcept = 0;
virtual QSettings& uiSettings() = 0;
virtual void showSettingsEditor(QWidget* parent) = 0;
};
}
|
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdint>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <vector>
#include <queue>
#include <unistd.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include "GameMessage.pb.h"
#define IMPORT_USER
#include "User.h"
const int MaxClient = 128;
int fd[MaxClient];
uint8_t Buffer[MaxClient][40960];
uint32_t Size[MaxClient];
uint32_t MessageType[MaxClient];
uint32_t MessageLen[MaxClient];
uint32_t NowPlayerID = 0;
uint32_t PlayerID[MaxClient];
int i = 0, maxi = 0;
inline void Init()
{
InitUserInfo();
memset(Size, sizeof(Size), 0);
memset(MessageType, sizeof(MessageType), 0);
memset(MessageLen, sizeof(MessageLen), 0);
memset(PlayerID, sizeof(PlayerID), 0);
puts("Init Done");
}
inline void SendAll(int i, uint32_t SumLen)
{
for(int j=1; j<=maxi; j+=1)
{
if(fd[j] < 0)
{
continue;
}
send(fd[j], Buffer[i], SumLen, 0); // DANGER
}
}
inline void ProcessEvent(int i)
{
switch(MessageType[i])
{
case 1:
{
PLoginRequest LoginRequest;
LoginRequest.ParseFromArray(Buffer[i], Size[i]);
puts("Login Request:");
printf("%s\n",LoginRequest.username().c_str());
printf("%s\n",LoginRequest.password().c_str());
if(UserLoginInfo.count(LoginRequest.username()) &&
UserLoginInfo[LoginRequest.username()] == LoginRequest.password())
{
++NowPlayerID;
PlayerID[i] = NowPlayerID;
PLoginRespond LoginRespond;
LoginRespond.set_allowlogin(1);
LoginRespond.set_playernumber(1); // HARD CODE
LoginRespond.set_selfid(NowPlayerID);
uint32_t SingleMessageType = 2;
uint32_t SingleMessageLen = LoginRespond.ByteSizeLong();
memcpy(Buffer[i] + 0, &SingleMessageType, 4);
memcpy(Buffer[i] + 4, &SingleMessageLen, 4);
LoginRespond.SerializeToArray(Buffer[i] + 8, SingleMessageLen);
uint32_t sendLen = send(fd[i], Buffer[i], SingleMessageLen + 8, 0); // DANGER
printf("New Client (%d)\n", NowPlayerID);
PGameBegin GameBegin;
GameBegin.set_selfid(1); // HARD CODE
SingleMessageType = 9;
SingleMessageLen = GameBegin.ByteSizeLong();
memcpy(Buffer[i] + 0, &SingleMessageType, 4);
memcpy(Buffer[i] + 4, &SingleMessageLen, 4);
GameBegin.SerializeToArray(Buffer[i] + 8, SingleMessageLen);
if(NowPlayerID == 2) // HARD CODE
{
SendAll(i, SingleMessageLen + 8);
}
}
else
{
PLoginRespond LoginRespond;
LoginRespond.set_allowlogin(0);
LoginRespond.set_playernumber(1); // HARD CODE
LoginRespond.set_selfid(1); // HARD CODE
uint32_t SingleMessageType = 2;
uint32_t SingleMessageLen = LoginRespond.ByteSizeLong();
memcpy(Buffer[i] + 0, &SingleMessageType, 4);
memcpy(Buffer[i] + 4, &SingleMessageLen, 4);
LoginRespond.SerializeToArray(Buffer[i] + 8, SingleMessageLen);
uint32_t sendLen = send(fd[i], Buffer[i], SingleMessageLen + 8, 0); // DANGER
}
}break;
case 3:
{
PActionRequest ActionRequest;
ActionRequest.ParseFromArray(Buffer[i], Size[i]);
uint32_t ActionPlayerID = PlayerID[i]; // DANGER
PPlayerAction PlayerAction;
PlayerAction.set_playerid(ActionPlayerID);
PlayerAction.set_actiontype(ActionRequest.actiontype());
uint32_t SingleMessageType = 4;
uint32_t SingleMessageLen = PlayerAction.ByteSizeLong();
memcpy(Buffer[i] + 0, &SingleMessageType, 4);
memcpy(Buffer[i] + 4, &SingleMessageLen, 4);
PlayerAction.SerializeToArray(Buffer[i] + 8, SingleMessageLen);
SendAll(i, SingleMessageLen + 8);
// uint32_t sendLen = send(fd[i], Buffer[i], SingleMessageLen + 8, 0); // DANGER
}break;
case 5:
{
PMoveRequest MoveRequest;
MoveRequest.ParseFromArray(Buffer[i], Size[i]);
uint32_t MovePlayerID = PlayerID[i];
PPlayerMove PlayerMove;
PlayerMove.set_playerid(MovePlayerID);
PlayerMove.set_movetype(MoveRequest.movetype());
PlayerMove.set_movevalue(MoveRequest.movevalue());
uint32_t SingleMessageType = 6;
uint32_t SingleMessageLen = PlayerMove.ByteSizeLong();
memcpy(Buffer[i] + 0, &SingleMessageType, 4);
memcpy(Buffer[i] + 4, &SingleMessageLen, 4);
PlayerMove.SerializeToArray(Buffer[i] + 8, SingleMessageLen);
SendAll(i, SingleMessageLen + 8);
// uint32_t sendLen = send(fd[i], Buffer[i], SingleMessageLen + 8, 0); // DANGER
}break;
case 7:
{
PTurnRequest TurnRequest;
TurnRequest.ParseFromArray(Buffer[i], Size[i]);
uint32_t TurnPlayerID = PlayerID[i];
PPlayerTurn PlayerTurn;
PlayerTurn.set_playerid(TurnPlayerID);
PlayerTurn.set_turntype(TurnRequest.turntype());
PlayerTurn.set_turnvalue(TurnRequest.turnvalue());
uint32_t SingleMessageType = 8;
uint32_t SingleMessageLen = PlayerTurn.ByteSizeLong();
memcpy(Buffer[i] + 0, &SingleMessageType, 4);
memcpy(Buffer[i] + 4, &SingleMessageLen, 4);
PlayerTurn.SerializeToArray(Buffer[i] + 8, SingleMessageLen);
SendAll(i, SingleMessageLen + 8);
// uint32_t sendLen = send(fd[i], Buffer[i], SingleMessageLen + 8, 0); // DANGER
}break;
}
}
int main()
{
Init();
struct epoll_event event;
struct epoll_event wait_event;
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in my_addr;
bzero(&my_addr, sizeof(my_addr));
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(3000);
my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
bind(sockfd, (struct sockaddr *)&my_addr, sizeof(my_addr));
listen(sockfd, 10);
puts("Server Start");
memset(fd, -1, sizeof(fd));
fd[0] = sockfd;
int epfd = epoll_create(10);
if(-1 == epfd)
{
puts("error in creating epfd");
return -1;
}
event.data.fd = sockfd;
event.events = EPOLLIN;
int ret = epoll_ctl(epfd, EPOLL_CTL_ADD, sockfd, &event);
if(-1 == ret)
{
puts("error in adding server");
return -1;
}
while(true)
{
ret = epoll_wait(epfd, &wait_event, maxi + 1, -1);
if(ret == 0){
printf("time out\n");
continue;
}
else if(ret == -1){
printf("epoll");
exit(2);
}
if((sockfd == wait_event.data.fd) && (EPOLLIN == wait_event.events & EPOLLIN))
{
struct sockaddr_in cli_addr;
unsigned int clilen = sizeof(cli_addr);
int connfd = accept(sockfd, (struct sockaddr *)&cli_addr, &clilen);
for(i=1; i<MaxClient; i+=1)
{
if(fd[i] < 0)
{
fd[i] = connfd;
event.data.fd = connfd;
event.events = EPOLLIN;
ret = epoll_ctl(epfd, EPOLL_CTL_ADD, connfd, &event);
if(-1 == ret)
{
puts("error in adding client");
return -1;
}
else
{
puts("new client connection");
}
break;
}
}
if(i > maxi) maxi = i;
if(--ret <= 0) continue;
}
for(i=1; i<=maxi; i+=1)
{
if(fd[i] < 0)
{
continue;
}
if((fd[i] == wait_event.data.fd) && (EPOLLIN == wait_event.events & EPOLLIN))
{
int len = 0;
if(!MessageType[i])
{
len = recv(fd[i], Buffer[i]+Size[i], 4-Size[i], 0);
Size[i] += len;
if(Size[i] >= 4)
{
memcpy(&MessageType[i], Buffer[i], 4);
Size[i] = 0;
}
}else if(!MessageLen[i])
{
len = recv(fd[i], Buffer[i]+Size[i], 4-Size[i], 0);
Size[i] += len;
if(Size[i] >= 4)
{
memcpy(&MessageLen[i], Buffer[i], 4);
Size[i] = 0;
}
}else
{
len = recv(fd[i], Buffer[i]+Size[i], MessageLen[i]-Size[i], 0);
Size[i] += len;
if(Size[i] >= MessageLen[i])
{
ProcessEvent(i);
MessageType[i] = 0;
MessageLen[i] = 0;
Size[i] = 0;
}
}
if(--ret <= 0 ) break;
}
}
}
return 0;
}
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "amount.h"
#include "base58.h"
#include "chain.h"
#include "core_io.h"
#include "init.h"
#include "main.h"
#include "net.h"
#include "netbase.h"
#include "policy/rbf.h"
#include "rpcserver.h"
#include "timedata.h"
#include "util.h"
#include "utilmoneystr.h"
#include "wallet.h"
#include "walletdb.h"
#include <stdint.h>
#include <boost/assign/list_of.hpp>
#include <univalue.h>
using namespace std;
int64_t nWalletUnlockTime;
static CCriticalSection cs_nWalletUnlockTime;
std::string HelpRequiringPassphrase()
{
return pwalletMain && pwalletMain->IsCrypted()
? "\nRequires wallet passphrase to be set with walletpassphrase call."
: "";
}
bool EnsureWalletIsAvailable(bool avoidException)
{
if (!pwalletMain)
{
if (!avoidException)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
else
return false;
}
return true;
}
void EnsureWalletIsUnlocked()
{
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
}
void WalletTxToJSON(const CWalletTx& wtx, UniValue& entry)
{
int confirms = wtx.GetDepthInMainChain();
entry.push_back(Pair("confirmations", confirms));
if (wtx.IsCoinBase())
entry.push_back(Pair("generated", true));
if (confirms > 0)
{
entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex()));
entry.push_back(Pair("blockindex", wtx.nIndex));
entry.push_back(Pair("blocktime", mapBlockIndex[wtx.hashBlock]->GetBlockTime()));
} else {
entry.push_back(Pair("trusted", wtx.IsTrusted()));
}
uint256 hash = wtx.GetHash();
entry.push_back(Pair("txid", hash.GetHex()));
UniValue conflicts(UniValue::VARR);
BOOST_FOREACH(const uint256& conflict, wtx.GetConflicts())
conflicts.push_back(conflict.GetHex());
entry.push_back(Pair("walletconflicts", conflicts));
entry.push_back(Pair("time", wtx.GetTxTime()));
entry.push_back(Pair("timereceived", (int64_t)wtx.nTimeReceived));
// Add opt-in RBF status
std::string rbfStatus = "no";
if (confirms <= 0) {
LOCK(mempool.cs);
if (!mempool.exists(hash)) {
if (SignalsOptInRBF(wtx)) {
rbfStatus = "yes";
} else {
rbfStatus = "unknown";
}
} else if (IsRBFOptIn(*mempool.mapTx.find(hash), mempool)) {
rbfStatus = "yes";
}
}
entry.push_back(Pair("bip125-replaceable", rbfStatus));
BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue)
entry.push_back(Pair(item.first, item.second));
}
string AccountFromValue(const UniValue& value)
{
string strAccount = value.get_str();
if (strAccount == "*")
throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name");
return strAccount;
}
UniValue getnewaddress(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 1)
throw runtime_error(
"getnewaddress ( \"account\" )\n"
"\nReturns a new Utabit address for receiving payments.\n"
"If 'account' is specified (DEPRECATED), it is added to the address book \n"
"so payments received with the address will be credited to 'account'.\n"
"\nArguments:\n"
"1. \"account\" (string, optional) DEPRECATED. The account name for the address to be linked to. If not provided, the default account \"\" is used. It can also be set to the empty string \"\" to represent the default account. The account does not need to exist, it will be created if there is no account by the given name.\n"
"\nResult:\n"
"\"utabitaddress\" (string) The new utabit address\n"
"\nExamples:\n"
+ HelpExampleCli("getnewaddress", "")
+ HelpExampleRpc("getnewaddress", "")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
// Parse the account first so we don't generate a key if there's an error
string strAccount;
if (params.size() > 0)
strAccount = AccountFromValue(params[0]);
if (!pwalletMain->IsLocked())
pwalletMain->TopUpKeyPool();
// Generate a new key that is added to wallet
CPubKey newKey;
if (!pwalletMain->GetKeyFromPool(newKey))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
CKeyID keyID = newKey.GetID();
pwalletMain->SetAddressBook(keyID, strAccount, "receive");
return CUtabitAddress(keyID).ToString();
}
CUtabitAddress GetAccountAddress(string strAccount, bool bForceNew=false)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
CAccount account;
walletdb.ReadAccount(strAccount, account);
bool bKeyUsed = false;
// Check if the current key has been used
if (account.vchPubKey.IsValid())
{
CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID());
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin();
it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid();
++it)
{
const CWalletTx& wtx = (*it).second;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
bKeyUsed = true;
}
}
// Generate a new key
if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed)
{
if (!pwalletMain->GetKeyFromPool(account.vchPubKey))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
pwalletMain->SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
walletdb.WriteAccount(strAccount, account);
}
return CUtabitAddress(account.vchPubKey.GetID());
}
UniValue getaccountaddress(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccountaddress \"account\"\n"
"\nDEPRECATED. Returns the current Utabit address for receiving payments to this account.\n"
"\nArguments:\n"
"1. \"account\" (string, required) The account name for the address. It can also be set to the empty string \"\" to represent the default account. The account does not need to exist, it will be created and a new address created if there is no account by the given name.\n"
"\nResult:\n"
"\"utabitaddress\" (string) The account utabit address\n"
"\nExamples:\n"
+ HelpExampleCli("getaccountaddress", "")
+ HelpExampleCli("getaccountaddress", "\"\"")
+ HelpExampleCli("getaccountaddress", "\"myaccount\"")
+ HelpExampleRpc("getaccountaddress", "\"myaccount\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
// Parse the account first so we don't generate a key if there's an error
string strAccount = AccountFromValue(params[0]);
UniValue ret(UniValue::VSTR);
ret = GetAccountAddress(strAccount).ToString();
return ret;
}
UniValue getrawchangeaddress(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 1)
throw runtime_error(
"getrawchangeaddress\n"
"\nReturns a new Utabit address, for receiving change.\n"
"This is for use with raw transactions, NOT normal use.\n"
"\nResult:\n"
"\"address\" (string) The address\n"
"\nExamples:\n"
+ HelpExampleCli("getrawchangeaddress", "")
+ HelpExampleRpc("getrawchangeaddress", "")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
if (!pwalletMain->IsLocked())
pwalletMain->TopUpKeyPool();
CReserveKey reservekey(pwalletMain);
CPubKey vchPubKey;
if (!reservekey.GetReservedKey(vchPubKey))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
reservekey.KeepKey();
CKeyID keyID = vchPubKey.GetID();
return CUtabitAddress(keyID).ToString();
}
UniValue setaccount(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"setaccount \"utabitaddress\" \"account\"\n"
"\nDEPRECATED. Sets the account associated with the given address.\n"
"\nArguments:\n"
"1. \"utabitaddress\" (string, required) The utabit address to be associated with an account.\n"
"2. \"account\" (string, required) The account to assign the address to.\n"
"\nExamples:\n"
+ HelpExampleCli("setaccount", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"tabby\"")
+ HelpExampleRpc("setaccount", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\", \"tabby\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
CUtabitAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Utabit address");
string strAccount;
if (params.size() > 1)
strAccount = AccountFromValue(params[1]);
// Only add the account if the address is yours.
if (IsMine(*pwalletMain, address.Get()))
{
// Detect when changing the account of an address that is the 'unused current key' of another account:
if (pwalletMain->mapAddressBook.count(address.Get()))
{
string strOldAccount = pwalletMain->mapAddressBook[address.Get()].name;
if (address == GetAccountAddress(strOldAccount))
GetAccountAddress(strOldAccount, true);
}
pwalletMain->SetAddressBook(address.Get(), strAccount, "receive");
}
else
throw JSONRPCError(RPC_MISC_ERROR, "setaccount can only be used with own address");
return NullUniValue;
}
UniValue getaccount(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccount \"utabitaddress\"\n"
"\nDEPRECATED. Returns the account associated with the given address.\n"
"\nArguments:\n"
"1. \"utabitaddress\" (string, required) The utabit address for account lookup.\n"
"\nResult:\n"
"\"accountname\" (string) the account address\n"
"\nExamples:\n"
+ HelpExampleCli("getaccount", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\"")
+ HelpExampleRpc("getaccount", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
CUtabitAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Utabit address");
string strAccount;
map<CTxDestination, CAddressBookData>::iterator mi = pwalletMain->mapAddressBook.find(address.Get());
if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.name.empty())
strAccount = (*mi).second.name;
return strAccount;
}
UniValue getaddressesbyaccount(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 1)
throw runtime_error(
"getaddressesbyaccount \"account\"\n"
"\nDEPRECATED. Returns the list of addresses for the given account.\n"
"\nArguments:\n"
"1. \"account\" (string, required) The account name.\n"
"\nResult:\n"
"[ (json array of string)\n"
" \"utabitaddress\" (string) a utabit address associated with the given account\n"
" ,...\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("getaddressesbyaccount", "\"tabby\"")
+ HelpExampleRpc("getaddressesbyaccount", "\"tabby\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
string strAccount = AccountFromValue(params[0]);
// Find all addresses that have the given account
UniValue ret(UniValue::VARR);
BOOST_FOREACH(const PAIRTYPE(CUtabitAddress, CAddressBookData)& item, pwalletMain->mapAddressBook)
{
const CUtabitAddress& address = item.first;
const string& strName = item.second.name;
if (strName == strAccount)
ret.push_back(address.ToString());
}
return ret;
}
static void SendMoney(const CTxDestination &address, CAmount nValue, bool fSubtractFeeFromAmount, CWalletTx& wtxNew)
{
CAmount curBalance = pwalletMain->GetBalance();
// Check amount
if (nValue <= 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid amount");
if (nValue > curBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds");
// Parse Utabit address
CScript scriptPubKey = GetScriptForDestination(address);
// Create and send the transaction
CReserveKey reservekey(pwalletMain);
CAmount nFeeRequired;
std::string strError;
vector<CRecipient> vecSend;
int nChangePosRet = -1;
CRecipient recipient = {scriptPubKey, nValue, fSubtractFeeFromAmount};
vecSend.push_back(recipient);
if (!pwalletMain->CreateTransaction(vecSend, wtxNew, reservekey, nFeeRequired, nChangePosRet, strError)) {
if (!fSubtractFeeFromAmount && nValue + nFeeRequired > pwalletMain->GetBalance())
strError = strprintf("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!", FormatMoney(nFeeRequired));
throw JSONRPCError(RPC_WALLET_ERROR, strError);
}
if (!pwalletMain->CommitTransaction(wtxNew, reservekey))
throw JSONRPCError(RPC_WALLET_ERROR, "Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.");
}
UniValue sendtoaddress(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 2 || params.size() > 5)
throw runtime_error(
"sendtoaddress \"utabitaddress\" amount ( \"comment\" \"comment-to\" subtractfeefromamount )\n"
"\nSend an amount to a given address.\n"
+ HelpRequiringPassphrase() +
"\nArguments:\n"
"1. \"utabitaddress\" (string, required) The utabit address to send to.\n"
"2. \"amount\" (numeric or string, required) The amount in " + CURRENCY_UNIT + " to send. eg 0.1\n"
"3. \"comment\" (string, optional) A comment used to store what the transaction is for. \n"
" This is not part of the transaction, just kept in your wallet.\n"
"4. \"comment-to\" (string, optional) A comment to store the name of the person or organization \n"
" to which you're sending the transaction. This is not part of the \n"
" transaction, just kept in your wallet.\n"
"5. subtractfeefromamount (boolean, optional, default=false) The fee will be deducted from the amount being sent.\n"
" The recipient will receive less utabits than you enter in the amount field.\n"
"\nResult:\n"
"\"transactionid\" (string) The transaction id.\n"
"\nExamples:\n"
+ HelpExampleCli("sendtoaddress", "\"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\" 0.1")
+ HelpExampleCli("sendtoaddress", "\"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\" 0.1 \"donation\" \"seans outpost\"")
+ HelpExampleCli("sendtoaddress", "\"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\" 0.1 \"\" \"\" true")
+ HelpExampleRpc("sendtoaddress", "\"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\", 0.1, \"donation\", \"seans outpost\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
CUtabitAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Utabit address");
// Amount
CAmount nAmount = AmountFromValue(params[1]);
if (nAmount <= 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
// Wallet comments
CWalletTx wtx;
if (params.size() > 2 && !params[2].isNull() && !params[2].get_str().empty())
wtx.mapValue["comment"] = params[2].get_str();
if (params.size() > 3 && !params[3].isNull() && !params[3].get_str().empty())
wtx.mapValue["to"] = params[3].get_str();
bool fSubtractFeeFromAmount = false;
if (params.size() > 4)
fSubtractFeeFromAmount = params[4].get_bool();
EnsureWalletIsUnlocked();
SendMoney(address.Get(), nAmount, fSubtractFeeFromAmount, wtx);
return wtx.GetHash().GetHex();
}
UniValue listaddressgroupings(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp)
throw runtime_error(
"listaddressgroupings\n"
"\nLists groups of addresses which have had their common ownership\n"
"made public by common use as inputs or as the resulting change\n"
"in past transactions\n"
"\nResult:\n"
"[\n"
" [\n"
" [\n"
" \"utabitaddress\", (string) The utabit address\n"
" amount, (numeric) The amount in " + CURRENCY_UNIT + "\n"
" \"account\" (string, optional) The account (DEPRECATED)\n"
" ]\n"
" ,...\n"
" ]\n"
" ,...\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("listaddressgroupings", "")
+ HelpExampleRpc("listaddressgroupings", "")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
UniValue jsonGroupings(UniValue::VARR);
map<CTxDestination, CAmount> balances = pwalletMain->GetAddressBalances();
BOOST_FOREACH(set<CTxDestination> grouping, pwalletMain->GetAddressGroupings())
{
UniValue jsonGrouping(UniValue::VARR);
BOOST_FOREACH(CTxDestination address, grouping)
{
UniValue addressInfo(UniValue::VARR);
addressInfo.push_back(CUtabitAddress(address).ToString());
addressInfo.push_back(ValueFromAmount(balances[address]));
{
if (pwalletMain->mapAddressBook.find(CUtabitAddress(address).Get()) != pwalletMain->mapAddressBook.end())
addressInfo.push_back(pwalletMain->mapAddressBook.find(CUtabitAddress(address).Get())->second.name);
}
jsonGrouping.push_back(addressInfo);
}
jsonGroupings.push_back(jsonGrouping);
}
return jsonGroupings;
}
UniValue signmessage(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 2)
throw runtime_error(
"signmessage \"utabitaddress\" \"message\"\n"
"\nSign a message with the private key of an address"
+ HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. \"utabitaddress\" (string, required) The utabit address to use for the private key.\n"
"2. \"message\" (string, required) The message to create a signature of.\n"
"\nResult:\n"
"\"signature\" (string) The signature of the message encoded in base 64\n"
"\nExamples:\n"
"\nUnlock the wallet for 30 seconds\n"
+ HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
"\nCreate the signature\n"
+ HelpExampleCli("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"my message\"") +
"\nVerify the signature\n"
+ HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"signature\" \"my message\"") +
"\nAs json rpc\n"
+ HelpExampleRpc("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\", \"my message\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
EnsureWalletIsUnlocked();
string strAddress = params[0].get_str();
string strMessage = params[1].get_str();
CUtabitAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
CKey key;
if (!pwalletMain->GetKey(keyID, key))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
vector<unsigned char> vchSig;
if (!key.SignCompact(ss.GetHash(), vchSig))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
return EncodeBase64(&vchSig[0], vchSig.size());
}
UniValue getreceivedbyaddress(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaddress \"utabitaddress\" ( minconf )\n"
"\nReturns the total amount received by the given utabitaddress in transactions with at least minconf confirmations.\n"
"\nArguments:\n"
"1. \"utabitaddress\" (string, required) The utabit address for transactions.\n"
"2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
"\nResult:\n"
"amount (numeric) The total amount in " + CURRENCY_UNIT + " received at this address.\n"
"\nExamples:\n"
"\nThe amount from transactions with at least 1 confirmation\n"
+ HelpExampleCli("getreceivedbyaddress", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\"") +
"\nThe amount including unconfirmed transactions, zero confirmations\n"
+ HelpExampleCli("getreceivedbyaddress", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" 0") +
"\nThe amount with at least 6 confirmation, very safe\n"
+ HelpExampleCli("getreceivedbyaddress", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" 6") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("getreceivedbyaddress", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\", 6")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
// Utabit address
CUtabitAddress address = CUtabitAddress(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Utabit address");
CScript scriptPubKey = GetScriptForDestination(address.Get());
if (!IsMine(*pwalletMain,scriptPubKey))
return (double)0.0;
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Tally
CAmount nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !CheckFinalTx(wtx))
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
return ValueFromAmount(nAmount);
}
UniValue getreceivedbyaccount(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaccount \"account\" ( minconf )\n"
"\nDEPRECATED. Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.\n"
"\nArguments:\n"
"1. \"account\" (string, required) The selected account, may be the default account using \"\".\n"
"2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
"\nResult:\n"
"amount (numeric) The total amount in " + CURRENCY_UNIT + " received for this account.\n"
"\nExamples:\n"
"\nAmount received by the default account with at least 1 confirmation\n"
+ HelpExampleCli("getreceivedbyaccount", "\"\"") +
"\nAmount received at the tabby account including unconfirmed amounts with zero confirmations\n"
+ HelpExampleCli("getreceivedbyaccount", "\"tabby\" 0") +
"\nThe amount with at least 6 confirmation, very safe\n"
+ HelpExampleCli("getreceivedbyaccount", "\"tabby\" 6") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("getreceivedbyaccount", "\"tabby\", 6")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Get the set of pub keys assigned to account
string strAccount = AccountFromValue(params[0]);
set<CTxDestination> setAddress = pwalletMain->GetAccountAddresses(strAccount);
// Tally
CAmount nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !CheckFinalTx(wtx))
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address))
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
}
return (double)nAmount / (double)COIN;
}
CAmount GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth, const isminefilter& filter)
{
CAmount nBalance = 0;
// Tally wallet transactions
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < 0)
continue;
CAmount nReceived, nSent, nFee;
wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee, filter);
if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth)
nBalance += nReceived;
nBalance -= nSent + nFee;
}
// Tally internal accounting entries
nBalance += walletdb.GetAccountCreditDebit(strAccount);
return nBalance;
}
CAmount GetAccountBalance(const string& strAccount, int nMinDepth, const isminefilter& filter)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
return GetAccountBalance(walletdb, strAccount, nMinDepth, filter);
}
UniValue getbalance(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 3)
throw runtime_error(
"getbalance ( \"account\" minconf includeWatchonly )\n"
"\nIf account is not specified, returns the server's total available balance.\n"
"If account is specified (DEPRECATED), returns the balance in the account.\n"
"Note that the account \"\" is not the same as leaving the parameter out.\n"
"The server total may be different to the balance in the default \"\" account.\n"
"\nArguments:\n"
"1. \"account\" (string, optional) DEPRECATED. The selected account, or \"*\" for entire wallet. It may be the default account using \"\".\n"
"2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
"3. includeWatchonly (bool, optional, default=false) Also include balance in watchonly addresses (see 'importaddress')\n"
"\nResult:\n"
"amount (numeric) The total amount in " + CURRENCY_UNIT + " received for this account.\n"
"\nExamples:\n"
"\nThe total amount in the wallet\n"
+ HelpExampleCli("getbalance", "") +
"\nThe total amount in the wallet at least 5 blocks confirmed\n"
+ HelpExampleCli("getbalance", "\"*\" 6") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("getbalance", "\"*\", 6")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
if (params.size() == 0)
return ValueFromAmount(pwalletMain->GetBalance());
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
isminefilter filter = ISMINE_SPENDABLE;
if(params.size() > 2)
if(params[2].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
if (params[0].get_str() == "*") {
// Calculate total balance a different way from GetBalance()
// (GetBalance() sums up all unspent TxOuts)
// getbalance and "getbalance * 1 true" should return the same number
CAmount nBalance = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < 0)
continue;
CAmount allFee;
string strSentAccount;
list<COutputEntry> listReceived;
list<COutputEntry> listSent;
wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
if (wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const COutputEntry& r, listReceived)
nBalance += r.amount;
}
BOOST_FOREACH(const COutputEntry& s, listSent)
nBalance -= s.amount;
nBalance -= allFee;
}
return ValueFromAmount(nBalance);
}
string strAccount = AccountFromValue(params[0]);
CAmount nBalance = GetAccountBalance(strAccount, nMinDepth, filter);
return ValueFromAmount(nBalance);
}
UniValue getunconfirmedbalance(const UniValue ¶ms, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 0)
throw runtime_error(
"getunconfirmedbalance\n"
"Returns the server's total unconfirmed balance\n");
LOCK2(cs_main, pwalletMain->cs_wallet);
return ValueFromAmount(pwalletMain->GetUnconfirmedBalance());
}
UniValue movecmd(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 3 || params.size() > 5)
throw runtime_error(
"move \"fromaccount\" \"toaccount\" amount ( minconf \"comment\" )\n"
"\nDEPRECATED. Move a specified amount from one account in your wallet to another.\n"
"\nArguments:\n"
"1. \"fromaccount\" (string, required) The name of the account to move funds from. May be the default account using \"\".\n"
"2. \"toaccount\" (string, required) The name of the account to move funds to. May be the default account using \"\".\n"
"3. amount (numeric) Quantity of " + CURRENCY_UNIT + " to move between accounts.\n"
"4. minconf (numeric, optional, default=1) Only use funds with at least this many confirmations.\n"
"5. \"comment\" (string, optional) An optional comment, stored in the wallet only.\n"
"\nResult:\n"
"true|false (boolean) true if successful.\n"
"\nExamples:\n"
"\nMove 0.01 " + CURRENCY_UNIT + " from the default account to the account named tabby\n"
+ HelpExampleCli("move", "\"\" \"tabby\" 0.01") +
"\nMove 0.01 " + CURRENCY_UNIT + " timotei to akiko with a comment and funds have 6 confirmations\n"
+ HelpExampleCli("move", "\"timotei\" \"akiko\" 0.01 6 \"happy birthday!\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("move", "\"timotei\", \"akiko\", 0.01, 6, \"happy birthday!\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
string strFrom = AccountFromValue(params[0]);
string strTo = AccountFromValue(params[1]);
CAmount nAmount = AmountFromValue(params[2]);
if (nAmount <= 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
if (params.size() > 3)
// unused parameter, used to be nMinDepth, keep type-checking it though
(void)params[3].get_int();
string strComment;
if (params.size() > 4)
strComment = params[4].get_str();
CWalletDB walletdb(pwalletMain->strWalletFile);
if (!walletdb.TxnBegin())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
int64_t nNow = GetAdjustedTime();
// Debit
CAccountingEntry debit;
debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
debit.strAccount = strFrom;
debit.nCreditDebit = -nAmount;
debit.nTime = nNow;
debit.strOtherAccount = strTo;
debit.strComment = strComment;
pwalletMain->AddAccountingEntry(debit, walletdb);
// Credit
CAccountingEntry credit;
credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
credit.strAccount = strTo;
credit.nCreditDebit = nAmount;
credit.nTime = nNow;
credit.strOtherAccount = strFrom;
credit.strComment = strComment;
pwalletMain->AddAccountingEntry(credit, walletdb);
if (!walletdb.TxnCommit())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
return true;
}
UniValue sendfrom(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 3 || params.size() > 6)
throw runtime_error(
"sendfrom \"fromaccount\" \"toutabitaddress\" amount ( minconf \"comment\" \"comment-to\" )\n"
"\nDEPRECATED (use sendtoaddress). Sent an amount from an account to a utabit address."
+ HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. \"fromaccount\" (string, required) The name of the account to send funds from. May be the default account using \"\".\n"
"2. \"toutabitaddress\" (string, required) The utabit address to send funds to.\n"
"3. amount (numeric or string, required) The amount in " + CURRENCY_UNIT + " (transaction fee is added on top).\n"
"4. minconf (numeric, optional, default=1) Only use funds with at least this many confirmations.\n"
"5. \"comment\" (string, optional) A comment used to store what the transaction is for. \n"
" This is not part of the transaction, just kept in your wallet.\n"
"6. \"comment-to\" (string, optional) An optional comment to store the name of the person or organization \n"
" to which you're sending the transaction. This is not part of the transaction, \n"
" it is just kept in your wallet.\n"
"\nResult:\n"
"\"transactionid\" (string) The transaction id.\n"
"\nExamples:\n"
"\nSend 0.01 " + CURRENCY_UNIT + " from the default account to the address, must have at least 1 confirmation\n"
+ HelpExampleCli("sendfrom", "\"\" \"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\" 0.01") +
"\nSend 0.01 from the tabby account to the given address, funds must have at least 6 confirmations\n"
+ HelpExampleCli("sendfrom", "\"tabby\" \"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\" 0.01 6 \"donation\" \"seans outpost\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("sendfrom", "\"tabby\", \"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\", 0.01, 6, \"donation\", \"seans outpost\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
string strAccount = AccountFromValue(params[0]);
CUtabitAddress address(params[1].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Utabit address");
CAmount nAmount = AmountFromValue(params[2]);
if (nAmount <= 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
int nMinDepth = 1;
if (params.size() > 3)
nMinDepth = params[3].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 4 && !params[4].isNull() && !params[4].get_str().empty())
wtx.mapValue["comment"] = params[4].get_str();
if (params.size() > 5 && !params[5].isNull() && !params[5].get_str().empty())
wtx.mapValue["to"] = params[5].get_str();
EnsureWalletIsUnlocked();
// Check funds
CAmount nBalance = GetAccountBalance(strAccount, nMinDepth, ISMINE_SPENDABLE);
if (nAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
SendMoney(address.Get(), nAmount, false, wtx);
return wtx.GetHash().GetHex();
}
UniValue sendmany(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 2 || params.size() > 5)
throw runtime_error(
"sendmany \"fromaccount\" {\"address\":amount,...} ( minconf \"comment\" [\"address\",...] )\n"
"\nSend multiple times. Amounts are double-precision floating point numbers."
+ HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. \"fromaccount\" (string, required) DEPRECATED. The account to send the funds from. Should be \"\" for the default account\n"
"2. \"amounts\" (string, required) A json object with addresses and amounts\n"
" {\n"
" \"address\":amount (numeric or string) The utabit address is the key, the numeric amount (can be string) in " + CURRENCY_UNIT + " is the value\n"
" ,...\n"
" }\n"
"3. minconf (numeric, optional, default=1) Only use the balance confirmed at least this many times.\n"
"4. \"comment\" (string, optional) A comment\n"
"5. subtractfeefromamount (string, optional) A json array with addresses.\n"
" The fee will be equally deducted from the amount of each selected address.\n"
" Those recipients will receive less utabits than you enter in their corresponding amount field.\n"
" If no addresses are specified here, the sender pays the fee.\n"
" [\n"
" \"address\" (string) Subtract fee from this address\n"
" ,...\n"
" ]\n"
"\nResult:\n"
"\"transactionid\" (string) The transaction id for the send. Only 1 transaction is created regardless of \n"
" the number of addresses.\n"
"\nExamples:\n"
"\nSend two amounts to two different addresses:\n"
+ HelpExampleCli("sendmany", "\"\" \"{\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\\\":0.01,\\\"1353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\\\":0.02}\"") +
"\nSend two amounts to two different addresses setting the confirmation and comment:\n"
+ HelpExampleCli("sendmany", "\"\" \"{\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\\\":0.01,\\\"1353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\\\":0.02}\" 6 \"testing\"") +
"\nSend two amounts to two different addresses, subtract fee from amount:\n"
+ HelpExampleCli("sendmany", "\"\" \"{\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\\\":0.01,\\\"1353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\\\":0.02}\" 1 \"\" \"[\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\\\",\\\"1353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\\\"]\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("sendmany", "\"\", \"{\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\\\":0.01,\\\"1353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\\\":0.02}\", 6, \"testing\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
string strAccount = AccountFromValue(params[0]);
UniValue sendTo = params[1].get_obj();
int nMinDepth = 1;
if (params.size() > 2)
nMinDepth = params[2].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 3 && !params[3].isNull() && !params[3].get_str().empty())
wtx.mapValue["comment"] = params[3].get_str();
UniValue subtractFeeFromAmount(UniValue::VARR);
if (params.size() > 4)
subtractFeeFromAmount = params[4].get_array();
set<CUtabitAddress> setAddress;
vector<CRecipient> vecSend;
CAmount totalAmount = 0;
vector<string> keys = sendTo.getKeys();
BOOST_FOREACH(const string& name_, keys)
{
CUtabitAddress address(name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Utabit address: ")+name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+name_);
setAddress.insert(address);
CScript scriptPubKey = GetScriptForDestination(address.Get());
CAmount nAmount = AmountFromValue(sendTo[name_]);
if (nAmount <= 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
totalAmount += nAmount;
bool fSubtractFeeFromAmount = false;
for (unsigned int idx = 0; idx < subtractFeeFromAmount.size(); idx++) {
const UniValue& addr = subtractFeeFromAmount[idx];
if (addr.get_str() == name_)
fSubtractFeeFromAmount = true;
}
CRecipient recipient = {scriptPubKey, nAmount, fSubtractFeeFromAmount};
vecSend.push_back(recipient);
}
EnsureWalletIsUnlocked();
// Check funds
CAmount nBalance = GetAccountBalance(strAccount, nMinDepth, ISMINE_SPENDABLE);
if (totalAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
CReserveKey keyChange(pwalletMain);
CAmount nFeeRequired = 0;
int nChangePosRet = -1;
string strFailReason;
bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, nChangePosRet, strFailReason);
if (!fCreated)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason);
if (!pwalletMain->CommitTransaction(wtx, keyChange))
throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed");
return wtx.GetHash().GetHex();
}
// Defined in rpcmisc.cpp
extern CScript _createmultisig_redeemScript(const UniValue& params);
UniValue addmultisigaddress(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 2 || params.size() > 3)
{
string msg = "addmultisigaddress nrequired [\"key\",...] ( \"account\" )\n"
"\nAdd a nrequired-to-sign multisignature address to the wallet.\n"
"Each key is a Utabit address or hex-encoded public key.\n"
"If 'account' is specified (DEPRECATED), assign address to that account.\n"
"\nArguments:\n"
"1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n"
"2. \"keysobject\" (string, required) A json array of utabit addresses or hex-encoded public keys\n"
" [\n"
" \"address\" (string) utabit address or hex-encoded public key\n"
" ...,\n"
" ]\n"
"3. \"account\" (string, optional) DEPRECATED. An account to assign the addresses to.\n"
"\nResult:\n"
"\"utabitaddress\" (string) A utabit address associated with the keys.\n"
"\nExamples:\n"
"\nAdd a multisig address from 2 addresses\n"
+ HelpExampleCli("addmultisigaddress", "2 \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"") +
"\nAs json rpc call\n"
+ HelpExampleRpc("addmultisigaddress", "2, \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"")
;
throw runtime_error(msg);
}
LOCK2(cs_main, pwalletMain->cs_wallet);
string strAccount;
if (params.size() > 2)
strAccount = AccountFromValue(params[2]);
// Construct using pay-to-script-hash:
CScript inner = _createmultisig_redeemScript(params);
CScriptID innerID(inner);
pwalletMain->AddCScript(inner);
pwalletMain->SetAddressBook(innerID, strAccount, "send");
return CUtabitAddress(innerID).ToString();
}
struct tallyitem
{
CAmount nAmount;
int nConf;
vector<uint256> txids;
bool fIsWatchonly;
tallyitem()
{
nAmount = 0;
nConf = std::numeric_limits<int>::max();
fIsWatchonly = false;
}
};
UniValue ListReceived(const UniValue& params, bool fByAccounts)
{
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
// Whether to include empty accounts
bool fIncludeEmpty = false;
if (params.size() > 1)
fIncludeEmpty = params[1].get_bool();
isminefilter filter = ISMINE_SPENDABLE;
if(params.size() > 2)
if(params[2].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
// Tally
map<CUtabitAddress, tallyitem> mapTally;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !CheckFinalTx(wtx))
continue;
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < nMinDepth)
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address))
continue;
isminefilter mine = IsMine(*pwalletMain, address);
if(!(mine & filter))
continue;
tallyitem& item = mapTally[address];
item.nAmount += txout.nValue;
item.nConf = min(item.nConf, nDepth);
item.txids.push_back(wtx.GetHash());
if (mine & ISMINE_WATCH_ONLY)
item.fIsWatchonly = true;
}
}
// Reply
UniValue ret(UniValue::VARR);
map<string, tallyitem> mapAccountTally;
BOOST_FOREACH(const PAIRTYPE(CUtabitAddress, CAddressBookData)& item, pwalletMain->mapAddressBook)
{
const CUtabitAddress& address = item.first;
const string& strAccount = item.second.name;
map<CUtabitAddress, tallyitem>::iterator it = mapTally.find(address);
if (it == mapTally.end() && !fIncludeEmpty)
continue;
CAmount nAmount = 0;
int nConf = std::numeric_limits<int>::max();
bool fIsWatchonly = false;
if (it != mapTally.end())
{
nAmount = (*it).second.nAmount;
nConf = (*it).second.nConf;
fIsWatchonly = (*it).second.fIsWatchonly;
}
if (fByAccounts)
{
tallyitem& item = mapAccountTally[strAccount];
item.nAmount += nAmount;
item.nConf = min(item.nConf, nConf);
item.fIsWatchonly = fIsWatchonly;
}
else
{
UniValue obj(UniValue::VOBJ);
if(fIsWatchonly)
obj.push_back(Pair("involvesWatchonly", true));
obj.push_back(Pair("address", address.ToString()));
obj.push_back(Pair("account", strAccount));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
if (!fByAccounts)
obj.push_back(Pair("label", strAccount));
UniValue transactions(UniValue::VARR);
if (it != mapTally.end())
{
BOOST_FOREACH(const uint256& item, (*it).second.txids)
{
transactions.push_back(item.GetHex());
}
}
obj.push_back(Pair("txids", transactions));
ret.push_back(obj);
}
}
if (fByAccounts)
{
for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
{
CAmount nAmount = (*it).second.nAmount;
int nConf = (*it).second.nConf;
UniValue obj(UniValue::VOBJ);
if((*it).second.fIsWatchonly)
obj.push_back(Pair("involvesWatchonly", true));
obj.push_back(Pair("account", (*it).first));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
ret.push_back(obj);
}
}
return ret;
}
UniValue listreceivedbyaddress(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 3)
throw runtime_error(
"listreceivedbyaddress ( minconf includeempty includeWatchonly)\n"
"\nList balances by receiving address.\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n"
"2. includeempty (numeric, optional, default=false) Whether to include addresses that haven't received any payments.\n"
"3. includeWatchonly (bool, optional, default=false) Whether to include watchonly addresses (see 'importaddress').\n"
"\nResult:\n"
"[\n"
" {\n"
" \"involvesWatchonly\" : true, (bool) Only returned if imported addresses were involved in transaction\n"
" \"address\" : \"receivingaddress\", (string) The receiving address\n"
" \"account\" : \"accountname\", (string) DEPRECATED. The account of the receiving address. The default account is \"\".\n"
" \"amount\" : x.xxx, (numeric) The total amount in " + CURRENCY_UNIT + " received by the address\n"
" \"confirmations\" : n, (numeric) The number of confirmations of the most recent transaction included\n"
" \"label\" : \"label\" (string) A comment for the address/transaction, if any\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("listreceivedbyaddress", "")
+ HelpExampleCli("listreceivedbyaddress", "6 true")
+ HelpExampleRpc("listreceivedbyaddress", "6, true, true")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
return ListReceived(params, false);
}
UniValue listreceivedbyaccount(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 3)
throw runtime_error(
"listreceivedbyaccount ( minconf includeempty includeWatchonly)\n"
"\nDEPRECATED. List balances by account.\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n"
"2. includeempty (boolean, optional, default=false) Whether to include accounts that haven't received any payments.\n"
"3. includeWatchonly (bool, optional, default=false) Whether to include watchonly addresses (see 'importaddress').\n"
"\nResult:\n"
"[\n"
" {\n"
" \"involvesWatchonly\" : true, (bool) Only returned if imported addresses were involved in transaction\n"
" \"account\" : \"accountname\", (string) The account name of the receiving account\n"
" \"amount\" : x.xxx, (numeric) The total amount received by addresses with this account\n"
" \"confirmations\" : n, (numeric) The number of confirmations of the most recent transaction included\n"
" \"label\" : \"label\" (string) A comment for the address/transaction, if any\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("listreceivedbyaccount", "")
+ HelpExampleCli("listreceivedbyaccount", "6 true")
+ HelpExampleRpc("listreceivedbyaccount", "6, true, true")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
return ListReceived(params, true);
}
static void MaybePushAddress(UniValue & entry, const CTxDestination &dest)
{
CUtabitAddress addr;
if (addr.Set(dest))
entry.push_back(Pair("address", addr.ToString()));
}
void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, UniValue& ret, const isminefilter& filter)
{
CAmount nFee;
string strSentAccount;
list<COutputEntry> listReceived;
list<COutputEntry> listSent;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, filter);
bool fAllAccounts = (strAccount == string("*"));
bool involvesWatchonly = wtx.IsFromMe(ISMINE_WATCH_ONLY);
// Sent
if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
{
BOOST_FOREACH(const COutputEntry& s, listSent)
{
UniValue entry(UniValue::VOBJ);
if(involvesWatchonly || (::IsMine(*pwalletMain, s.destination) & ISMINE_WATCH_ONLY))
entry.push_back(Pair("involvesWatchonly", true));
entry.push_back(Pair("account", strSentAccount));
MaybePushAddress(entry, s.destination);
entry.push_back(Pair("category", "send"));
entry.push_back(Pair("amount", ValueFromAmount(-s.amount)));
if (pwalletMain->mapAddressBook.count(s.destination))
entry.push_back(Pair("label", pwalletMain->mapAddressBook[s.destination].name));
entry.push_back(Pair("vout", s.vout));
entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
if (fLong)
WalletTxToJSON(wtx, entry);
entry.push_back(Pair("abandoned", wtx.isAbandoned()));
ret.push_back(entry);
}
}
// Received
if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const COutputEntry& r, listReceived)
{
string account;
if (pwalletMain->mapAddressBook.count(r.destination))
account = pwalletMain->mapAddressBook[r.destination].name;
if (fAllAccounts || (account == strAccount))
{
UniValue entry(UniValue::VOBJ);
if(involvesWatchonly || (::IsMine(*pwalletMain, r.destination) & ISMINE_WATCH_ONLY))
entry.push_back(Pair("involvesWatchonly", true));
entry.push_back(Pair("account", account));
MaybePushAddress(entry, r.destination);
if (wtx.IsCoinBase())
{
if (wtx.GetDepthInMainChain() < 1)
entry.push_back(Pair("category", "orphan"));
else if (wtx.GetBlocksToMaturity() > 0)
entry.push_back(Pair("category", "immature"));
else
entry.push_back(Pair("category", "generate"));
}
else
{
entry.push_back(Pair("category", "receive"));
}
entry.push_back(Pair("amount", ValueFromAmount(r.amount)));
if (pwalletMain->mapAddressBook.count(r.destination))
entry.push_back(Pair("label", account));
entry.push_back(Pair("vout", r.vout));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
}
}
void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, UniValue& ret)
{
bool fAllAccounts = (strAccount == string("*"));
if (fAllAccounts || acentry.strAccount == strAccount)
{
UniValue entry(UniValue::VOBJ);
entry.push_back(Pair("account", acentry.strAccount));
entry.push_back(Pair("category", "move"));
entry.push_back(Pair("time", acentry.nTime));
entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
entry.push_back(Pair("comment", acentry.strComment));
ret.push_back(entry);
}
}
UniValue listtransactions(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 4)
throw runtime_error(
"listtransactions ( \"account\" count from includeWatchonly)\n"
"\nReturns up to 'count' most recent transactions skipping the first 'from' transactions for account 'account'.\n"
"\nArguments:\n"
"1. \"account\" (string, optional) DEPRECATED. The account name. Should be \"*\".\n"
"2. count (numeric, optional, default=10) The number of transactions to return\n"
"3. from (numeric, optional, default=0) The number of transactions to skip\n"
"4. includeWatchonly (bool, optional, default=false) Include transactions to watchonly addresses (see 'importaddress')\n"
"\nResult:\n"
"[\n"
" {\n"
" \"account\":\"accountname\", (string) DEPRECATED. The account name associated with the transaction. \n"
" It will be \"\" for the default account.\n"
" \"address\":\"utabitaddress\", (string) The utabit address of the transaction. Not present for \n"
" move transactions (category = move).\n"
" \"category\":\"send|receive|move\", (string) The transaction category. 'move' is a local (off blockchain)\n"
" transaction between accounts, and not associated with an address,\n"
" transaction id or block. 'send' and 'receive' transactions are \n"
" associated with an address, transaction id and block details\n"
" \"amount\": x.xxx, (numeric) The amount in " + CURRENCY_UNIT + ". This is negative for the 'send' category, and for the\n"
" 'move' category for moves outbound. It is positive for the 'receive' category,\n"
" and for the 'move' category for inbound funds.\n"
" \"vout\": n, (numeric) the vout value\n"
" \"fee\": x.xxx, (numeric) The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the \n"
" 'send' category of transactions.\n"
" \"confirmations\": n, (numeric) The number of confirmations for the transaction. Available for 'send' and \n"
" 'receive' category of transactions. Negative confirmations indicate the\n"
" transation conflicts with the block chain\n"
" \"trusted\": xxx (bool) Whether we consider the outputs of this unconfirmed transaction safe to spend.\n"
" \"blockhash\": \"hashvalue\", (string) The block hash containing the transaction. Available for 'send' and 'receive'\n"
" category of transactions.\n"
" \"blockindex\": n, (numeric) The block index containing the transaction. Available for 'send' and 'receive'\n"
" category of transactions.\n"
" \"blocktime\": xxx, (numeric) The block time in seconds since epoch (1 Jan 1970 GMT).\n"
" \"txid\": \"transactionid\", (string) The transaction id. Available for 'send' and 'receive' category of transactions.\n"
" \"time\": xxx, (numeric) The transaction time in seconds since epoch (midnight Jan 1 1970 GMT).\n"
" \"timereceived\": xxx, (numeric) The time received in seconds since epoch (midnight Jan 1 1970 GMT). Available \n"
" for 'send' and 'receive' category of transactions.\n"
" \"comment\": \"...\", (string) If a comment is associated with the transaction.\n"
" \"label\": \"label\" (string) A comment for the address/transaction, if any\n"
" \"otheraccount\": \"accountname\", (string) For the 'move' category of transactions, the account the funds came \n"
" from (for receiving funds, positive amounts), or went to (for sending funds,\n"
" negative amounts).\n"
" \"bip125-replaceable\": \"yes|no|unknown\" (string) Whether this transaction could be replaced due to BIP125 (replace-by-fee);\n"
" may be unknown for unconfirmed transactions not in the mempool\n"
" }\n"
"]\n"
"\nExamples:\n"
"\nList the most recent 10 transactions in the systems\n"
+ HelpExampleCli("listtransactions", "") +
"\nList transactions 100 to 120\n"
+ HelpExampleCli("listtransactions", "\"*\" 20 100") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("listtransactions", "\"*\", 20, 100")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
string strAccount = "*";
if (params.size() > 0)
strAccount = params[0].get_str();
int nCount = 10;
if (params.size() > 1)
nCount = params[1].get_int();
int nFrom = 0;
if (params.size() > 2)
nFrom = params[2].get_int();
isminefilter filter = ISMINE_SPENDABLE;
if(params.size() > 3)
if(params[3].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
if (nCount < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count");
if (nFrom < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from");
UniValue ret(UniValue::VARR);
const CWallet::TxItems & txOrdered = pwalletMain->wtxOrdered;
// iterate backwards until we have nCount items to return:
for (CWallet::TxItems::const_reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
{
CWalletTx *const pwtx = (*it).second.first;
if (pwtx != 0)
ListTransactions(*pwtx, strAccount, 0, true, ret, filter);
CAccountingEntry *const pacentry = (*it).second.second;
if (pacentry != 0)
AcentryToJSON(*pacentry, strAccount, ret);
if ((int)ret.size() >= (nCount+nFrom)) break;
}
// ret is newest to oldest
if (nFrom > (int)ret.size())
nFrom = ret.size();
if ((nFrom + nCount) > (int)ret.size())
nCount = ret.size() - nFrom;
vector<UniValue> arrTmp = ret.getValues();
vector<UniValue>::iterator first = arrTmp.begin();
std::advance(first, nFrom);
vector<UniValue>::iterator last = arrTmp.begin();
std::advance(last, nFrom+nCount);
if (last != arrTmp.end()) arrTmp.erase(last, arrTmp.end());
if (first != arrTmp.begin()) arrTmp.erase(arrTmp.begin(), first);
std::reverse(arrTmp.begin(), arrTmp.end()); // Return oldest to newest
ret.clear();
ret.setArray();
ret.push_backV(arrTmp);
return ret;
}
UniValue listaccounts(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 2)
throw runtime_error(
"listaccounts ( minconf includeWatchonly)\n"
"\nDEPRECATED. Returns Object that has account names as keys, account balances as values.\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) Only include transactions with at least this many confirmations\n"
"2. includeWatchonly (bool, optional, default=false) Include balances in watchonly addresses (see 'importaddress')\n"
"\nResult:\n"
"{ (json object where keys are account names, and values are numeric balances\n"
" \"account\": x.xxx, (numeric) The property name is the account name, and the value is the total balance for the account.\n"
" ...\n"
"}\n"
"\nExamples:\n"
"\nList account balances where there at least 1 confirmation\n"
+ HelpExampleCli("listaccounts", "") +
"\nList account balances including zero confirmation transactions\n"
+ HelpExampleCli("listaccounts", "0") +
"\nList account balances for 6 or more confirmations\n"
+ HelpExampleCli("listaccounts", "6") +
"\nAs json rpc call\n"
+ HelpExampleRpc("listaccounts", "6")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
isminefilter includeWatchonly = ISMINE_SPENDABLE;
if(params.size() > 1)
if(params[1].get_bool())
includeWatchonly = includeWatchonly | ISMINE_WATCH_ONLY;
map<string, CAmount> mapAccountBalances;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& entry, pwalletMain->mapAddressBook) {
if (IsMine(*pwalletMain, entry.first) & includeWatchonly) // This address belongs to me
mapAccountBalances[entry.second.name] = 0;
}
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
CAmount nFee;
string strSentAccount;
list<COutputEntry> listReceived;
list<COutputEntry> listSent;
int nDepth = wtx.GetDepthInMainChain();
if (wtx.GetBlocksToMaturity() > 0 || nDepth < 0)
continue;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, includeWatchonly);
mapAccountBalances[strSentAccount] -= nFee;
BOOST_FOREACH(const COutputEntry& s, listSent)
mapAccountBalances[strSentAccount] -= s.amount;
if (nDepth >= nMinDepth)
{
BOOST_FOREACH(const COutputEntry& r, listReceived)
if (pwalletMain->mapAddressBook.count(r.destination))
mapAccountBalances[pwalletMain->mapAddressBook[r.destination].name] += r.amount;
else
mapAccountBalances[""] += r.amount;
}
}
const list<CAccountingEntry> & acentries = pwalletMain->laccentries;
BOOST_FOREACH(const CAccountingEntry& entry, acentries)
mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
UniValue ret(UniValue::VOBJ);
BOOST_FOREACH(const PAIRTYPE(string, CAmount)& accountBalance, mapAccountBalances) {
ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
}
return ret;
}
UniValue listsinceblock(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp)
throw runtime_error(
"listsinceblock ( \"blockhash\" target-confirmations includeWatchonly)\n"
"\nGet all transactions in blocks since block [blockhash], or all transactions if omitted\n"
"\nArguments:\n"
"1. \"blockhash\" (string, optional) The block hash to list transactions since\n"
"2. target-confirmations: (numeric, optional) The confirmations required, must be 1 or more\n"
"3. includeWatchonly: (bool, optional, default=false) Include transactions to watchonly addresses (see 'importaddress')"
"\nResult:\n"
"{\n"
" \"transactions\": [\n"
" \"account\":\"accountname\", (string) DEPRECATED. The account name associated with the transaction. Will be \"\" for the default account.\n"
" \"address\":\"utabitaddress\", (string) The utabit address of the transaction. Not present for move transactions (category = move).\n"
" \"category\":\"send|receive\", (string) The transaction category. 'send' has negative amounts, 'receive' has positive amounts.\n"
" \"amount\": x.xxx, (numeric) The amount in " + CURRENCY_UNIT + ". This is negative for the 'send' category, and for the 'move' category for moves \n"
" outbound. It is positive for the 'receive' category, and for the 'move' category for inbound funds.\n"
" \"vout\" : n, (numeric) the vout value\n"
" \"fee\": x.xxx, (numeric) The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the 'send' category of transactions.\n"
" \"confirmations\": n, (numeric) The number of confirmations for the transaction. Available for 'send' and 'receive' category of transactions.\n"
" \"blockhash\": \"hashvalue\", (string) The block hash containing the transaction. Available for 'send' and 'receive' category of transactions.\n"
" \"blockindex\": n, (numeric) The block index containing the transaction. Available for 'send' and 'receive' category of transactions.\n"
" \"blocktime\": xxx, (numeric) The block time in seconds since epoch (1 Jan 1970 GMT).\n"
" \"txid\": \"transactionid\", (string) The transaction id. Available for 'send' and 'receive' category of transactions.\n"
" \"time\": xxx, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT).\n"
" \"timereceived\": xxx, (numeric) The time received in seconds since epoch (Jan 1 1970 GMT). Available for 'send' and 'receive' category of transactions.\n"
" \"comment\": \"...\", (string) If a comment is associated with the transaction.\n"
" \"label\" : \"label\" (string) A comment for the address/transaction, if any\n"
" \"to\": \"...\", (string) If a comment to is associated with the transaction.\n"
" ],\n"
" \"lastblock\": \"lastblockhash\" (string) The hash of the last block\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("listsinceblock", "")
+ HelpExampleCli("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\" 6")
+ HelpExampleRpc("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\", 6")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
CBlockIndex *pindex = NULL;
int target_confirms = 1;
isminefilter filter = ISMINE_SPENDABLE;
if (params.size() > 0)
{
uint256 blockId;
blockId.SetHex(params[0].get_str());
BlockMap::iterator it = mapBlockIndex.find(blockId);
if (it != mapBlockIndex.end())
pindex = it->second;
}
if (params.size() > 1)
{
target_confirms = params[1].get_int();
if (target_confirms < 1)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
}
if(params.size() > 2)
if(params[2].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
int depth = pindex ? (1 + chainActive.Height() - pindex->nHeight) : -1;
UniValue transactions(UniValue::VARR);
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++)
{
CWalletTx tx = (*it).second;
if (depth == -1 || tx.GetDepthInMainChain() < depth)
ListTransactions(tx, "*", 0, true, transactions, filter);
}
CBlockIndex *pblockLast = chainActive[chainActive.Height() + 1 - target_confirms];
uint256 lastblock = pblockLast ? pblockLast->GetBlockHash() : uint256();
UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("transactions", transactions));
ret.push_back(Pair("lastblock", lastblock.GetHex()));
return ret;
}
UniValue gettransaction(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"gettransaction \"txid\" ( includeWatchonly )\n"
"\nGet detailed information about in-wallet transaction <txid>\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id\n"
"2. \"includeWatchonly\" (bool, optional, default=false) Whether to include watchonly addresses in balance calculation and details[]\n"
"\nResult:\n"
"{\n"
" \"amount\" : x.xxx, (numeric) The transaction amount in " + CURRENCY_UNIT + "\n"
" \"confirmations\" : n, (numeric) The number of confirmations\n"
" \"blockhash\" : \"hash\", (string) The block hash\n"
" \"blockindex\" : xx, (numeric) The block index\n"
" \"blocktime\" : ttt, (numeric) The time in seconds since epoch (1 Jan 1970 GMT)\n"
" \"txid\" : \"transactionid\", (string) The transaction id.\n"
" \"time\" : ttt, (numeric) The transaction time in seconds since epoch (1 Jan 1970 GMT)\n"
" \"timereceived\" : ttt, (numeric) The time received in seconds since epoch (1 Jan 1970 GMT)\n"
" \"bip125-replaceable\": \"yes|no|unknown\" (string) Whether this transaction could be replaced due to BIP125 (replace-by-fee);\n"
" may be unknown for unconfirmed transactions not in the mempool\n"
" \"details\" : [\n"
" {\n"
" \"account\" : \"accountname\", (string) DEPRECATED. The account name involved in the transaction, can be \"\" for the default account.\n"
" \"address\" : \"utabitaddress\", (string) The utabit address involved in the transaction\n"
" \"category\" : \"send|receive\", (string) The category, either 'send' or 'receive'\n"
" \"amount\" : x.xxx, (numeric) The amount in " + CURRENCY_UNIT + "\n"
" \"label\" : \"label\", (string) A comment for the address/transaction, if any\n"
" \"vout\" : n, (numeric) the vout value\n"
" }\n"
" ,...\n"
" ],\n"
" \"hex\" : \"data\" (string) Raw data for transaction\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
+ HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\" true")
+ HelpExampleRpc("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
uint256 hash;
hash.SetHex(params[0].get_str());
isminefilter filter = ISMINE_SPENDABLE;
if(params.size() > 1)
if(params[1].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
UniValue entry(UniValue::VOBJ);
if (!pwalletMain->mapWallet.count(hash))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id");
const CWalletTx& wtx = pwalletMain->mapWallet[hash];
CAmount nCredit = wtx.GetCredit(filter);
CAmount nDebit = wtx.GetDebit(filter);
CAmount nNet = nCredit - nDebit;
CAmount nFee = (wtx.IsFromMe(filter) ? wtx.GetValueOut() - nDebit : 0);
entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
if (wtx.IsFromMe(filter))
entry.push_back(Pair("fee", ValueFromAmount(nFee)));
WalletTxToJSON(wtx, entry);
UniValue details(UniValue::VARR);
ListTransactions(wtx, "*", 0, false, details, filter);
entry.push_back(Pair("details", details));
string strHex = EncodeHexTx(static_cast<CTransaction>(wtx));
entry.push_back(Pair("hex", strHex));
return entry;
}
UniValue abandontransaction(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 1)
throw runtime_error(
"abandontransaction \"txid\"\n"
"\nMark in-wallet transaction <txid> as abandoned\n"
"This will mark this transaction and all its in-wallet descendants as abandoned which will allow\n"
"for their inputs to be respent. It can be used to replace \"stuck\" or evicted transactions.\n"
"It only works on transactions which are not included in a block and are not currently in the mempool.\n"
"It has no effect on transactions which are already conflicted or abandoned.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id\n"
"\nResult:\n"
"\nExamples:\n"
+ HelpExampleCli("abandontransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
+ HelpExampleRpc("abandontransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
uint256 hash;
hash.SetHex(params[0].get_str());
if (!pwalletMain->mapWallet.count(hash))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id");
if (!pwalletMain->AbandonTransaction(hash))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not eligible for abandonment");
return NullUniValue;
}
UniValue backupwallet(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 1)
throw runtime_error(
"backupwallet \"destination\"\n"
"\nSafely copies wallet.dat to destination, which can be a directory or a path with filename.\n"
"\nArguments:\n"
"1. \"destination\" (string) The destination directory or file\n"
"\nExamples:\n"
+ HelpExampleCli("backupwallet", "\"backup.dat\"")
+ HelpExampleRpc("backupwallet", "\"backup.dat\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
string strDest = params[0].get_str();
if (!BackupWallet(*pwalletMain, strDest))
throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!");
return NullUniValue;
}
UniValue keypoolrefill(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 1)
throw runtime_error(
"keypoolrefill ( newsize )\n"
"\nFills the keypool."
+ HelpRequiringPassphrase() + "\n"
"\nArguments\n"
"1. newsize (numeric, optional, default=100) The new keypool size\n"
"\nExamples:\n"
+ HelpExampleCli("keypoolrefill", "")
+ HelpExampleRpc("keypoolrefill", "")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
// 0 is interpreted by TopUpKeyPool() as the default keypool size given by -keypool
unsigned int kpSize = 0;
if (params.size() > 0) {
if (params[0].get_int() < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected valid size.");
kpSize = (unsigned int)params[0].get_int();
}
EnsureWalletIsUnlocked();
pwalletMain->TopUpKeyPool(kpSize);
if (pwalletMain->GetKeyPoolSize() < kpSize)
throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool.");
return NullUniValue;
}
static void LockWallet(CWallet* pWallet)
{
LOCK(cs_nWalletUnlockTime);
nWalletUnlockTime = 0;
pWallet->Lock();
}
UniValue walletpassphrase(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
throw runtime_error(
"walletpassphrase \"passphrase\" timeout\n"
"\nStores the wallet decryption key in memory for 'timeout' seconds.\n"
"This is needed prior to performing transactions related to private keys such as sending utabits\n"
"\nArguments:\n"
"1. \"passphrase\" (string, required) The wallet passphrase\n"
"2. timeout (numeric, required) The time to keep the decryption key in seconds.\n"
"\nNote:\n"
"Issuing the walletpassphrase command while the wallet is already unlocked will set a new unlock\n"
"time that overrides the old one.\n"
"\nExamples:\n"
"\nunlock the wallet for 60 seconds\n"
+ HelpExampleCli("walletpassphrase", "\"my pass phrase\" 60") +
"\nLock the wallet again (before 60 seconds)\n"
+ HelpExampleCli("walletlock", "") +
"\nAs json rpc call\n"
+ HelpExampleRpc("walletpassphrase", "\"my pass phrase\", 60")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called.");
// Note that the walletpassphrase is stored in params[0] which is not mlock()ed
SecureString strWalletPass;
strWalletPass.reserve(100);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() > 0)
{
if (!pwalletMain->Unlock(strWalletPass))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
}
else
throw runtime_error(
"walletpassphrase <passphrase> <timeout>\n"
"Stores the wallet decryption key in memory for <timeout> seconds.");
pwalletMain->TopUpKeyPool();
int64_t nSleepTime = params[1].get_int64();
LOCK(cs_nWalletUnlockTime);
nWalletUnlockTime = GetTime() + nSleepTime;
RPCRunLater("lockwallet", boost::bind(LockWallet, pwalletMain), nSleepTime);
return NullUniValue;
}
UniValue walletpassphrasechange(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
throw runtime_error(
"walletpassphrasechange \"oldpassphrase\" \"newpassphrase\"\n"
"\nChanges the wallet passphrase from 'oldpassphrase' to 'newpassphrase'.\n"
"\nArguments:\n"
"1. \"oldpassphrase\" (string) The current passphrase\n"
"2. \"newpassphrase\" (string) The new passphrase\n"
"\nExamples:\n"
+ HelpExampleCli("walletpassphrasechange", "\"old one\" \"new one\"")
+ HelpExampleRpc("walletpassphrasechange", "\"old one\", \"new one\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.");
// TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strOldWalletPass;
strOldWalletPass.reserve(100);
strOldWalletPass = params[0].get_str().c_str();
SecureString strNewWalletPass;
strNewWalletPass.reserve(100);
strNewWalletPass = params[1].get_str().c_str();
if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1)
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
return NullUniValue;
}
UniValue walletlock(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0))
throw runtime_error(
"walletlock\n"
"\nRemoves the wallet encryption key from memory, locking the wallet.\n"
"After calling this method, you will need to call walletpassphrase again\n"
"before being able to call any methods which require the wallet to be unlocked.\n"
"\nExamples:\n"
"\nSet the passphrase for 2 minutes to perform a transaction\n"
+ HelpExampleCli("walletpassphrase", "\"my pass phrase\" 120") +
"\nPerform a send (requires passphrase set)\n"
+ HelpExampleCli("sendtoaddress", "\"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\" 1.0") +
"\nClear the passphrase since we are done before 2 minutes is up\n"
+ HelpExampleCli("walletlock", "") +
"\nAs json rpc call\n"
+ HelpExampleRpc("walletlock", "")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called.");
{
LOCK(cs_nWalletUnlockTime);
pwalletMain->Lock();
nWalletUnlockTime = 0;
}
return NullUniValue;
}
UniValue encryptwallet(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1))
throw runtime_error(
"encryptwallet \"passphrase\"\n"
"\nEncrypts the wallet with 'passphrase'. This is for first time encryption.\n"
"After this, any calls that interact with private keys such as sending or signing \n"
"will require the passphrase to be set prior the making these calls.\n"
"Use the walletpassphrase call for this, and then walletlock call.\n"
"If the wallet is already encrypted, use the walletpassphrasechange call.\n"
"Note that this will shutdown the server.\n"
"\nArguments:\n"
"1. \"passphrase\" (string) The pass phrase to encrypt the wallet with. It must be at least 1 character, but should be long.\n"
"\nExamples:\n"
"\nEncrypt you wallet\n"
+ HelpExampleCli("encryptwallet", "\"my pass phrase\"") +
"\nNow set the passphrase to use the wallet, such as for signing or sending utabit\n"
+ HelpExampleCli("walletpassphrase", "\"my pass phrase\"") +
"\nNow we can so something like sign\n"
+ HelpExampleCli("signmessage", "\"utabitaddress\" \"test message\"") +
"\nNow lock the wallet again by removing the passphrase\n"
+ HelpExampleCli("walletlock", "") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("encryptwallet", "\"my pass phrase\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
if (fHelp)
return true;
if (pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called.");
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strWalletPass;
strWalletPass.reserve(100);
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() < 1)
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (!pwalletMain->EncryptWallet(strWalletPass))
throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet.");
// BDB seems to have a bad habit of writing old data into
// slack space in .dat files; that is bad if the old data is
// unencrypted private keys. So:
StartShutdown();
return "wallet encrypted; Utabit server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup.";
}
UniValue lockunspent(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"lockunspent unlock [{\"txid\":\"txid\",\"vout\":n},...]\n"
"\nUpdates list of temporarily unspendable outputs.\n"
"Temporarily lock (unlock=false) or unlock (unlock=true) specified transaction outputs.\n"
"A locked transaction output will not be chosen by automatic coin selection, when spending utabits.\n"
"Locks are stored in memory only. Nodes start with zero locked outputs, and the locked output list\n"
"is always cleared (by virtue of process exit) when a node stops or fails.\n"
"Also see the listunspent call\n"
"\nArguments:\n"
"1. unlock (boolean, required) Whether to unlock (true) or lock (false) the specified transactions\n"
"2. \"transactions\" (string, required) A json array of objects. Each object the txid (string) vout (numeric)\n"
" [ (json array of json objects)\n"
" {\n"
" \"txid\":\"id\", (string) The transaction id\n"
" \"vout\": n (numeric) The output number\n"
" }\n"
" ,...\n"
" ]\n"
"\nResult:\n"
"true|false (boolean) Whether the command was successful or not\n"
"\nExamples:\n"
"\nList the unspent transactions\n"
+ HelpExampleCli("listunspent", "") +
"\nLock an unspent transaction\n"
+ HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nList the locked transactions\n"
+ HelpExampleCli("listlockunspent", "") +
"\nUnlock the transaction again\n"
+ HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("lockunspent", "false, \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
if (params.size() == 1)
RPCTypeCheck(params, boost::assign::list_of(UniValue::VBOOL));
else
RPCTypeCheck(params, boost::assign::list_of(UniValue::VBOOL)(UniValue::VARR));
bool fUnlock = params[0].get_bool();
if (params.size() == 1) {
if (fUnlock)
pwalletMain->UnlockAllCoins();
return true;
}
UniValue outputs = params[1].get_array();
for (unsigned int idx = 0; idx < outputs.size(); idx++) {
const UniValue& output = outputs[idx];
if (!output.isObject())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected object");
const UniValue& o = output.get_obj();
RPCTypeCheckObj(o, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM));
string txid = find_value(o, "txid").get_str();
if (!IsHex(txid))
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");
int nOutput = find_value(o, "vout").get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
COutPoint outpt(uint256S(txid), nOutput);
if (fUnlock)
pwalletMain->UnlockCoin(outpt);
else
pwalletMain->LockCoin(outpt);
}
return true;
}
UniValue listlockunspent(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 0)
throw runtime_error(
"listlockunspent\n"
"\nReturns list of temporarily unspendable outputs.\n"
"See the lockunspent call to lock and unlock transactions for spending.\n"
"\nResult:\n"
"[\n"
" {\n"
" \"txid\" : \"transactionid\", (string) The transaction id locked\n"
" \"vout\" : n (numeric) The vout value\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n"
"\nList the unspent transactions\n"
+ HelpExampleCli("listunspent", "") +
"\nLock an unspent transaction\n"
+ HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nList the locked transactions\n"
+ HelpExampleCli("listlockunspent", "") +
"\nUnlock the transaction again\n"
+ HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("listlockunspent", "")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
vector<COutPoint> vOutpts;
pwalletMain->ListLockedCoins(vOutpts);
UniValue ret(UniValue::VARR);
BOOST_FOREACH(COutPoint &outpt, vOutpts) {
UniValue o(UniValue::VOBJ);
o.push_back(Pair("txid", outpt.hash.GetHex()));
o.push_back(Pair("vout", (int)outpt.n));
ret.push_back(o);
}
return ret;
}
UniValue settxfee(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 1 || params.size() > 1)
throw runtime_error(
"settxfee amount\n"
"\nSet the transaction fee per kB. Overwrites the paytxfee parameter.\n"
"\nArguments:\n"
"1. amount (numeric or sting, required) The transaction fee in " + CURRENCY_UNIT + "/kB\n"
"\nResult\n"
"true|false (boolean) Returns true if successful\n"
"\nExamples:\n"
+ HelpExampleCli("settxfee", "0.00001")
+ HelpExampleRpc("settxfee", "0.00001")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
// Amount
CAmount nAmount = AmountFromValue(params[0]);
payTxFee = CFeeRate(nAmount, 1000);
return true;
}
UniValue getwalletinfo(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 0)
throw runtime_error(
"getwalletinfo\n"
"Returns an object containing various wallet state info.\n"
"\nResult:\n"
"{\n"
" \"walletversion\": xxxxx, (numeric) the wallet version\n"
" \"balance\": xxxxxxx, (numeric) the total confirmed balance of the wallet in " + CURRENCY_UNIT + "\n"
" \"unconfirmed_balance\": xxx, (numeric) the total unconfirmed balance of the wallet in " + CURRENCY_UNIT + "\n"
" \"immature_balance\": xxxxxx, (numeric) the total immature balance of the wallet in " + CURRENCY_UNIT + "\n"
" \"txcount\": xxxxxxx, (numeric) the total number of transactions in the wallet\n"
" \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since GMT epoch) of the oldest pre-generated key in the key pool\n"
" \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated\n"
" \"unlocked_until\": ttt, (numeric) the timestamp in seconds since epoch (midnight Jan 1 1970 GMT) that the wallet is unlocked for transfers, or 0 if the wallet is locked\n"
" \"paytxfee\": x.xxxx, (numeric) the transaction fee configuration, set in " + CURRENCY_UNIT + "/kB\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getwalletinfo", "")
+ HelpExampleRpc("getwalletinfo", "")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
obj.push_back(Pair("unconfirmed_balance", ValueFromAmount(pwalletMain->GetUnconfirmedBalance())));
obj.push_back(Pair("immature_balance", ValueFromAmount(pwalletMain->GetImmatureBalance())));
obj.push_back(Pair("txcount", (int)pwalletMain->mapWallet.size()));
obj.push_back(Pair("keypoololdest", pwalletMain->GetOldestKeyPoolTime()));
obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize()));
if (pwalletMain->IsCrypted())
obj.push_back(Pair("unlocked_until", nWalletUnlockTime));
obj.push_back(Pair("paytxfee", ValueFromAmount(payTxFee.GetFeePerK())));
return obj;
}
UniValue resendwallettransactions(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 0)
throw runtime_error(
"resendwallettransactions\n"
"Immediately re-broadcast unconfirmed wallet transactions to all peers.\n"
"Intended only for testing; the wallet code periodically re-broadcasts\n"
"automatically.\n"
"Returns array of transaction ids that were re-broadcast.\n"
);
LOCK2(cs_main, pwalletMain->cs_wallet);
std::vector<uint256> txids = pwalletMain->ResendWalletTransactionsBefore(GetTime());
UniValue result(UniValue::VARR);
BOOST_FOREACH(const uint256& txid, txids)
{
result.push_back(txid.ToString());
}
return result;
}
UniValue listunspent(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 3)
throw runtime_error(
"listunspent ( minconf maxconf [\"address\",...] )\n"
"\nReturns array of unspent transaction outputs\n"
"with between minconf and maxconf (inclusive) confirmations.\n"
"Optionally filter to only include txouts paid to specified addresses.\n"
"Results are an array of Objects, each of which has:\n"
"{txid, vout, scriptPubKey, amount, confirmations}\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) The minimum confirmations to filter\n"
"2. maxconf (numeric, optional, default=9999999) The maximum confirmations to filter\n"
"3. \"addresses\" (string) A json array of utabit addresses to filter\n"
" [\n"
" \"address\" (string) utabit address\n"
" ,...\n"
" ]\n"
"\nResult\n"
"[ (array of json object)\n"
" {\n"
" \"txid\" : \"txid\", (string) the transaction id \n"
" \"vout\" : n, (numeric) the vout value\n"
" \"address\" : \"address\", (string) the utabit address\n"
" \"account\" : \"account\", (string) DEPRECATED. The associated account, or \"\" for the default account\n"
" \"scriptPubKey\" : \"key\", (string) the script key\n"
" \"amount\" : x.xxx, (numeric) the transaction amount in " + CURRENCY_UNIT + "\n"
" \"confirmations\" : n (numeric) The number of confirmations\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples\n"
+ HelpExampleCli("listunspent", "")
+ HelpExampleCli("listunspent", "6 9999999 \"[\\\"1PGFqEzfmQch1gKD3ra4k18PNj3tTUUSqg\\\",\\\"1LtvqCaApEdUGFkpKMM4MstjcaL4dKg8SP\\\"]\"")
+ HelpExampleRpc("listunspent", "6, 9999999 \"[\\\"1PGFqEzfmQch1gKD3ra4k18PNj3tTUUSqg\\\",\\\"1LtvqCaApEdUGFkpKMM4MstjcaL4dKg8SP\\\"]\"")
);
RPCTypeCheck(params, boost::assign::list_of(UniValue::VNUM)(UniValue::VNUM)(UniValue::VARR));
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
int nMaxDepth = 9999999;
if (params.size() > 1)
nMaxDepth = params[1].get_int();
set<CUtabitAddress> setAddress;
if (params.size() > 2) {
UniValue inputs = params[2].get_array();
for (unsigned int idx = 0; idx < inputs.size(); idx++) {
const UniValue& input = inputs[idx];
CUtabitAddress address(input.get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Utabit address: ")+input.get_str());
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+input.get_str());
setAddress.insert(address);
}
}
UniValue results(UniValue::VARR);
vector<COutput> vecOutputs;
assert(pwalletMain != NULL);
LOCK2(cs_main, pwalletMain->cs_wallet);
pwalletMain->AvailableCoins(vecOutputs, false, NULL, true);
BOOST_FOREACH(const COutput& out, vecOutputs) {
if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth)
continue;
if (setAddress.size()) {
CTxDestination address;
if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
continue;
if (!setAddress.count(address))
continue;
}
CAmount nValue = out.tx->vout[out.i].nValue;
const CScript& pk = out.tx->vout[out.i].scriptPubKey;
UniValue entry(UniValue::VOBJ);
entry.push_back(Pair("txid", out.tx->GetHash().GetHex()));
entry.push_back(Pair("vout", out.i));
CTxDestination address;
if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) {
entry.push_back(Pair("address", CUtabitAddress(address).ToString()));
if (pwalletMain->mapAddressBook.count(address))
entry.push_back(Pair("account", pwalletMain->mapAddressBook[address].name));
}
entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end())));
if (pk.IsPayToScriptHash()) {
CTxDestination address;
if (ExtractDestination(pk, address)) {
const CScriptID& hash = boost::get<CScriptID>(address);
CScript redeemScript;
if (pwalletMain->GetCScript(hash, redeemScript))
entry.push_back(Pair("redeemScript", HexStr(redeemScript.begin(), redeemScript.end())));
}
}
entry.push_back(Pair("amount",ValueFromAmount(nValue)));
entry.push_back(Pair("confirmations",out.nDepth));
entry.push_back(Pair("spendable", out.fSpendable));
results.push_back(entry);
}
return results;
}
UniValue fundrawtransaction(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"fundrawtransaction \"hexstring\" includeWatching\n"
"\nAdd inputs to a transaction until it has enough in value to meet its out value.\n"
"This will not modify existing inputs, and will add one change output to the outputs.\n"
"Note that inputs which were signed may need to be resigned after completion since in/outputs have been added.\n"
"The inputs added will not be signed, use signrawtransaction for that.\n"
"Note that all existing inputs must have their previous output transaction be in the wallet.\n"
"Note that all inputs selected must be of standard form and P2SH scripts must be"
"in the wallet using importaddress or addmultisigaddress (to calculate fees).\n"
"Only pay-to-pubkey, multisig, and P2SH versions thereof are currently supported for watch-only\n"
"\nArguments:\n"
"1. \"hexstring\" (string, required) The hex string of the raw transaction\n"
"2. includeWatching (boolean, optional, default false) Also select inputs which are watch only\n"
"\nResult:\n"
"{\n"
" \"hex\": \"value\", (string) The resulting raw transaction (hex-encoded string)\n"
" \"fee\": n, (numeric) Fee the resulting transaction pays\n"
" \"changepos\": n (numeric) The position of the added change output, or -1\n"
"}\n"
"\"hex\" \n"
"\nExamples:\n"
"\nCreate a transaction with no inputs\n"
+ HelpExampleCli("createrawtransaction", "\"[]\" \"{\\\"myaddress\\\":0.01}\"") +
"\nAdd sufficient unsigned inputs to meet the output value\n"
+ HelpExampleCli("fundrawtransaction", "\"rawtransactionhex\"") +
"\nSign the transaction\n"
+ HelpExampleCli("signrawtransaction", "\"fundedtransactionhex\"") +
"\nSend the transaction\n"
+ HelpExampleCli("sendrawtransaction", "\"signedtransactionhex\"")
);
RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)(UniValue::VBOOL));
// parse hex string from parameter
CTransaction origTx;
if (!DecodeHexTx(origTx, params[0].get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
if (origTx.vout.size() == 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "TX must have at least one output");
bool includeWatching = false;
if (params.size() > 1)
includeWatching = params[1].get_bool();
CMutableTransaction tx(origTx);
CAmount nFee;
string strFailReason;
int nChangePos = -1;
if(!pwalletMain->FundTransaction(tx, nFee, nChangePos, strFailReason, includeWatching))
throw JSONRPCError(RPC_INTERNAL_ERROR, strFailReason);
UniValue result(UniValue::VOBJ);
result.push_back(Pair("hex", EncodeHexTx(tx)));
result.push_back(Pair("changepos", nChangePos));
result.push_back(Pair("fee", ValueFromAmount(nFee)));
return result;
}
|
// dllmain.cpp : Defines the entry point for the DLL application.
#pragma once
#include "FileTypes/ItemsData.h"
#include "FileTypes/ItemMake.h"
#include "FileTypes/PopBase.h"
#include "pch.h"
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
|
/*
** Copyright 2014-2015 Centreon
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
**
** For more information : contact@centreon.com
*/
#ifndef CCB_GRAPHITE_FACTORY_HH
# define CCB_GRAPHITE_FACTORY_HH
# include "com/centreon/broker/io/factory.hh"
# include "com/centreon/broker/namespace.hh"
CCB_BEGIN()
namespace graphite {
/**
* @class factory factory.hh "com/centreon/broker/graphite/factory.hh"
* @brief Graphite layer factory.
*
* Build Graphite layer objects.
*/
class factory : public io::factory {
public:
factory();
factory(factory const& other);
~factory();
factory& operator=(factory const& other);
io::factory* clone() const;
bool has_endpoint(config::endpoint& cfg) const;
io::endpoint* new_endpoint(
config::endpoint& cfg,
bool& is_acceptor,
std::shared_ptr<persistent_cache> cache) const;
};
}
CCB_END()
#endif // !CCB_GRAPHITE_FACTORY_HH
|
//-------------------------------------------------------------------------
/*
Copyright (C) 2010-2019 EDuke32 developers and contributors
Copyright (C) 2019 sirlemonhead, Nuke.YKT
This file is part of PCExhumed.
PCExhumed is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.
This program 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 this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
//-------------------------------------------------------------------------
#include "ns.h"
#include "engine.h"
#include "exhumed.h"
#include "view.h"
#include "aistuff.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
BEGIN_PS_NS
enum { kMaxGrads = 12 };
const char *GradList[kMaxGrads] = {
"normal.rmp",
"nodim.rmp",
"torch.rmp",
"notorch.rmp",
"brite.rmp",
"redbrite.rmp",
"grnbrite.rmp",
"normal.rmp",
"nodim.rmp",
"torch.rmp",
"notorch.rmp",
"brite.rmp"
};
int rtint = 0;
int gtint = 0;
int btint = 0;
palette_t *fadedestpal;
palette_t *fadecurpal;
int nPalDelay;
int nPalDiff;
int bGreenPal = 0;
// keep a local copy of the palette that would have been sent to the VGA display adapter
uint8_t vgaPalette[768];
int LoadPaletteLookups()
{
uint8_t buffer[256*64];
numshades = 64;
for (int i = 0; i < kMaxGrads; i++)
{
auto hFile = fileSystem.OpenFileReader(GradList[i]);
if (!hFile.isOpen())
{
Printf("Error reading palette lookup '%s'\n", GradList[i]);
return 0;
}
hFile.Read(buffer, 256*64);
lookups.setTable(i, buffer);
bGreenPal = 0;
// These 3 tables do not have normal gradients. The others work without adjustment.
// Other changes than altering the fog gradient are not necessary.
lookups.tables[kPalTorch].ShadeFactor = lookups.tables[kPalTorch2].ShadeFactor = (numshades - 2) / 20.f;
lookups.tables[kPalNoTorch].ShadeFactor = lookups.tables[kPalNoTorch2].ShadeFactor = (numshades - 2) / 4.f;
lookups.tables[kPalBrite].ShadeFactor = lookups.tables[kPalBrite2].ShadeFactor = (numshades - 2) / 128.f;
lookups.setFadeColor(kPalRedBrite, 255, 0, 0);
}
return 1;
}
void SetGreenPal()
{
bGreenPal = 1;
}
void RestoreGreenPal()
{
bGreenPal = 0;
}
int HavePLURemap()
{
return bGreenPal || bTorch;
}
uint8_t RemapPLU(uint8_t pal)
{
if (bGreenPal)
{
if (pal != kPalRedBrite)
pal = kPalGreenBrite;
}
else if (bTorch)
{
switch (pal)
{
case kPalTorch:
pal = kPalNoTorch;
break;
case kPalNoTorch:
pal = kPalTorch;
break;
case kPalTorch2:
pal = kPalNoTorch2;
break;
case kPalNoTorch2:
pal = kPalTorch2;
break;
}
}
return pal;
}
void GrabPalette()
{
nPalDiff = 0;
nPalDelay = 0;
btint = 0;
gtint = 0;
rtint = 0;
videoTintBlood(0, 0, 0);
}
void FixPalette()
{
if (!nPalDiff) {
return;
}
if (nPalDelay > 0)
{
nPalDelay--;
return;
}
nPalDelay = 5;
nPalDiff -= 20;
gtint -= 20;
rtint -= 20;
btint -= 20;
if (gtint < 0) {
gtint = 0;
}
if (rtint < 0) {
rtint = 0;
}
if (btint < 0) {
btint = 0;
}
if (nPalDiff < 0) {
nPalDiff = 0;
}
videoTintBlood(rtint, gtint, btint);
}
void TintPalette(int r, int g, int b)
{
if (bCamera) {
return;
}
// range limit R between 20 and 255 if positive
if (r > 255)
{
r = 255;
}
else
{
if (r && r < 20) {
r = 20;
}
}
// range limit G between 20 and 255 if positive
if (g > 255)
{
g = 255;
}
else
{
if (g && g < 20) {
g = 20;
}
}
// range limit B between 20 and 255 if positive
if (b > 255)
{
b = 255;
}
else
{
if (b && b < 20) {
b = 20;
}
}
// loc_17EFA
if (g && gtint > 32) {
return;
}
gtint += g;
if (r && rtint > 256) {
return;
}
rtint += r;
btint += b;
// do not modify r, g or b variables from this point on
int nVal;
// loc_17F49
if (abs(r) > abs(g)) {
nVal = abs(r);
}
else {
nVal = abs(g);
}
if (nVal < abs(b)) {
nVal = abs(b);
}
nPalDiff += nVal;
videoTintBlood(rtint, gtint, btint);
nPalDelay = 0;
}
END_PS_NS
|
#include <muduo/net/Buffer.h>
#include <gtest/gtest.h>
using muduo::string;
using muduo::net::Buffer;
TEST(testBufferAppendRetrieve, readWritePrepend)
{
Buffer buf;
EXPECT_EQ(buf.readableBytes(), (unsigned long)(0));
EXPECT_EQ(buf.writableBytes(), Buffer::kInitialSize);
EXPECT_EQ(buf.prependableBytes(), Buffer::kCheapPrepend);
const string str(200, 'x');
buf.append(str);
EXPECT_EQ(buf.readableBytes(), str.size());
EXPECT_EQ(buf.writableBytes(), Buffer::kInitialSize - str.size());
EXPECT_EQ(buf.prependableBytes(), Buffer::kCheapPrepend);
const string str2 = buf.retrieveAsString(50);
EXPECT_EQ(str2.size(), (unsigned long)(50));
EXPECT_EQ(buf.readableBytes(), str.size() - str2.size());
EXPECT_EQ(buf.writableBytes(), Buffer::kInitialSize - str.size());
EXPECT_EQ(buf.prependableBytes(), Buffer::kCheapPrepend + str2.size());
buf.append(str);
EXPECT_EQ(buf.readableBytes(), 2*str.size() - str2.size());
EXPECT_EQ(buf.writableBytes(), Buffer::kInitialSize - 2*str.size());
EXPECT_EQ(buf.prependableBytes(), Buffer::kCheapPrepend + str2.size());
const string str3 = buf.retrieveAllAsString();
EXPECT_EQ(str3.size(), (unsigned long)(350));
EXPECT_EQ(buf.readableBytes(), (unsigned long)(0));
EXPECT_EQ(buf.writableBytes(), Buffer::kInitialSize);
EXPECT_EQ(buf.prependableBytes(), Buffer::kCheapPrepend);
}
TEST(testBufferGrow, append)
{
Buffer buf;
buf.append(string(400, 'y'));
EXPECT_EQ(buf.readableBytes(), (unsigned long)400);
EXPECT_EQ(buf.writableBytes(), Buffer::kInitialSize-400);
buf.retrieve(50);
EXPECT_EQ(buf.readableBytes(), (unsigned long)350);
EXPECT_EQ(buf.writableBytes(), Buffer::kInitialSize-400);
EXPECT_EQ(buf.prependableBytes(), Buffer::kCheapPrepend+50);
buf.append(string(1000, 'z'));
EXPECT_EQ(buf.readableBytes(), (unsigned long)1350);
EXPECT_EQ(buf.writableBytes(), (unsigned long)0);
EXPECT_EQ(buf.prependableBytes(), Buffer::kCheapPrepend+50); // FIXME
buf.retrieveAll();
EXPECT_EQ(buf.readableBytes(), (unsigned long)0);
EXPECT_EQ(buf.writableBytes(), (unsigned long)1400); // FIXME
EXPECT_EQ(buf.prependableBytes(), Buffer::kCheapPrepend);
}
TEST(testBufferInsideGrow, retrieve)
{
Buffer buf;
buf.append(string(800, 'y'));
EXPECT_EQ(buf.readableBytes(), (unsigned long)800);
EXPECT_EQ(buf.writableBytes(), Buffer::kInitialSize-800);
buf.retrieve(500);
EXPECT_EQ(buf.readableBytes(), (unsigned long)300);
EXPECT_EQ(buf.writableBytes(), Buffer::kInitialSize-800);
EXPECT_EQ(buf.prependableBytes(), Buffer::kCheapPrepend+500);
buf.append(string(300, 'z'));
EXPECT_EQ(buf.readableBytes(), (unsigned long)600);
EXPECT_EQ(buf.writableBytes(), Buffer::kInitialSize-600);
EXPECT_EQ(buf.prependableBytes(), Buffer::kCheapPrepend);
}
TEST(testBufferShrink, retrieve)
{
Buffer buf;
buf.append(string(2000, 'y'));
EXPECT_EQ(buf.readableBytes(), (unsigned long)2000);
EXPECT_EQ(buf.writableBytes(), (unsigned long)0);
EXPECT_EQ(buf.prependableBytes(), Buffer::kCheapPrepend);
buf.retrieve(1500);
EXPECT_EQ(buf.readableBytes(), (unsigned long)500);
EXPECT_EQ(buf.writableBytes(), (unsigned long)0);
EXPECT_EQ(buf.prependableBytes(), Buffer::kCheapPrepend+1500);
buf.shrink(0);
EXPECT_EQ(buf.readableBytes(), (unsigned long)500);
EXPECT_EQ(buf.writableBytes(), Buffer::kInitialSize-500);
EXPECT_EQ(buf.retrieveAllAsString(), string(500, 'y'));
EXPECT_EQ(buf.prependableBytes(), Buffer::kCheapPrepend);
}
TEST(testBufferPrepend, prePend)
{
Buffer buf;
buf.append(string(200, 'y'));
EXPECT_EQ(buf.readableBytes(), (unsigned long)200);
EXPECT_EQ(buf.writableBytes(), Buffer::kInitialSize-200);
EXPECT_EQ(buf.prependableBytes(), Buffer::kCheapPrepend);
int x = 0;
buf.prepend(&x, sizeof x);
EXPECT_EQ(buf.readableBytes(), (unsigned long)204);
EXPECT_EQ(buf.writableBytes(), Buffer::kInitialSize-200);
EXPECT_EQ(buf.prependableBytes(), Buffer::kCheapPrepend - 4);
}
TEST(testBufferReadInt, read)
{
Buffer buf;
buf.append("HTTP");
EXPECT_EQ(buf.readableBytes(), (unsigned long)4);
EXPECT_EQ(buf.peekInt8(), 'H');
int top16 = buf.peekInt16();
EXPECT_EQ(top16, 'H'*256 + 'T');
EXPECT_EQ(buf.peekInt32(), top16*65536 + 'T'*256 + 'P');
EXPECT_EQ(buf.readInt8(), 'H');
EXPECT_EQ(buf.readInt16(), 'T'*256 + 'T');
EXPECT_EQ(buf.readInt8(), 'P');
EXPECT_EQ(buf.readableBytes(), (unsigned long)0);
EXPECT_EQ(buf.writableBytes(), Buffer::kInitialSize);
buf.appendInt8(-1);
buf.appendInt16(-1);
buf.appendInt32(-1);
EXPECT_EQ(buf.readableBytes(), (unsigned long)7);
EXPECT_EQ(buf.readInt8(), -1);
EXPECT_EQ(buf.readInt32(), -1);
EXPECT_EQ(buf.readInt16(), -1);
}
TEST(testBufferFindEOL, findEOL)
{
Buffer buf;
buf.append(string(100000, 'x'));
const char* null = NULL;
EXPECT_EQ(buf.findEOL(), null);
EXPECT_EQ(buf.findEOL(buf.peek()+90000), null);
}
void output(Buffer&& buf, const void* inner)
{
Buffer newbuf(std::move(buf));
// printf("New Buffer at %p, inner %p\n", &newbuf, newbuf.peek());
EXPECT_EQ(inner, newbuf.peek());
}
// NOTE: This test fails in g++ 4.4, passes in g++ 4.6.
TEST(testMove, move)
{
Buffer buf;
buf.append("muduo", 5);
const void* inner = buf.peek();
// printf("Buffer at %p, inner %p\n", &buf, inner);
output(std::move(buf), inner);
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
#include "geqrftest.hh"
#include <lapack/geqrf.hh>
#include <lapack/ormqr.hh>
using namespace Linalg;
void
GEQRFTest::setUp()
{
// Allocate some space;
tau = Vector<double>(3);
static double a_data[9] = { 12, -51, 4,
6, 167, -68,
-4, 24, -41 };
A = Matrix<double>::fromData(a_data, 3, 3, 3, 1, 0).copy();
}
void
GEQRFTest::testRealNN()
{
Vector<double> tmp(this->A.rows());
Matrix<double> A = this->A.copy();
Lapack::geqrf(A, tau);
{
Matrix<double> B = this->A.copy();
Lapack::ormqr(A, tau, B, tmp, true, true);
for (size_t i=0; i<3; i++) {
for (size_t j=i; j<3; j++) {
UT_ASSERT_NEAR(B(i,j), A(i,j));
}
}
}
{
Matrix<double> B = this->A.copy().t();
Lapack::ormqr(A, tau, B, tmp, false, false);
for (size_t i=0; i<3; i++) {
for (size_t j=i; j<3; j++) {
UT_ASSERT_NEAR(B(j,i), A(i,j));
}
}
}
}
void
GEQRFTest::testRealMN()
{
static double a_data[24] = {0,0,0, 0,0,1, 0,1,0, 0,1,1, 1,0,0, 1,0,1, 1,1,0, 1,1,1};
static double b_data[8] = {0, 1, 1, 2, 1, 2, 2, 3};
Matrix<double> A = Matrix<double>::fromData(a_data, 8, 3, 3, 1, 0);
Vector<double> b = Matrix<double>::fromData(b_data, 8, 1, 1, 8, 0).col(0);
Vector<double> tau(3), tmp(8);
Lapack::geqrf(A, tau);
Lapack::ormqr(A, tau, b, tmp, true, true);
for (size_t i=0; i<3; i++) {
double row_sum_R = 0.0;
for (size_t j=i; j<3; j++){
row_sum_R += A(i,j);
}
UT_ASSERT_NEAR(b(i), row_sum_R);
}
}
UnitTest::TestSuite *
GEQRFTest::suite()
{
UnitTest::TestSuite *s = new UnitTest::TestSuite("Tests for geqrf :");
s->addTest(new UnitTest::TestCaller<GEQRFTest>(
"Lapack::geqrf(double[n,n])", &GEQRFTest::testRealNN));
s->addTest(new UnitTest::TestCaller<GEQRFTest>(
"Lapack::geqrf(double[m,n])", &GEQRFTest::testRealMN));
return s;
}
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include <algorithm>
#include <iostream>
#include <limits>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "arrow/chunked_array.h"
#include "arrow/compute/api.h"
#include "arrow/compute/kernels/test_util.h"
#include "arrow/table.h"
#include "arrow/testing/gtest_common.h"
#include "arrow/testing/gtest_util.h"
#include "arrow/testing/random.h"
#include "arrow/testing/util.h"
namespace arrow {
using internal::checked_cast;
using internal::checked_pointer_cast;
using util::string_view;
namespace compute {
// ----------------------------------------------------------------------
TEST(GetTakeIndices, Basics) {
auto CheckCase = [&](const std::string& filter_json, const std::string& indices_json,
FilterOptions::NullSelectionBehavior null_selection,
const std::shared_ptr<DataType>& indices_type = uint16()) {
auto filter = ArrayFromJSON(boolean(), filter_json);
auto expected_indices = ArrayFromJSON(indices_type, indices_json);
ASSERT_OK_AND_ASSIGN(auto indices,
internal::GetTakeIndices(*filter->data(), null_selection));
AssertArraysEqual(*expected_indices, *MakeArray(indices), /*verbose=*/true);
};
// Drop null cases
CheckCase("[]", "[]", FilterOptions::DROP);
CheckCase("[null]", "[]", FilterOptions::DROP);
CheckCase("[null, false, true, true, false, true]", "[2, 3, 5]", FilterOptions::DROP);
// Emit null cases
CheckCase("[]", "[]", FilterOptions::EMIT_NULL);
CheckCase("[null]", "[null]", FilterOptions::EMIT_NULL);
CheckCase("[null, false, true, true]", "[null, 2, 3]", FilterOptions::EMIT_NULL);
}
// TODO: Add slicing
template <typename IndexArrayType>
void CheckGetTakeIndicesCase(const Array& untyped_filter) {
const auto& filter = checked_cast<const BooleanArray&>(untyped_filter);
ASSERT_OK_AND_ASSIGN(std::shared_ptr<ArrayData> drop_indices,
internal::GetTakeIndices(*filter.data(), FilterOptions::DROP));
// Verify DROP indices
{
IndexArrayType indices(drop_indices);
int64_t out_position = 0;
for (int64_t i = 0; i < filter.length(); ++i) {
if (filter.IsValid(i)) {
if (filter.Value(i)) {
ASSERT_EQ(indices.Value(out_position), i);
++out_position;
}
}
}
// Check that the end length agrees with the output of GetFilterOutputSize
ASSERT_EQ(out_position,
internal::GetFilterOutputSize(*filter.data(), FilterOptions::DROP));
}
ASSERT_OK_AND_ASSIGN(
std::shared_ptr<ArrayData> emit_indices,
internal::GetTakeIndices(*filter.data(), FilterOptions::EMIT_NULL));
// Verify EMIT_NULL indices
{
IndexArrayType indices(emit_indices);
int64_t out_position = 0;
for (int64_t i = 0; i < filter.length(); ++i) {
if (filter.IsValid(i)) {
if (filter.Value(i)) {
ASSERT_EQ(indices.Value(out_position), i);
++out_position;
}
} else {
ASSERT_TRUE(indices.IsNull(out_position));
++out_position;
}
}
// Check that the end length agrees with the output of GetFilterOutputSize
ASSERT_EQ(out_position,
internal::GetFilterOutputSize(*filter.data(), FilterOptions::EMIT_NULL));
}
}
TEST(GetTakeIndices, RandomlyGenerated) {
random::RandomArrayGenerator rng(kRandomSeed);
// Multiple of word size + 1
const int64_t length = 6401;
for (auto null_prob : {0.0, 0.01, 0.999, 1.0}) {
for (auto true_prob : {0.0, 0.01, 0.999, 1.0}) {
auto filter = rng.Boolean(length, true_prob, null_prob);
CheckGetTakeIndicesCase<UInt16Array>(*filter);
CheckGetTakeIndicesCase<UInt16Array>(*filter->Slice(7));
}
}
// Check that the uint32 path is traveled successfully
const int64_t uint16_max = std::numeric_limits<uint16_t>::max();
auto filter =
std::static_pointer_cast<BooleanArray>(rng.Boolean(uint16_max + 1, 0.99, 0.01));
CheckGetTakeIndicesCase<UInt16Array>(*filter->Slice(1));
CheckGetTakeIndicesCase<UInt32Array>(*filter);
}
// ----------------------------------------------------------------------
// Filter tests
std::shared_ptr<Array> CoalesceNullToFalse(std::shared_ptr<Array> filter) {
if (filter->null_count() == 0) {
return filter;
}
const auto& data = *filter->data();
auto is_true = std::make_shared<BooleanArray>(data.length, data.buffers[1]);
auto is_valid = std::make_shared<BooleanArray>(data.length, data.buffers[0]);
EXPECT_OK_AND_ASSIGN(Datum out_datum, And(is_true, is_valid));
return out_datum.make_array();
}
template <typename ArrowType>
class TestFilterKernel : public ::testing::Test {
protected:
TestFilterKernel() : emit_null_(FilterOptions::EMIT_NULL), drop_(FilterOptions::DROP) {}
void AssertFilter(std::shared_ptr<Array> values, std::shared_ptr<Array> filter,
std::shared_ptr<Array> expected) {
// test with EMIT_NULL
ASSERT_OK_AND_ASSIGN(Datum out_datum, Filter(values, filter, emit_null_));
auto actual = out_datum.make_array();
ASSERT_OK(actual->ValidateFull());
AssertArraysEqual(*expected, *actual);
// test with DROP using EMIT_NULL and a coalesced filter
auto coalesced_filter = CoalesceNullToFalse(filter);
ASSERT_OK_AND_ASSIGN(out_datum, Filter(values, coalesced_filter, emit_null_));
expected = out_datum.make_array();
ASSERT_OK_AND_ASSIGN(out_datum, Filter(values, filter, drop_));
actual = out_datum.make_array();
ASSERT_OK(actual->ValidateFull());
AssertArraysEqual(*expected, *actual);
}
void AssertFilter(std::shared_ptr<DataType> type, const std::string& values,
const std::string& filter, const std::string& expected) {
AssertFilter(ArrayFromJSON(type, values), ArrayFromJSON(boolean(), filter),
ArrayFromJSON(type, expected));
}
FilterOptions emit_null_, drop_;
};
void ValidateFilter(const std::shared_ptr<Array>& values,
const std::shared_ptr<Array>& filter_boxed) {
FilterOptions emit_null(FilterOptions::EMIT_NULL);
FilterOptions drop(FilterOptions::DROP);
ASSERT_OK_AND_ASSIGN(Datum out_datum, Filter(values, filter_boxed, emit_null));
auto filtered_emit_null = out_datum.make_array();
ASSERT_OK(filtered_emit_null->ValidateFull());
ASSERT_OK_AND_ASSIGN(out_datum, Filter(values, filter_boxed, drop));
auto filtered_drop = out_datum.make_array();
ASSERT_OK(filtered_drop->ValidateFull());
// Create the expected arrays using Take
ASSERT_OK_AND_ASSIGN(
std::shared_ptr<ArrayData> drop_indices,
internal::GetTakeIndices(*filter_boxed->data(), FilterOptions::DROP));
ASSERT_OK_AND_ASSIGN(Datum expected_drop, Take(values, Datum(drop_indices)));
ASSERT_OK_AND_ASSIGN(
std::shared_ptr<ArrayData> emit_null_indices,
internal::GetTakeIndices(*filter_boxed->data(), FilterOptions::EMIT_NULL));
ASSERT_OK_AND_ASSIGN(Datum expected_emit_null, Take(values, Datum(emit_null_indices)));
AssertArraysEqual(*expected_drop.make_array(), *filtered_drop,
/*verbose=*/true);
AssertArraysEqual(*expected_emit_null.make_array(), *filtered_emit_null,
/*verbose=*/true);
}
class TestFilterKernelWithNull : public TestFilterKernel<NullType> {
protected:
void AssertFilter(const std::string& values, const std::string& filter,
const std::string& expected) {
TestFilterKernel<NullType>::AssertFilter(ArrayFromJSON(null(), values),
ArrayFromJSON(boolean(), filter),
ArrayFromJSON(null(), expected));
}
};
TEST_F(TestFilterKernelWithNull, FilterNull) {
this->AssertFilter("[]", "[]", "[]");
this->AssertFilter("[null, null, null]", "[0, 1, 0]", "[null]");
this->AssertFilter("[null, null, null]", "[1, 1, 0]", "[null, null]");
}
class TestFilterKernelWithBoolean : public TestFilterKernel<BooleanType> {
protected:
void AssertFilter(const std::string& values, const std::string& filter,
const std::string& expected) {
TestFilterKernel<BooleanType>::AssertFilter(ArrayFromJSON(boolean(), values),
ArrayFromJSON(boolean(), filter),
ArrayFromJSON(boolean(), expected));
}
};
TEST_F(TestFilterKernelWithBoolean, FilterBoolean) {
this->AssertFilter("[]", "[]", "[]");
this->AssertFilter("[true, false, true]", "[0, 1, 0]", "[false]");
this->AssertFilter("[null, false, true]", "[0, 1, 0]", "[false]");
this->AssertFilter("[true, false, true]", "[null, 1, 0]", "[null, false]");
}
TEST_F(TestFilterKernelWithBoolean, DefaultOptions) {
auto values = ArrayFromJSON(int8(), "[7, 8, null, 9]");
auto filter = ArrayFromJSON(boolean(), "[1, 1, 0, null]");
ASSERT_OK_AND_ASSIGN(auto no_options_provided,
CallFunction("filter", {values, filter}));
auto default_options = FilterOptions::Defaults();
ASSERT_OK_AND_ASSIGN(auto explicit_defaults,
CallFunction("filter", {values, filter}, &default_options));
AssertDatumsEqual(explicit_defaults, no_options_provided);
}
template <typename ArrowType>
class TestFilterKernelWithNumeric : public TestFilterKernel<ArrowType> {
protected:
std::shared_ptr<DataType> type_singleton() {
return TypeTraits<ArrowType>::type_singleton();
}
};
TYPED_TEST_SUITE(TestFilterKernelWithNumeric, NumericArrowTypes);
TYPED_TEST(TestFilterKernelWithNumeric, FilterNumeric) {
auto type = this->type_singleton();
this->AssertFilter(type, "[]", "[]", "[]");
this->AssertFilter(type, "[9]", "[0]", "[]");
this->AssertFilter(type, "[9]", "[1]", "[9]");
this->AssertFilter(type, "[9]", "[null]", "[null]");
this->AssertFilter(type, "[null]", "[0]", "[]");
this->AssertFilter(type, "[null]", "[1]", "[null]");
this->AssertFilter(type, "[null]", "[null]", "[null]");
this->AssertFilter(type, "[7, 8, 9]", "[0, 1, 0]", "[8]");
this->AssertFilter(type, "[7, 8, 9]", "[1, 0, 1]", "[7, 9]");
this->AssertFilter(type, "[null, 8, 9]", "[0, 1, 0]", "[8]");
this->AssertFilter(type, "[7, 8, 9]", "[null, 1, 0]", "[null, 8]");
this->AssertFilter(type, "[7, 8, 9]", "[1, null, 1]", "[7, null, 9]");
this->AssertFilter(ArrayFromJSON(type, "[7, 8, 9]"),
ArrayFromJSON(boolean(), "[0, 1, 1, 1, 0, 1]")->Slice(3, 3),
ArrayFromJSON(type, "[7, 9]"));
ASSERT_RAISES(Invalid, Filter(ArrayFromJSON(type, "[7, 8, 9]"),
ArrayFromJSON(boolean(), "[]"), this->emit_null_));
ASSERT_RAISES(Invalid, Filter(ArrayFromJSON(type, "[7, 8, 9]"),
ArrayFromJSON(boolean(), "[]"), this->drop_));
}
template <typename CType>
using Comparator = bool(CType, CType);
template <typename CType>
Comparator<CType>* GetComparator(CompareOperator op) {
static Comparator<CType>* cmp[] = {
// EQUAL
[](CType l, CType r) { return l == r; },
// NOT_EQUAL
[](CType l, CType r) { return l != r; },
// GREATER
[](CType l, CType r) { return l > r; },
// GREATER_EQUAL
[](CType l, CType r) { return l >= r; },
// LESS
[](CType l, CType r) { return l < r; },
// LESS_EQUAL
[](CType l, CType r) { return l <= r; },
};
return cmp[op];
}
template <typename T, typename Fn, typename CType = typename TypeTraits<T>::CType>
std::shared_ptr<Array> CompareAndFilter(const CType* data, int64_t length, Fn&& fn) {
std::vector<CType> filtered;
filtered.reserve(length);
std::copy_if(data, data + length, std::back_inserter(filtered), std::forward<Fn>(fn));
std::shared_ptr<Array> filtered_array;
ArrayFromVector<T, CType>(filtered, &filtered_array);
return filtered_array;
}
template <typename T, typename CType = typename TypeTraits<T>::CType>
std::shared_ptr<Array> CompareAndFilter(const CType* data, int64_t length, CType val,
CompareOperator op) {
auto cmp = GetComparator<CType>(op);
return CompareAndFilter<T>(data, length, [&](CType e) { return cmp(e, val); });
}
template <typename T, typename CType = typename TypeTraits<T>::CType>
std::shared_ptr<Array> CompareAndFilter(const CType* data, int64_t length,
const CType* other, CompareOperator op) {
auto cmp = GetComparator<CType>(op);
return CompareAndFilter<T>(data, length, [&](CType e) { return cmp(e, *other++); });
}
TYPED_TEST(TestFilterKernelWithNumeric, CompareScalarAndFilterRandomNumeric) {
using ScalarType = typename TypeTraits<TypeParam>::ScalarType;
using ArrayType = typename TypeTraits<TypeParam>::ArrayType;
using CType = typename TypeTraits<TypeParam>::CType;
auto rand = random::RandomArrayGenerator(kRandomSeed);
for (size_t i = 3; i < 10; i++) {
const int64_t length = static_cast<int64_t>(1ULL << i);
// TODO(bkietz) rewrite with some nulls
auto array =
checked_pointer_cast<ArrayType>(rand.Numeric<TypeParam>(length, 0, 100, 0));
CType c_fifty = 50;
auto fifty = std::make_shared<ScalarType>(c_fifty);
for (auto op : {EQUAL, NOT_EQUAL, GREATER, LESS_EQUAL}) {
ASSERT_OK_AND_ASSIGN(Datum selection,
Compare(array, Datum(fifty), CompareOptions(op)));
ASSERT_OK_AND_ASSIGN(Datum filtered, Filter(array, selection));
auto filtered_array = filtered.make_array();
ASSERT_OK(filtered_array->ValidateFull());
auto expected =
CompareAndFilter<TypeParam>(array->raw_values(), array->length(), c_fifty, op);
ASSERT_ARRAYS_EQUAL(*filtered_array, *expected);
}
}
}
TYPED_TEST(TestFilterKernelWithNumeric, CompareArrayAndFilterRandomNumeric) {
using ArrayType = typename TypeTraits<TypeParam>::ArrayType;
auto rand = random::RandomArrayGenerator(kRandomSeed);
for (size_t i = 3; i < 10; i++) {
const int64_t length = static_cast<int64_t>(1ULL << i);
auto lhs = checked_pointer_cast<ArrayType>(
rand.Numeric<TypeParam>(length, 0, 100, /*null_probability=*/0.0));
auto rhs = checked_pointer_cast<ArrayType>(
rand.Numeric<TypeParam>(length, 0, 100, /*null_probability=*/0.0));
for (auto op : {EQUAL, NOT_EQUAL, GREATER, LESS_EQUAL}) {
ASSERT_OK_AND_ASSIGN(Datum selection, Compare(lhs, rhs, CompareOptions(op)));
ASSERT_OK_AND_ASSIGN(Datum filtered, Filter(lhs, selection));
auto filtered_array = filtered.make_array();
ASSERT_OK(filtered_array->ValidateFull());
auto expected = CompareAndFilter<TypeParam>(lhs->raw_values(), lhs->length(),
rhs->raw_values(), op);
ASSERT_ARRAYS_EQUAL(*filtered_array, *expected);
}
}
}
TYPED_TEST(TestFilterKernelWithNumeric, ScalarInRangeAndFilterRandomNumeric) {
using ScalarType = typename TypeTraits<TypeParam>::ScalarType;
using ArrayType = typename TypeTraits<TypeParam>::ArrayType;
using CType = typename TypeTraits<TypeParam>::CType;
auto rand = random::RandomArrayGenerator(kRandomSeed);
for (size_t i = 3; i < 10; i++) {
const int64_t length = static_cast<int64_t>(1ULL << i);
auto array = checked_pointer_cast<ArrayType>(
rand.Numeric<TypeParam>(length, 0, 100, /*null_probability=*/0.0));
CType c_fifty = 50, c_hundred = 100;
auto fifty = std::make_shared<ScalarType>(c_fifty);
auto hundred = std::make_shared<ScalarType>(c_hundred);
ASSERT_OK_AND_ASSIGN(Datum greater_than_fifty,
Compare(array, Datum(fifty), CompareOptions(GREATER)));
ASSERT_OK_AND_ASSIGN(Datum less_than_hundred,
Compare(array, Datum(hundred), CompareOptions(LESS)));
ASSERT_OK_AND_ASSIGN(Datum selection, And(greater_than_fifty, less_than_hundred));
ASSERT_OK_AND_ASSIGN(Datum filtered, Filter(array, selection));
auto filtered_array = filtered.make_array();
ASSERT_OK(filtered_array->ValidateFull());
auto expected = CompareAndFilter<TypeParam>(
array->raw_values(), array->length(),
[&](CType e) { return (e > c_fifty) && (e < c_hundred); });
ASSERT_ARRAYS_EQUAL(*filtered_array, *expected);
}
}
TEST(TestFilterKernel, NoValidityBitmapButUnknownNullCount) {
auto values = ArrayFromJSON(int32(), "[1, 2, 3, 4]");
auto filter = ArrayFromJSON(boolean(), "[true, true, false, true]");
auto expected = (*Filter(values, filter)).make_array();
filter->data()->null_count = kUnknownNullCount;
auto result = (*Filter(values, filter)).make_array();
AssertArraysEqual(*expected, *result);
}
template <typename TypeClass>
class TestFilterKernelWithString : public TestFilterKernel<TypeClass> {
protected:
std::shared_ptr<DataType> value_type() {
return TypeTraits<TypeClass>::type_singleton();
}
void AssertFilter(const std::string& values, const std::string& filter,
const std::string& expected) {
TestFilterKernel<TypeClass>::AssertFilter(ArrayFromJSON(value_type(), values),
ArrayFromJSON(boolean(), filter),
ArrayFromJSON(value_type(), expected));
}
void AssertFilterDictionary(const std::string& dictionary_values,
const std::string& dictionary_filter,
const std::string& filter,
const std::string& expected_filter) {
auto dict = ArrayFromJSON(value_type(), dictionary_values);
auto type = dictionary(int8(), value_type());
ASSERT_OK_AND_ASSIGN(auto values,
DictionaryArray::FromArrays(
type, ArrayFromJSON(int8(), dictionary_filter), dict));
ASSERT_OK_AND_ASSIGN(
auto expected,
DictionaryArray::FromArrays(type, ArrayFromJSON(int8(), expected_filter), dict));
auto take_filter = ArrayFromJSON(boolean(), filter);
TestFilterKernel<TypeClass>::AssertFilter(values, take_filter, expected);
}
};
TYPED_TEST_SUITE(TestFilterKernelWithString, BinaryTypes);
TYPED_TEST(TestFilterKernelWithString, FilterString) {
this->AssertFilter(R"(["a", "b", "c"])", "[0, 1, 0]", R"(["b"])");
this->AssertFilter(R"([null, "b", "c"])", "[0, 1, 0]", R"(["b"])");
this->AssertFilter(R"(["a", "b", "c"])", "[null, 1, 0]", R"([null, "b"])");
}
TYPED_TEST(TestFilterKernelWithString, FilterDictionary) {
auto dict = R"(["a", "b", "c", "d", "e"])";
this->AssertFilterDictionary(dict, "[3, 4, 2]", "[0, 1, 0]", "[4]");
this->AssertFilterDictionary(dict, "[null, 4, 2]", "[0, 1, 0]", "[4]");
this->AssertFilterDictionary(dict, "[3, 4, 2]", "[null, 1, 0]", "[null, 4]");
}
class TestFilterKernelWithList : public TestFilterKernel<ListType> {
public:
};
TEST_F(TestFilterKernelWithList, FilterListInt32) {
std::string list_json = "[[], [1,2], null, [3]]";
this->AssertFilter(list(int32()), list_json, "[0, 0, 0, 0]", "[]");
this->AssertFilter(list(int32()), list_json, "[0, 1, 1, null]", "[[1,2], null, null]");
this->AssertFilter(list(int32()), list_json, "[0, 0, 1, null]", "[null, null]");
this->AssertFilter(list(int32()), list_json, "[1, 0, 0, 1]", "[[], [3]]");
this->AssertFilter(list(int32()), list_json, "[1, 1, 1, 1]", list_json);
this->AssertFilter(list(int32()), list_json, "[0, 1, 0, 1]", "[[1,2], [3]]");
}
TEST_F(TestFilterKernelWithList, FilterListListInt32) {
std::string list_json = R"([
[],
[[1], [2, null, 2], []],
null,
[[3, null], null]
])";
auto type = list(list(int32()));
this->AssertFilter(type, list_json, "[0, 0, 0, 0]", "[]");
this->AssertFilter(type, list_json, "[0, 1, 1, null]", R"([
[[1], [2, null, 2], []],
null,
null
])");
this->AssertFilter(type, list_json, "[0, 0, 1, null]", "[null, null]");
this->AssertFilter(type, list_json, "[1, 0, 0, 1]", R"([
[],
[[3, null], null]
])");
this->AssertFilter(type, list_json, "[1, 1, 1, 1]", list_json);
this->AssertFilter(type, list_json, "[0, 1, 0, 1]", R"([
[[1], [2, null, 2], []],
[[3, null], null]
])");
}
class TestFilterKernelWithLargeList : public TestFilterKernel<LargeListType> {};
TEST_F(TestFilterKernelWithLargeList, FilterListInt32) {
std::string list_json = "[[], [1,2], null, [3]]";
this->AssertFilter(large_list(int32()), list_json, "[0, 0, 0, 0]", "[]");
this->AssertFilter(large_list(int32()), list_json, "[0, 1, 1, null]",
"[[1,2], null, null]");
}
class TestFilterKernelWithFixedSizeList : public TestFilterKernel<FixedSizeListType> {};
TEST_F(TestFilterKernelWithFixedSizeList, FilterFixedSizeListInt32) {
std::string list_json = "[null, [1, null, 3], [4, 5, 6], [7, 8, null]]";
this->AssertFilter(fixed_size_list(int32(), 3), list_json, "[0, 0, 0, 0]", "[]");
this->AssertFilter(fixed_size_list(int32(), 3), list_json, "[0, 1, 1, null]",
"[[1, null, 3], [4, 5, 6], null]");
this->AssertFilter(fixed_size_list(int32(), 3), list_json, "[0, 0, 1, null]",
"[[4, 5, 6], null]");
this->AssertFilter(fixed_size_list(int32(), 3), list_json, "[1, 1, 1, 1]", list_json);
this->AssertFilter(fixed_size_list(int32(), 3), list_json, "[0, 1, 0, 1]",
"[[1, null, 3], [7, 8, null]]");
}
class TestFilterKernelWithMap : public TestFilterKernel<MapType> {};
TEST_F(TestFilterKernelWithMap, FilterMapStringToInt32) {
std::string map_json = R"([
[["joe", 0], ["mark", null]],
null,
[["cap", 8]],
[]
])";
this->AssertFilter(map(utf8(), int32()), map_json, "[0, 0, 0, 0]", "[]");
this->AssertFilter(map(utf8(), int32()), map_json, "[0, 1, 1, null]", R"([
null,
[["cap", 8]],
null
])");
this->AssertFilter(map(utf8(), int32()), map_json, "[1, 1, 1, 1]", map_json);
this->AssertFilter(map(utf8(), int32()), map_json, "[0, 1, 0, 1]", "[null, []]");
}
class TestFilterKernelWithStruct : public TestFilterKernel<StructType> {};
TEST_F(TestFilterKernelWithStruct, FilterStruct) {
auto struct_type = struct_({field("a", int32()), field("b", utf8())});
auto struct_json = R"([
null,
{"a": 1, "b": ""},
{"a": 2, "b": "hello"},
{"a": 4, "b": "eh"}
])";
this->AssertFilter(struct_type, struct_json, "[0, 0, 0, 0]", "[]");
this->AssertFilter(struct_type, struct_json, "[0, 1, 1, null]", R"([
{"a": 1, "b": ""},
{"a": 2, "b": "hello"},
null
])");
this->AssertFilter(struct_type, struct_json, "[1, 1, 1, 1]", struct_json);
this->AssertFilter(struct_type, struct_json, "[1, 0, 1, 0]", R"([
null,
{"a": 2, "b": "hello"}
])");
}
class TestFilterKernelWithUnion : public TestFilterKernel<UnionType> {};
TEST_F(TestFilterKernelWithUnion, DISABLED_FilterUnion) {
for (auto union_ : UnionTypeFactories()) {
auto union_type = union_({field("a", int32()), field("b", utf8())}, {2, 5});
auto union_json = R"([
null,
[2, 222],
[5, "hello"],
[5, "eh"],
null,
[2, 111]
])";
this->AssertFilter(union_type, union_json, "[0, 0, 0, 0, 0, 0]", "[]");
this->AssertFilter(union_type, union_json, "[0, 1, 1, null, 0, 1]", R"([
[2, 222],
[5, "hello"],
null,
[2, 111]
])");
this->AssertFilter(union_type, union_json, "[1, 0, 1, 0, 1, 0]", R"([
null,
[5, "hello"],
null
])");
this->AssertFilter(union_type, union_json, "[1, 1, 1, 1, 1, 1]", union_json);
}
}
class TestFilterKernelWithRecordBatch : public TestFilterKernel<RecordBatch> {
public:
void AssertFilter(const std::shared_ptr<Schema>& schm, const std::string& batch_json,
const std::string& selection, FilterOptions options,
const std::string& expected_batch) {
std::shared_ptr<RecordBatch> actual;
ASSERT_OK(this->DoFilter(schm, batch_json, selection, options, &actual));
ASSERT_OK(actual->ValidateFull());
ASSERT_BATCHES_EQUAL(*RecordBatchFromJSON(schm, expected_batch), *actual);
}
Status DoFilter(const std::shared_ptr<Schema>& schm, const std::string& batch_json,
const std::string& selection, FilterOptions options,
std::shared_ptr<RecordBatch>* out) {
auto batch = RecordBatchFromJSON(schm, batch_json);
ARROW_ASSIGN_OR_RAISE(Datum out_datum,
Filter(batch, ArrayFromJSON(boolean(), selection), options));
*out = out_datum.record_batch();
return Status::OK();
}
};
TEST_F(TestFilterKernelWithRecordBatch, FilterRecordBatch) {
std::vector<std::shared_ptr<Field>> fields = {field("a", int32()), field("b", utf8())};
auto schm = schema(fields);
auto batch_json = R"([
{"a": null, "b": "yo"},
{"a": 1, "b": ""},
{"a": 2, "b": "hello"},
{"a": 4, "b": "eh"}
])";
for (auto options : {this->emit_null_, this->drop_}) {
this->AssertFilter(schm, batch_json, "[0, 0, 0, 0]", options, "[]");
this->AssertFilter(schm, batch_json, "[1, 1, 1, 1]", options, batch_json);
this->AssertFilter(schm, batch_json, "[1, 0, 1, 0]", options, R"([
{"a": null, "b": "yo"},
{"a": 2, "b": "hello"}
])");
}
this->AssertFilter(schm, batch_json, "[0, 1, 1, null]", this->drop_, R"([
{"a": 1, "b": ""},
{"a": 2, "b": "hello"}
])");
this->AssertFilter(schm, batch_json, "[0, 1, 1, null]", this->emit_null_, R"([
{"a": 1, "b": ""},
{"a": 2, "b": "hello"},
{"a": null, "b": null}
])");
}
class TestFilterKernelWithChunkedArray : public TestFilterKernel<ChunkedArray> {
public:
void AssertFilter(const std::shared_ptr<DataType>& type,
const std::vector<std::string>& values, const std::string& filter,
const std::vector<std::string>& expected) {
std::shared_ptr<ChunkedArray> actual;
ASSERT_OK(this->FilterWithArray(type, values, filter, &actual));
ASSERT_OK(actual->ValidateFull());
AssertChunkedEqual(*ChunkedArrayFromJSON(type, expected), *actual);
}
void AssertChunkedFilter(const std::shared_ptr<DataType>& type,
const std::vector<std::string>& values,
const std::vector<std::string>& filter,
const std::vector<std::string>& expected) {
std::shared_ptr<ChunkedArray> actual;
ASSERT_OK(this->FilterWithChunkedArray(type, values, filter, &actual));
ASSERT_OK(actual->ValidateFull());
AssertChunkedEqual(*ChunkedArrayFromJSON(type, expected), *actual);
}
Status FilterWithArray(const std::shared_ptr<DataType>& type,
const std::vector<std::string>& values,
const std::string& filter, std::shared_ptr<ChunkedArray>* out) {
ARROW_ASSIGN_OR_RAISE(Datum out_datum, Filter(ChunkedArrayFromJSON(type, values),
ArrayFromJSON(boolean(), filter)));
*out = out_datum.chunked_array();
return Status::OK();
}
Status FilterWithChunkedArray(const std::shared_ptr<DataType>& type,
const std::vector<std::string>& values,
const std::vector<std::string>& filter,
std::shared_ptr<ChunkedArray>* out) {
ARROW_ASSIGN_OR_RAISE(Datum out_datum,
Filter(ChunkedArrayFromJSON(type, values),
ChunkedArrayFromJSON(boolean(), filter)));
*out = out_datum.chunked_array();
return Status::OK();
}
};
TEST_F(TestFilterKernelWithChunkedArray, FilterChunkedArray) {
this->AssertFilter(int8(), {"[]"}, "[]", {});
this->AssertChunkedFilter(int8(), {"[]"}, {"[]"}, {});
this->AssertFilter(int8(), {"[7]", "[8, 9]"}, "[0, 1, 0]", {"[8]"});
this->AssertChunkedFilter(int8(), {"[7]", "[8, 9]"}, {"[0]", "[1, 0]"}, {"[8]"});
this->AssertChunkedFilter(int8(), {"[7]", "[8, 9]"}, {"[0, 1]", "[0]"}, {"[8]"});
std::shared_ptr<ChunkedArray> arr;
ASSERT_RAISES(
Invalid, this->FilterWithArray(int8(), {"[7]", "[8, 9]"}, "[0, 1, 0, 1, 1]", &arr));
ASSERT_RAISES(Invalid, this->FilterWithChunkedArray(int8(), {"[7]", "[8, 9]"},
{"[0, 1, 0]", "[1, 1]"}, &arr));
}
class TestFilterKernelWithTable : public TestFilterKernel<Table> {
public:
void AssertFilter(const std::shared_ptr<Schema>& schm,
const std::vector<std::string>& table_json, const std::string& filter,
FilterOptions options,
const std::vector<std::string>& expected_table) {
std::shared_ptr<Table> actual;
ASSERT_OK(this->FilterWithArray(schm, table_json, filter, options, &actual));
ASSERT_OK(actual->ValidateFull());
ASSERT_TABLES_EQUAL(*TableFromJSON(schm, expected_table), *actual);
}
void AssertChunkedFilter(const std::shared_ptr<Schema>& schm,
const std::vector<std::string>& table_json,
const std::vector<std::string>& filter, FilterOptions options,
const std::vector<std::string>& expected_table) {
std::shared_ptr<Table> actual;
ASSERT_OK(this->FilterWithChunkedArray(schm, table_json, filter, options, &actual));
ASSERT_OK(actual->ValidateFull());
AssertTablesEqual(*TableFromJSON(schm, expected_table), *actual,
/*same_chunk_layout=*/false);
}
Status FilterWithArray(const std::shared_ptr<Schema>& schm,
const std::vector<std::string>& values,
const std::string& filter, FilterOptions options,
std::shared_ptr<Table>* out) {
ARROW_ASSIGN_OR_RAISE(
Datum out_datum,
Filter(TableFromJSON(schm, values), ArrayFromJSON(boolean(), filter), options));
*out = out_datum.table();
return Status::OK();
}
Status FilterWithChunkedArray(const std::shared_ptr<Schema>& schm,
const std::vector<std::string>& values,
const std::vector<std::string>& filter,
FilterOptions options, std::shared_ptr<Table>* out) {
ARROW_ASSIGN_OR_RAISE(Datum out_datum,
Filter(TableFromJSON(schm, values),
ChunkedArrayFromJSON(boolean(), filter), options));
*out = out_datum.table();
return Status::OK();
}
};
TEST_F(TestFilterKernelWithTable, FilterTable) {
std::vector<std::shared_ptr<Field>> fields = {field("a", int32()), field("b", utf8())};
auto schm = schema(fields);
std::vector<std::string> table_json = {R"([
{"a": null, "b": "yo"},
{"a": 1, "b": ""}
])",
R"([
{"a": 2, "b": "hello"},
{"a": 4, "b": "eh"}
])"};
for (auto options : {this->emit_null_, this->drop_}) {
this->AssertFilter(schm, table_json, "[0, 0, 0, 0]", options, {});
this->AssertChunkedFilter(schm, table_json, {"[0]", "[0, 0, 0]"}, options, {});
this->AssertFilter(schm, table_json, "[1, 1, 1, 1]", options, table_json);
this->AssertChunkedFilter(schm, table_json, {"[1]", "[1, 1, 1]"}, options,
table_json);
}
std::vector<std::string> expected_emit_null = {R"([
{"a": 1, "b": ""}
])",
R"([
{"a": 2, "b": "hello"},
{"a": null, "b": null}
])"};
this->AssertFilter(schm, table_json, "[0, 1, 1, null]", this->emit_null_,
expected_emit_null);
this->AssertChunkedFilter(schm, table_json, {"[0, 1, 1]", "[null]"}, this->emit_null_,
expected_emit_null);
std::vector<std::string> expected_drop = {R"([{"a": 1, "b": ""}])",
R"([{"a": 2, "b": "hello"}])"};
this->AssertFilter(schm, table_json, "[0, 1, 1, null]", this->drop_, expected_drop);
this->AssertChunkedFilter(schm, table_json, {"[0, 1, 1]", "[null]"}, this->drop_,
expected_drop);
}
TEST(TestFilterMetaFunction, ArityChecking) {
ASSERT_RAISES(Invalid, CallFunction("filter", {}));
}
// ----------------------------------------------------------------------
// Take tests
void AssertTakeArrays(const std::shared_ptr<Array>& values,
const std::shared_ptr<Array>& indices,
const std::shared_ptr<Array>& expected) {
ASSERT_OK_AND_ASSIGN(std::shared_ptr<Array> actual, Take(*values, *indices));
ASSERT_OK(actual->ValidateFull());
AssertArraysEqual(*expected, *actual, /*verbose=*/true);
}
Status TakeJSON(const std::shared_ptr<DataType>& type, const std::string& values,
const std::shared_ptr<DataType>& index_type, const std::string& indices,
std::shared_ptr<Array>* out) {
return Take(*ArrayFromJSON(type, values), *ArrayFromJSON(index_type, indices))
.Value(out);
}
void CheckTake(const std::shared_ptr<DataType>& type, const std::string& values,
const std::string& indices, const std::string& expected) {
std::shared_ptr<Array> actual;
for (auto index_type : {int8(), uint32()}) {
ASSERT_OK(TakeJSON(type, values, index_type, indices, &actual));
ASSERT_OK(actual->ValidateFull());
AssertArraysEqual(*ArrayFromJSON(type, expected), *actual, /*verbose=*/true);
}
}
void AssertTakeNull(const std::string& values, const std::string& indices,
const std::string& expected) {
CheckTake(null(), values, indices, expected);
}
void AssertTakeBoolean(const std::string& values, const std::string& indices,
const std::string& expected) {
CheckTake(boolean(), values, indices, expected);
}
template <typename ValuesType, typename IndexType>
void ValidateTakeImpl(const std::shared_ptr<Array>& values,
const std::shared_ptr<Array>& indices,
const std::shared_ptr<Array>& result) {
using ValuesArrayType = typename TypeTraits<ValuesType>::ArrayType;
using IndexArrayType = typename TypeTraits<IndexType>::ArrayType;
auto typed_values = checked_pointer_cast<ValuesArrayType>(values);
auto typed_result = checked_pointer_cast<ValuesArrayType>(result);
auto typed_indices = checked_pointer_cast<IndexArrayType>(indices);
for (int64_t i = 0; i < indices->length(); ++i) {
if (typed_indices->IsNull(i) || typed_values->IsNull(typed_indices->Value(i))) {
ASSERT_TRUE(result->IsNull(i)) << i;
} else {
ASSERT_FALSE(result->IsNull(i)) << i;
ASSERT_EQ(typed_result->GetView(i), typed_values->GetView(typed_indices->Value(i)))
<< i;
}
}
}
template <typename ValuesType>
void ValidateTake(const std::shared_ptr<Array>& values,
const std::shared_ptr<Array>& indices) {
ASSERT_OK_AND_ASSIGN(Datum out, Take(values, indices));
auto taken = out.make_array();
ASSERT_OK(taken->ValidateFull());
ASSERT_EQ(indices->length(), taken->length());
switch (indices->type_id()) {
case Type::INT8:
ValidateTakeImpl<ValuesType, Int8Type>(values, indices, taken);
break;
case Type::INT16:
ValidateTakeImpl<ValuesType, Int16Type>(values, indices, taken);
break;
case Type::INT32:
ValidateTakeImpl<ValuesType, Int32Type>(values, indices, taken);
break;
case Type::INT64:
ValidateTakeImpl<ValuesType, Int64Type>(values, indices, taken);
break;
case Type::UINT8:
ValidateTakeImpl<ValuesType, UInt8Type>(values, indices, taken);
break;
case Type::UINT16:
ValidateTakeImpl<ValuesType, UInt16Type>(values, indices, taken);
break;
case Type::UINT32:
ValidateTakeImpl<ValuesType, UInt32Type>(values, indices, taken);
break;
case Type::UINT64:
ValidateTakeImpl<ValuesType, UInt64Type>(values, indices, taken);
break;
default:
FAIL() << "Invalid index type";
break;
}
}
template <typename T>
T GetMaxIndex(int64_t values_length) {
int64_t max_index = values_length - 1;
if (max_index > static_cast<int64_t>(std::numeric_limits<T>::max())) {
max_index = std::numeric_limits<T>::max();
}
return static_cast<T>(max_index);
}
template <>
uint64_t GetMaxIndex(int64_t values_length) {
return static_cast<uint64_t>(values_length - 1);
}
template <typename ArrowType>
class TestTakeKernel : public ::testing::Test {};
TEST(TestTakeKernel, TakeNull) {
AssertTakeNull("[null, null, null]", "[0, 1, 0]", "[null, null, null]");
AssertTakeNull("[null, null, null]", "[0, 2]", "[null, null]");
std::shared_ptr<Array> arr;
ASSERT_RAISES(IndexError,
TakeJSON(null(), "[null, null, null]", int8(), "[0, 9, 0]", &arr));
ASSERT_RAISES(IndexError,
TakeJSON(boolean(), "[null, null, null]", int8(), "[0, -1, 0]", &arr));
}
TEST(TestTakeKernel, InvalidIndexType) {
std::shared_ptr<Array> arr;
ASSERT_RAISES(NotImplemented, TakeJSON(null(), "[null, null, null]", float32(),
"[0.0, 1.0, 0.1]", &arr));
}
TEST(TestTakeKernel, DefaultOptions) {
auto indices = ArrayFromJSON(int8(), "[null, 2, 0, 3]");
auto values = ArrayFromJSON(int8(), "[7, 8, 9, null]");
ASSERT_OK_AND_ASSIGN(auto no_options_provided, CallFunction("take", {values, indices}));
auto default_options = TakeOptions::Defaults();
ASSERT_OK_AND_ASSIGN(auto explicit_defaults,
CallFunction("take", {values, indices}, &default_options));
AssertDatumsEqual(explicit_defaults, no_options_provided);
}
TEST(TestTakeKernel, TakeBoolean) {
AssertTakeBoolean("[7, 8, 9]", "[]", "[]");
AssertTakeBoolean("[true, false, true]", "[0, 1, 0]", "[true, false, true]");
AssertTakeBoolean("[null, false, true]", "[0, 1, 0]", "[null, false, null]");
AssertTakeBoolean("[true, false, true]", "[null, 1, 0]", "[null, false, true]");
std::shared_ptr<Array> arr;
ASSERT_RAISES(IndexError,
TakeJSON(boolean(), "[true, false, true]", int8(), "[0, 9, 0]", &arr));
ASSERT_RAISES(IndexError,
TakeJSON(boolean(), "[true, false, true]", int8(), "[0, -1, 0]", &arr));
}
template <typename ArrowType>
class TestTakeKernelWithNumeric : public TestTakeKernel<ArrowType> {
protected:
void AssertTake(const std::string& values, const std::string& indices,
const std::string& expected) {
CheckTake(type_singleton(), values, indices, expected);
}
std::shared_ptr<DataType> type_singleton() {
return TypeTraits<ArrowType>::type_singleton();
}
};
TYPED_TEST_SUITE(TestTakeKernelWithNumeric, NumericArrowTypes);
TYPED_TEST(TestTakeKernelWithNumeric, TakeNumeric) {
this->AssertTake("[7, 8, 9]", "[]", "[]");
this->AssertTake("[7, 8, 9]", "[0, 1, 0]", "[7, 8, 7]");
this->AssertTake("[null, 8, 9]", "[0, 1, 0]", "[null, 8, null]");
this->AssertTake("[7, 8, 9]", "[null, 1, 0]", "[null, 8, 7]");
this->AssertTake("[null, 8, 9]", "[]", "[]");
this->AssertTake("[7, 8, 9]", "[0, 0, 0, 0, 0, 0, 2]", "[7, 7, 7, 7, 7, 7, 9]");
std::shared_ptr<Array> arr;
ASSERT_RAISES(IndexError,
TakeJSON(this->type_singleton(), "[7, 8, 9]", int8(), "[0, 9, 0]", &arr));
ASSERT_RAISES(IndexError, TakeJSON(this->type_singleton(), "[7, 8, 9]", int8(),
"[0, -1, 0]", &arr));
}
template <typename TypeClass>
class TestTakeKernelWithString : public TestTakeKernel<TypeClass> {
public:
std::shared_ptr<DataType> value_type() {
return TypeTraits<TypeClass>::type_singleton();
}
void AssertTake(const std::string& values, const std::string& indices,
const std::string& expected) {
CheckTake(value_type(), values, indices, expected);
}
void AssertTakeDictionary(const std::string& dictionary_values,
const std::string& dictionary_indices,
const std::string& indices,
const std::string& expected_indices) {
auto dict = ArrayFromJSON(value_type(), dictionary_values);
auto type = dictionary(int8(), value_type());
ASSERT_OK_AND_ASSIGN(auto values,
DictionaryArray::FromArrays(
type, ArrayFromJSON(int8(), dictionary_indices), dict));
ASSERT_OK_AND_ASSIGN(
auto expected,
DictionaryArray::FromArrays(type, ArrayFromJSON(int8(), expected_indices), dict));
auto take_indices = ArrayFromJSON(int8(), indices);
AssertTakeArrays(values, take_indices, expected);
}
};
TYPED_TEST_SUITE(TestTakeKernelWithString, BinaryTypes);
TYPED_TEST(TestTakeKernelWithString, TakeString) {
this->AssertTake(R"(["a", "b", "c"])", "[0, 1, 0]", R"(["a", "b", "a"])");
this->AssertTake(R"([null, "b", "c"])", "[0, 1, 0]", "[null, \"b\", null]");
this->AssertTake(R"(["a", "b", "c"])", "[null, 1, 0]", R"([null, "b", "a"])");
std::shared_ptr<DataType> type = this->value_type();
std::shared_ptr<Array> arr;
ASSERT_RAISES(IndexError,
TakeJSON(type, R"(["a", "b", "c"])", int8(), "[0, 9, 0]", &arr));
ASSERT_RAISES(IndexError, TakeJSON(type, R"(["a", "b", null, "ddd", "ee"])", int64(),
"[2, 5]", &arr));
}
TYPED_TEST(TestTakeKernelWithString, TakeDictionary) {
auto dict = R"(["a", "b", "c", "d", "e"])";
this->AssertTakeDictionary(dict, "[3, 4, 2]", "[0, 1, 0]", "[3, 4, 3]");
this->AssertTakeDictionary(dict, "[null, 4, 2]", "[0, 1, 0]", "[null, 4, null]");
this->AssertTakeDictionary(dict, "[3, 4, 2]", "[null, 1, 0]", "[null, 4, 3]");
}
class TestTakeKernelFSB : public TestTakeKernel<FixedSizeBinaryType> {
public:
std::shared_ptr<DataType> value_type() { return fixed_size_binary(3); }
void AssertTake(const std::string& values, const std::string& indices,
const std::string& expected) {
CheckTake(value_type(), values, indices, expected);
}
};
TEST_F(TestTakeKernelFSB, TakeFixedSizeBinary) {
this->AssertTake(R"(["aaa", "bbb", "ccc"])", "[0, 1, 0]", R"(["aaa", "bbb", "aaa"])");
this->AssertTake(R"([null, "bbb", "ccc"])", "[0, 1, 0]", "[null, \"bbb\", null]");
this->AssertTake(R"(["aaa", "bbb", "ccc"])", "[null, 1, 0]", R"([null, "bbb", "aaa"])");
std::shared_ptr<DataType> type = this->value_type();
std::shared_ptr<Array> arr;
ASSERT_RAISES(IndexError,
TakeJSON(type, R"(["aaa", "bbb", "ccc"])", int8(), "[0, 9, 0]", &arr));
ASSERT_RAISES(IndexError, TakeJSON(type, R"(["aaa", "bbb", null, "ddd", "eee"])",
int64(), "[2, 5]", &arr));
}
class TestTakeKernelWithList : public TestTakeKernel<ListType> {};
TEST_F(TestTakeKernelWithList, TakeListInt32) {
std::string list_json = "[[], [1,2], null, [3]]";
CheckTake(list(int32()), list_json, "[]", "[]");
CheckTake(list(int32()), list_json, "[3, 2, 1]", "[[3], null, [1,2]]");
CheckTake(list(int32()), list_json, "[null, 3, 0]", "[null, [3], []]");
CheckTake(list(int32()), list_json, "[null, null]", "[null, null]");
CheckTake(list(int32()), list_json, "[3, 0, 0, 3]", "[[3], [], [], [3]]");
CheckTake(list(int32()), list_json, "[0, 1, 2, 3]", list_json);
CheckTake(list(int32()), list_json, "[0, 0, 0, 0, 0, 0, 1]",
"[[], [], [], [], [], [], [1, 2]]");
}
TEST_F(TestTakeKernelWithList, TakeListListInt32) {
std::string list_json = R"([
[],
[[1], [2, null, 2], []],
null,
[[3, null], null]
])";
auto type = list(list(int32()));
CheckTake(type, list_json, "[]", "[]");
CheckTake(type, list_json, "[3, 2, 1]", R"([
[[3, null], null],
null,
[[1], [2, null, 2], []]
])");
CheckTake(type, list_json, "[null, 3, 0]", R"([
null,
[[3, null], null],
[]
])");
CheckTake(type, list_json, "[null, null]", "[null, null]");
CheckTake(type, list_json, "[3, 0, 0, 3]",
"[[[3, null], null], [], [], [[3, null], null]]");
CheckTake(type, list_json, "[0, 1, 2, 3]", list_json);
CheckTake(type, list_json, "[0, 0, 0, 0, 0, 0, 1]",
"[[], [], [], [], [], [], [[1], [2, null, 2], []]]");
}
class TestTakeKernelWithLargeList : public TestTakeKernel<LargeListType> {};
TEST_F(TestTakeKernelWithLargeList, TakeLargeListInt32) {
std::string list_json = "[[], [1,2], null, [3]]";
CheckTake(large_list(int32()), list_json, "[]", "[]");
CheckTake(large_list(int32()), list_json, "[null, 1, 2, 0]", "[null, [1,2], null, []]");
}
class TestTakeKernelWithFixedSizeList : public TestTakeKernel<FixedSizeListType> {};
TEST_F(TestTakeKernelWithFixedSizeList, TakeFixedSizeListInt32) {
std::string list_json = "[null, [1, null, 3], [4, 5, 6], [7, 8, null]]";
CheckTake(fixed_size_list(int32(), 3), list_json, "[]", "[]");
CheckTake(fixed_size_list(int32(), 3), list_json, "[3, 2, 1]",
"[[7, 8, null], [4, 5, 6], [1, null, 3]]");
CheckTake(fixed_size_list(int32(), 3), list_json, "[null, 2, 0]",
"[null, [4, 5, 6], null]");
CheckTake(fixed_size_list(int32(), 3), list_json, "[null, null]", "[null, null]");
CheckTake(fixed_size_list(int32(), 3), list_json, "[3, 0, 0, 3]",
"[[7, 8, null], null, null, [7, 8, null]]");
CheckTake(fixed_size_list(int32(), 3), list_json, "[0, 1, 2, 3]", list_json);
CheckTake(
fixed_size_list(int32(), 3), list_json, "[2, 2, 2, 2, 2, 2, 1]",
"[[4, 5, 6], [4, 5, 6], [4, 5, 6], [4, 5, 6], [4, 5, 6], [4, 5, 6], [1, null, 3]]");
}
class TestTakeKernelWithMap : public TestTakeKernel<MapType> {};
TEST_F(TestTakeKernelWithMap, TakeMapStringToInt32) {
std::string map_json = R"([
[["joe", 0], ["mark", null]],
null,
[["cap", 8]],
[]
])";
CheckTake(map(utf8(), int32()), map_json, "[]", "[]");
CheckTake(map(utf8(), int32()), map_json, "[3, 1, 3, 1, 3]",
"[[], null, [], null, []]");
CheckTake(map(utf8(), int32()), map_json, "[2, 1, null]", R"([
[["cap", 8]],
null,
null
])");
CheckTake(map(utf8(), int32()), map_json, "[2, 1, 0]", R"([
[["cap", 8]],
null,
[["joe", 0], ["mark", null]]
])");
CheckTake(map(utf8(), int32()), map_json, "[0, 1, 2, 3]", map_json);
CheckTake(map(utf8(), int32()), map_json, "[0, 0, 0, 0, 0, 0, 3]", R"([
[["joe", 0], ["mark", null]],
[["joe", 0], ["mark", null]],
[["joe", 0], ["mark", null]],
[["joe", 0], ["mark", null]],
[["joe", 0], ["mark", null]],
[["joe", 0], ["mark", null]],
[]
])");
}
class TestTakeKernelWithStruct : public TestTakeKernel<StructType> {};
TEST_F(TestTakeKernelWithStruct, TakeStruct) {
auto struct_type = struct_({field("a", int32()), field("b", utf8())});
auto struct_json = R"([
null,
{"a": 1, "b": ""},
{"a": 2, "b": "hello"},
{"a": 4, "b": "eh"}
])";
CheckTake(struct_type, struct_json, "[]", "[]");
CheckTake(struct_type, struct_json, "[3, 1, 3, 1, 3]", R"([
{"a": 4, "b": "eh"},
{"a": 1, "b": ""},
{"a": 4, "b": "eh"},
{"a": 1, "b": ""},
{"a": 4, "b": "eh"}
])");
CheckTake(struct_type, struct_json, "[3, 1, 0]", R"([
{"a": 4, "b": "eh"},
{"a": 1, "b": ""},
null
])");
CheckTake(struct_type, struct_json, "[0, 1, 2, 3]", struct_json);
CheckTake(struct_type, struct_json, "[0, 2, 2, 2, 2, 2, 2]", R"([
null,
{"a": 2, "b": "hello"},
{"a": 2, "b": "hello"},
{"a": 2, "b": "hello"},
{"a": 2, "b": "hello"},
{"a": 2, "b": "hello"},
{"a": 2, "b": "hello"}
])");
}
class TestTakeKernelWithUnion : public TestTakeKernel<UnionType> {};
// TODO: Restore Union take functionality
TEST_F(TestTakeKernelWithUnion, DISABLED_TakeUnion) {
for (auto union_ : UnionTypeFactories()) {
auto union_type = union_({field("a", int32()), field("b", utf8())}, {2, 5});
auto union_json = R"([
null,
[2, 222],
[5, "hello"],
[5, "eh"],
null,
[2, 111]
])";
CheckTake(union_type, union_json, "[]", "[]");
CheckTake(union_type, union_json, "[3, 1, 3, 1, 3]", R"([
[5, "eh"],
[2, 222],
[5, "eh"],
[2, 222],
[5, "eh"]
])");
CheckTake(union_type, union_json, "[4, 2, 1]", R"([
null,
[5, "hello"],
[2, 222]
])");
CheckTake(union_type, union_json, "[0, 1, 2, 3, 4, 5]", union_json);
CheckTake(union_type, union_json, "[0, 2, 2, 2, 2, 2, 2]", R"([
null,
[5, "hello"],
[5, "hello"],
[5, "hello"],
[5, "hello"],
[5, "hello"],
[5, "hello"]
])");
}
}
class TestPermutationsWithTake : public TestBase {
protected:
void DoTake(const Int16Array& values, const Int16Array& indices,
std::shared_ptr<Int16Array>* out) {
ASSERT_OK_AND_ASSIGN(std::shared_ptr<Array> boxed_out, Take(values, indices));
ASSERT_OK(boxed_out->ValidateFull());
*out = checked_pointer_cast<Int16Array>(std::move(boxed_out));
}
std::shared_ptr<Int16Array> DoTake(const Int16Array& values,
const Int16Array& indices) {
std::shared_ptr<Int16Array> out;
DoTake(values, indices, &out);
return out;
}
std::shared_ptr<Int16Array> DoTakeN(uint64_t n, std::shared_ptr<Int16Array> array) {
auto power_of_2 = array;
array = Identity(array->length());
while (n != 0) {
if (n & 1) {
array = DoTake(*array, *power_of_2);
}
power_of_2 = DoTake(*power_of_2, *power_of_2);
n >>= 1;
}
return array;
}
template <typename Rng>
void Shuffle(const Int16Array& array, Rng& gen, std::shared_ptr<Int16Array>* shuffled) {
auto byte_length = array.length() * sizeof(int16_t);
ASSERT_OK_AND_ASSIGN(auto data, array.values()->CopySlice(0, byte_length));
auto mutable_data = reinterpret_cast<int16_t*>(data->mutable_data());
std::shuffle(mutable_data, mutable_data + array.length(), gen);
shuffled->reset(new Int16Array(array.length(), data));
}
template <typename Rng>
std::shared_ptr<Int16Array> Shuffle(const Int16Array& array, Rng& gen) {
std::shared_ptr<Int16Array> out;
Shuffle(array, gen, &out);
return out;
}
void Identity(int64_t length, std::shared_ptr<Int16Array>* identity) {
Int16Builder identity_builder;
ASSERT_OK(identity_builder.Resize(length));
for (int16_t i = 0; i < length; ++i) {
identity_builder.UnsafeAppend(i);
}
ASSERT_OK(identity_builder.Finish(identity));
}
std::shared_ptr<Int16Array> Identity(int64_t length) {
std::shared_ptr<Int16Array> out;
Identity(length, &out);
return out;
}
std::shared_ptr<Int16Array> Inverse(const std::shared_ptr<Int16Array>& permutation) {
auto length = static_cast<int16_t>(permutation->length());
std::vector<bool> cycle_lengths(length + 1, false);
auto permutation_to_the_i = permutation;
for (int16_t cycle_length = 1; cycle_length <= length; ++cycle_length) {
cycle_lengths[cycle_length] = HasTrivialCycle(*permutation_to_the_i);
permutation_to_the_i = DoTake(*permutation, *permutation_to_the_i);
}
uint64_t cycle_to_identity_length = 1;
for (int16_t cycle_length = length; cycle_length > 1; --cycle_length) {
if (!cycle_lengths[cycle_length]) {
continue;
}
if (cycle_to_identity_length % cycle_length == 0) {
continue;
}
if (cycle_to_identity_length >
std::numeric_limits<uint64_t>::max() / cycle_length) {
// overflow, can't compute Inverse
return nullptr;
}
cycle_to_identity_length *= cycle_length;
}
return DoTakeN(cycle_to_identity_length - 1, permutation);
}
bool HasTrivialCycle(const Int16Array& permutation) {
for (int64_t i = 0; i < permutation.length(); ++i) {
if (permutation.Value(i) == static_cast<int16_t>(i)) {
return true;
}
}
return false;
}
};
TEST_F(TestPermutationsWithTake, InvertPermutation) {
for (auto seed : std::vector<random::SeedType>({0, kRandomSeed, kRandomSeed * 2 - 1})) {
std::default_random_engine gen(seed);
for (int16_t length = 0; length < 1 << 10; ++length) {
auto identity = Identity(length);
auto permutation = Shuffle(*identity, gen);
auto inverse = Inverse(permutation);
if (inverse == nullptr) {
break;
}
ASSERT_TRUE(DoTake(*inverse, *permutation)->Equals(identity));
}
}
}
class TestTakeKernelWithRecordBatch : public TestTakeKernel<RecordBatch> {
public:
void AssertTake(const std::shared_ptr<Schema>& schm, const std::string& batch_json,
const std::string& indices, const std::string& expected_batch) {
std::shared_ptr<RecordBatch> actual;
for (auto index_type : {int8(), uint32()}) {
ASSERT_OK(TakeJSON(schm, batch_json, index_type, indices, &actual));
ASSERT_OK(actual->ValidateFull());
ASSERT_BATCHES_EQUAL(*RecordBatchFromJSON(schm, expected_batch), *actual);
}
}
Status TakeJSON(const std::shared_ptr<Schema>& schm, const std::string& batch_json,
const std::shared_ptr<DataType>& index_type, const std::string& indices,
std::shared_ptr<RecordBatch>* out) {
auto batch = RecordBatchFromJSON(schm, batch_json);
ARROW_ASSIGN_OR_RAISE(Datum result,
Take(Datum(batch), Datum(ArrayFromJSON(index_type, indices))));
*out = result.record_batch();
return Status::OK();
}
};
TEST_F(TestTakeKernelWithRecordBatch, TakeRecordBatch) {
std::vector<std::shared_ptr<Field>> fields = {field("a", int32()), field("b", utf8())};
auto schm = schema(fields);
auto struct_json = R"([
{"a": null, "b": "yo"},
{"a": 1, "b": ""},
{"a": 2, "b": "hello"},
{"a": 4, "b": "eh"}
])";
this->AssertTake(schm, struct_json, "[]", "[]");
this->AssertTake(schm, struct_json, "[3, 1, 3, 1, 3]", R"([
{"a": 4, "b": "eh"},
{"a": 1, "b": ""},
{"a": 4, "b": "eh"},
{"a": 1, "b": ""},
{"a": 4, "b": "eh"}
])");
this->AssertTake(schm, struct_json, "[3, 1, 0]", R"([
{"a": 4, "b": "eh"},
{"a": 1, "b": ""},
{"a": null, "b": "yo"}
])");
this->AssertTake(schm, struct_json, "[0, 1, 2, 3]", struct_json);
this->AssertTake(schm, struct_json, "[0, 2, 2, 2, 2, 2, 2]", R"([
{"a": null, "b": "yo"},
{"a": 2, "b": "hello"},
{"a": 2, "b": "hello"},
{"a": 2, "b": "hello"},
{"a": 2, "b": "hello"},
{"a": 2, "b": "hello"},
{"a": 2, "b": "hello"}
])");
}
class TestTakeKernelWithChunkedArray : public TestTakeKernel<ChunkedArray> {
public:
void AssertTake(const std::shared_ptr<DataType>& type,
const std::vector<std::string>& values, const std::string& indices,
const std::vector<std::string>& expected) {
std::shared_ptr<ChunkedArray> actual;
ASSERT_OK(this->TakeWithArray(type, values, indices, &actual));
ASSERT_OK(actual->ValidateFull());
AssertChunkedEqual(*ChunkedArrayFromJSON(type, expected), *actual);
}
void AssertChunkedTake(const std::shared_ptr<DataType>& type,
const std::vector<std::string>& values,
const std::vector<std::string>& indices,
const std::vector<std::string>& expected) {
std::shared_ptr<ChunkedArray> actual;
ASSERT_OK(this->TakeWithChunkedArray(type, values, indices, &actual));
ASSERT_OK(actual->ValidateFull());
AssertChunkedEqual(*ChunkedArrayFromJSON(type, expected), *actual);
}
Status TakeWithArray(const std::shared_ptr<DataType>& type,
const std::vector<std::string>& values, const std::string& indices,
std::shared_ptr<ChunkedArray>* out) {
ARROW_ASSIGN_OR_RAISE(Datum result, Take(ChunkedArrayFromJSON(type, values),
ArrayFromJSON(int8(), indices)));
*out = result.chunked_array();
return Status::OK();
}
Status TakeWithChunkedArray(const std::shared_ptr<DataType>& type,
const std::vector<std::string>& values,
const std::vector<std::string>& indices,
std::shared_ptr<ChunkedArray>* out) {
ARROW_ASSIGN_OR_RAISE(Datum result, Take(ChunkedArrayFromJSON(type, values),
ChunkedArrayFromJSON(int8(), indices)));
*out = result.chunked_array();
return Status::OK();
}
};
TEST_F(TestTakeKernelWithChunkedArray, TakeChunkedArray) {
this->AssertTake(int8(), {"[]"}, "[]", {"[]"});
this->AssertChunkedTake(int8(), {"[]"}, {"[]"}, {"[]"});
this->AssertTake(int8(), {"[7]", "[8, 9]"}, "[0, 1, 0, 2]", {"[7, 8, 7, 9]"});
this->AssertChunkedTake(int8(), {"[7]", "[8, 9]"}, {"[0, 1, 0]", "[]", "[2]"},
{"[7, 8, 7]", "[]", "[9]"});
this->AssertTake(int8(), {"[7]", "[8, 9]"}, "[2, 1]", {"[9, 8]"});
std::shared_ptr<ChunkedArray> arr;
ASSERT_RAISES(IndexError,
this->TakeWithArray(int8(), {"[7]", "[8, 9]"}, "[0, 5]", &arr));
ASSERT_RAISES(IndexError, this->TakeWithChunkedArray(int8(), {"[7]", "[8, 9]"},
{"[0, 1, 0]", "[5, 1]"}, &arr));
}
class TestTakeKernelWithTable : public TestTakeKernel<Table> {
public:
void AssertTake(const std::shared_ptr<Schema>& schm,
const std::vector<std::string>& table_json, const std::string& filter,
const std::vector<std::string>& expected_table) {
std::shared_ptr<Table> actual;
ASSERT_OK(this->TakeWithArray(schm, table_json, filter, &actual));
ASSERT_OK(actual->ValidateFull());
ASSERT_TABLES_EQUAL(*TableFromJSON(schm, expected_table), *actual);
}
void AssertChunkedTake(const std::shared_ptr<Schema>& schm,
const std::vector<std::string>& table_json,
const std::vector<std::string>& filter,
const std::vector<std::string>& expected_table) {
std::shared_ptr<Table> actual;
ASSERT_OK(this->TakeWithChunkedArray(schm, table_json, filter, &actual));
ASSERT_OK(actual->ValidateFull());
ASSERT_TABLES_EQUAL(*TableFromJSON(schm, expected_table), *actual);
}
Status TakeWithArray(const std::shared_ptr<Schema>& schm,
const std::vector<std::string>& values, const std::string& indices,
std::shared_ptr<Table>* out) {
ARROW_ASSIGN_OR_RAISE(Datum result, Take(Datum(TableFromJSON(schm, values)),
Datum(ArrayFromJSON(int8(), indices))));
*out = result.table();
return Status::OK();
}
Status TakeWithChunkedArray(const std::shared_ptr<Schema>& schm,
const std::vector<std::string>& values,
const std::vector<std::string>& indices,
std::shared_ptr<Table>* out) {
ARROW_ASSIGN_OR_RAISE(Datum result,
Take(Datum(TableFromJSON(schm, values)),
Datum(ChunkedArrayFromJSON(int8(), indices))));
*out = result.table();
return Status::OK();
}
};
TEST_F(TestTakeKernelWithTable, TakeTable) {
std::vector<std::shared_ptr<Field>> fields = {field("a", int32()), field("b", utf8())};
auto schm = schema(fields);
std::vector<std::string> table_json = {
"[{\"a\": null, \"b\": \"yo\"},{\"a\": 1, \"b\": \"\"}]",
"[{\"a\": 2, \"b\": \"hello\"},{\"a\": 4, \"b\": \"eh\"}]"};
this->AssertTake(schm, table_json, "[]", {"[]"});
std::vector<std::string> expected_310 = {
"[{\"a\": 4, \"b\": \"eh\"},{\"a\": 1, \"b\": \"\"},{\"a\": null, \"b\": \"yo\"}]"};
this->AssertTake(schm, table_json, "[3, 1, 0]", expected_310);
this->AssertChunkedTake(schm, table_json, {"[0, 1]", "[2, 3]"}, table_json);
}
TEST(TestTakeMetaFunction, ArityChecking) {
ASSERT_RAISES(Invalid, CallFunction("take", {}));
}
// ----------------------------------------------------------------------
// Random data tests
template <typename Unused = void>
struct FilterRandomTest {
static void Test(const std::shared_ptr<DataType>& type) {
auto rand = random::RandomArrayGenerator(kRandomSeed);
const int64_t length = static_cast<int64_t>(1ULL << 10);
for (auto null_probability : {0.0, 0.01, 0.1, 0.999, 1.0}) {
for (auto true_probability : {0.0, 0.1, 0.999, 1.0}) {
auto values = rand.ArrayOf(type, length, null_probability);
auto filter = rand.Boolean(length + 1, true_probability, null_probability);
auto filter_no_nulls = rand.Boolean(length + 1, true_probability, 0.0);
ValidateFilter(values, filter->Slice(0, values->length()));
ValidateFilter(values, filter_no_nulls->Slice(0, values->length()));
// Test values and filter have different offsets
ValidateFilter(values->Slice(3), filter->Slice(4));
ValidateFilter(values->Slice(3), filter_no_nulls->Slice(4));
}
}
}
};
template <typename ValuesType, typename IndexType>
void CheckTakeRandom(const std::shared_ptr<Array>& values, int64_t indices_length,
double null_probability, random::RandomArrayGenerator* rand) {
using IndexCType = typename IndexType::c_type;
IndexCType max_index = GetMaxIndex<IndexCType>(values->length());
auto indices = rand->Numeric<IndexType>(indices_length, static_cast<IndexCType>(0),
max_index, null_probability);
auto indices_no_nulls = rand->Numeric<IndexType>(
indices_length, static_cast<IndexCType>(0), max_index, /*null_probability=*/0.0);
ValidateTake<ValuesType>(values, indices);
ValidateTake<ValuesType>(values, indices_no_nulls);
// Sliced indices array
if (indices_length >= 2) {
indices = indices->Slice(1, indices_length - 2);
indices_no_nulls = indices_no_nulls->Slice(1, indices_length - 2);
ValidateTake<ValuesType>(values, indices);
ValidateTake<ValuesType>(values, indices_no_nulls);
}
}
template <typename ValuesType>
struct TakeRandomTest {
static void Test(const std::shared_ptr<DataType>& type) {
auto rand = random::RandomArrayGenerator(kRandomSeed);
const int64_t values_length = 64 * 16 + 1;
const int64_t indices_length = 64 * 4 + 1;
for (const auto null_probability : {0.0, 0.001, 0.05, 0.25, 0.95, 0.999, 1.0}) {
auto values = rand.ArrayOf(type, values_length, null_probability);
CheckTakeRandom<ValuesType, Int8Type>(values, indices_length, null_probability,
&rand);
CheckTakeRandom<ValuesType, Int16Type>(values, indices_length, null_probability,
&rand);
CheckTakeRandom<ValuesType, Int32Type>(values, indices_length, null_probability,
&rand);
CheckTakeRandom<ValuesType, Int64Type>(values, indices_length, null_probability,
&rand);
CheckTakeRandom<ValuesType, UInt8Type>(values, indices_length, null_probability,
&rand);
CheckTakeRandom<ValuesType, UInt16Type>(values, indices_length, null_probability,
&rand);
CheckTakeRandom<ValuesType, UInt32Type>(values, indices_length, null_probability,
&rand);
CheckTakeRandom<ValuesType, UInt64Type>(values, indices_length, null_probability,
&rand);
// Sliced values array
if (values_length > 2) {
values = values->Slice(1, values_length - 2);
CheckTakeRandom<ValuesType, UInt64Type>(values, indices_length, null_probability,
&rand);
}
}
}
};
TEST(TestFilter, PrimitiveRandom) { TestRandomPrimitiveCTypes<FilterRandomTest>(); }
TEST(TestFilter, RandomBoolean) { FilterRandomTest<>::Test(boolean()); }
TEST(TestFilter, RandomString) {
FilterRandomTest<>::Test(utf8());
FilterRandomTest<>::Test(large_utf8());
}
TEST(TestFilter, RandomFixedSizeBinary) {
FilterRandomTest<>::Test(fixed_size_binary(0));
FilterRandomTest<>::Test(fixed_size_binary(16));
}
TEST(TestTake, PrimitiveRandom) { TestRandomPrimitiveCTypes<TakeRandomTest>(); }
TEST(TestTake, RandomBoolean) { TakeRandomTest<BooleanType>::Test(boolean()); }
TEST(TestTake, RandomString) {
TakeRandomTest<StringType>::Test(utf8());
TakeRandomTest<LargeStringType>::Test(large_utf8());
}
TEST(TestTake, RandomFixedSizeBinary) {
TakeRandomTest<FixedSizeBinaryType>::Test(fixed_size_binary(0));
TakeRandomTest<FixedSizeBinaryType>::Test(fixed_size_binary(16));
}
} // namespace compute
} // namespace arrow
|
// Author: Florian Lier [flier AT techfak.uni-bielefeld DOT de]
/*
* Copyright (c) 2012-2016 Aldebaran Robotics. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the COPYING file.
*/
#include "naoqiwrapper.hpp"
NaoQiWrapper::NaoQiWrapper(std::string _robot_ip, std::string _robot_port) {
robot_ip = _robot_ip;
robot_port = std::atoi(_robot_port.c_str());
std::cout << ">>> Using Robot " << _robot_ip << ":" << std::atoi(_robot_port.c_str()) << std::endl;
motion = new AL::ALMotionProxy(robot_ip, robot_port);
robot_posture = new AL::ALRobotPostureProxy(robot_ip, robot_port);
memory_proxy = new AL::ALMemoryProxy(robot_ip, robot_port);
fractionMaxSpeed = 0.022f;
joints = AL::ALValue::array("HeadYaw", "HeadPitch");
angles = AL::ALValue::array(0.0f, 0.0f);
stiff = AL::ALValue::array(1.0f, 1.0f);
motion->setFallManagerEnabled(true);
motion->setSmartStiffnessEnabled(true);
wake();
setStiff(1.0f);
motion->setStiffnesses(joints, stiff);
std::cout << ">>> Setting Stiffness to 1.0" << std::endl;
robot_posture->goToPosture("Stand", 0.5f);
std::cout << ">>> Standing Up" << std::endl;
motion->moveInit();
AL::ALValue breathConfig;
breathConfig.arraySetSize(2);
AL::ALValue tmp;
tmp.arraySetSize(2);
tmp[0] = "Bpm";
tmp[1] = 7.0f;
breathConfig[0] = tmp;
tmp[0] = "Amplitude";
tmp[1] = 0.9f;
breathConfig[1] = tmp;
motion->setBreathConfig(breathConfig);
motion->setBreathEnabled("Body", true);
}
NaoQiWrapper::~NaoQiWrapper(){}
float NaoQiWrapper::getHeadPitch(){
return motion->getAngles("HeadPitch", useSensors)[0];
}
float NaoQiWrapper::getHeadYaw(){
return motion->getAngles("HeadYaw", useSensors)[0];
}
void NaoQiWrapper::printDataList() {
std::cout << memory_proxy->getDataList("Head") << std::endl;
}
float NaoQiWrapper::getHeadPitchVelocity() {
return memory_proxy->getData("Motion/Velocity/Sensor/HeadPitch");
}
float NaoQiWrapper::getHeadYawVelocity() {
return memory_proxy->getData("Motion/Velocity/Sensor/HeadYaw");
}
void NaoQiWrapper::setHeadYaw(float _yaw) {
angles[0] = degreeToRad(_yaw);
}
void NaoQiWrapper::setHeadPitch(float _pitch) {
angles[1] = degreeToRad(_pitch);
}
void NaoQiWrapper::setFractionSpeed(float _speed) {
fractionMaxSpeed = _speed;
}
void NaoQiWrapper::setStiff(float _stiff) {
for (int i=0; i < joints.getSize(); i++) {
stiff[i] = _stiff;
}
}
//void NaoQiWrapper::executeMotion() {
// motion->setAngles(joints, angles, fractionMaxSpeed);
//}
void NaoQiWrapper::executeMotion() {
if (skip == false) {
motion->setAngles(joints, angles, fractionMaxSpeed);
skip = true;
return;
} else {
skip = false;
return;
}
}
//void NaoQiWrapper::executeMotion() {
// if (divider % 5 == 0) {
// motion->setAngles(joints, angles, fractionMaxSpeed);
// }
// divider++;
//}
float NaoQiWrapper::degreeToRad(float _angle){
return (_angle * M_PI) / 180;
}
float NaoQiWrapper::getRandom(float min, float max) {
return (max - min) * ((((float) rand()) / (float) RAND_MAX)) + min ;
}
void NaoQiWrapper::shutdown(){
std::cout << ">>> Setting Stiffness to 0.0" << std::endl;
setStiff(0.0f);
motion->setStiffnesses(joints, stiff);
robot_posture->goToPosture("SitRelax", 0.5f);
rest();
}
void NaoQiWrapper::wake(){
std::cout << ">>> Waking Up" << std::endl;
motion->wakeUp();
}
void NaoQiWrapper::rest(){
std::cout << ">>> Resting" << std::endl;
motion->rest();
}
|
#pragma once
#include <iostream>
#include <cmath>
#include <fstream>
#include "Vector3D.hh"
#include "Vector4D.hh"
//#include "Matrix3D.hh"
class Object {
Vector3D LokCorners[CUBE];
public:
Object();
Object(const Object &obj);
Object(Vector3D ObjectCorners[CUBE]);
Vector3D &operator [] (int index);
const Vector3D &operator [] (int index) const;
double &operator () (unsigned int row, unsigned int column);
const double &operator () (unsigned int row, unsigned int column) const;
};
bool SaveToFile(const char *FileName, Object &Obj);
std::ostream &operator << (std::ostream &out, const Object &Obj);
|
/// DccInterpreter.cpp
///
/// DCC Interpreter for Arduino
#include <DccInterpreter.h>
#include <limits.h>
namespace Dcc
{
/// A preamble is valid if this number of "1" is transmitted (at least)
#define DCCINTERPRETER_PREAMBLE_MIN_NR_ONES 10u
// ---------------------------------------------------
/// Returns true if unNr exceeds the minimal number of "1"
// ---------------------------------------------------
static inline bool isPreambleValid(unsigned int unNr) { return unNr >= DCCINTERPRETER_PREAMBLE_MIN_NR_ONES; }
// ---------------------------------------------------
/// constructor
// ---------------------------------------------------
DccInterpreter::DccInterpreter()
: state(STATE_PREAMBLE)
, unNrBitsData(0u)
{
invalid();
}
// ---------------------------------------------------
/// destructor
// ---------------------------------------------------
DccInterpreter::~DccInterpreter()
{}
// ---------------------------------------------------
/// State function: check if a valid preamble is transmitted:
/// Sequence of at least 10x "1", followed by a "0"
// ---------------------------------------------------
DccInterpreter::eState DccInterpreter::executePreamble(eBit bitRcv)
{
eState nextState = state;
if (bitRcv == BIT_ONE)
{
// prevent overflow
if (unNrOnePreamble < 255u)
{
unNrOnePreamble++;
}
}
else // BIT_ZERO
{
if (isPreambleValid(unNrOnePreamble))
{
nextState = STATE_DATA;
}
// reset counter because
// - min number of "1" not reached, invalid or waiting for first "1"
// - or valid preamble detected, switch to STATE_DATE but prepare next switch to STATE_PREAMBLE
unNrOnePreamble = 0;
}
return nextState;
}
// ---------------------------------------------------
/// State function: Interpret adress or data bytes bit by bit.
// ---------------------------------------------------
DccInterpreter::eState DccInterpreter::executeData(eBit bitRcv)
{
eState nextState = state;
if (unNrBitsData < 8u)
{
CurrentPacket.addBit((unsigned int) bitRcv);
unNrBitsData++;
}
else
{
unNrBitsData = 0u;
// Bit 0 is expected at the end of a data / address byte
// If a 1 bit is received instead of a 0 bit, the packet is finished and the next packet is to be received
if (bitRcv == BIT_ONE)
{
nextState = STATE_PREAMBLE;
// store packet into the array (if it does not exist already)
packetReceived(CurrentPacket);
// prepare next reception
CurrentPacket.clear();
}
}
return nextState;
}
// ---------------------------------------------------
/// trigger state machine
// ---------------------------------------------------
void DccInterpreter::execute(eBit bitRcv)
{
switch (state)
{
case STATE_PREAMBLE: { state = executePreamble(bitRcv); } break;
case STATE_DATA : { state = executeData (bitRcv); } break;
default : {} break;
}
}
// ---------------------------------------------------
/// "1" bit received
// ---------------------------------------------------
void DccInterpreter::one()
{
execute(BIT_ONE);
}
// ---------------------------------------------------
/// "0" bit received
// ---------------------------------------------------
void DccInterpreter::zero()
{
execute(BIT_ZERO);
}
// ---------------------------------------------------
/// Invalid received, reset
// ---------------------------------------------------
void DccInterpreter::invalid()
{
state = STATE_PREAMBLE;
unNrOnePreamble = 0u;
unNrBitsData = 0u;
CurrentPacket.clear();
}
// ---------------------------------------------------
/// Store the received packet into the list of packets (if it does not exist already)
// ---------------------------------------------------
void DccInterpreter::packetReceived(const Packet& pkt)
{
PacketContainer::iterator it;
it = aPackets.find(pkt);
if (it == aPackets.end())
{
if (aPackets.size() < DCCINTERPRETER_MAXPACKETS)
{
aPackets.push_back(pkt);
aPackets.back().unNrRcv++;
}
}
else
{
if (it->unNrRcv < UINT_MAX - 1u)
{
it->unNrRcv++;
}
}
}
} // namespace Dcc
// EOF
|
/*
* Copyright (c) 2008-2021
* Nakata, Maho
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*/
#include <mpblas.h>
#include <mplapack.h>
void Claswp(INTEGER const n, COMPLEX *a, INTEGER const lda, INTEGER const k1, INTEGER const k2, INTEGER *ipiv, INTEGER const incx) {
//
// -- LAPACK auxiliary routine --
// -- LAPACK is a software package provided by Univ. of Tennessee, --
// -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--
//
// .. Scalar Arguments ..
// ..
// .. Array Arguments ..
// ..
//
// =====================================================================
//
// .. Local Scalars ..
// ..
// .. Executable Statements ..
//
// Interchange row I with row IPIV(K1+(I-K1)*abs(INCX)) for each of rows
// K1 through K2.
//
INTEGER ix0 = 0;
INTEGER i1 = 0;
INTEGER i2 = 0;
INTEGER inc = 0;
if (incx > 0) {
ix0 = k1;
i1 = k1;
i2 = k2;
inc = 1;
} else if (incx < 0) {
ix0 = k1 + (k1 - k2) * incx;
i1 = k2;
i2 = k1;
inc = -1;
} else {
return;
}
//
INTEGER n32 = (n / 32) * 32;
INTEGER j = 0;
INTEGER ix = 0;
INTEGER i = 0;
INTEGER ip = 0;
INTEGER k = 0;
COMPLEX temp = 0.0;
if (n32 != 0) {
for (j = 1; j <= n32; j = j + 32) {
ix = ix0;
for (i = i1; inc > 0 ? i <= i2 : i >= i2; i = i + inc) {
ip = ipiv[ix - 1];
if (ip != i) {
for (k = j; k <= j + 31; k = k + 1) {
temp = a[(i - 1) + (k - 1) * lda];
a[(i - 1) + (k - 1) * lda] = a[(ip - 1) + (k - 1) * lda];
a[(ip - 1) + (k - 1) * lda] = temp;
}
}
ix += incx;
}
}
}
if (n32 != n) {
n32++;
ix = ix0;
for (i = i1; inc > 0 ? i <= i2 : i >= i2; i = i + inc) {
ip = ipiv[ix - 1];
if (ip != i) {
for (k = n32; k <= n; k = k + 1) {
temp = a[(i - 1) + (k - 1) * lda];
a[(i - 1) + (k - 1) * lda] = a[(ip - 1) + (k - 1) * lda];
a[(ip - 1) + (k - 1) * lda] = temp;
}
}
ix += incx;
}
}
//
// End of Claswp
//
}
|
// LLVM module pass to create the single function (fully inlined)
// and parallelized kernel for an OpenCL workgroup.
//
// Copyright (c) 2011 Universidad Rey Juan Carlos
// 2012-2019 Pekka Jääskeläinen
//
// 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
// copies 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
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER 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 <cstdio>
#include <map>
#include <iostream>
#include "CompilerWarnings.h"
IGNORE_COMPILER_WARNING("-Wunused-parameter")
#include "config.h"
#include "pocl.h"
#include "pocl_llvm_api.h"
#include <llvm/Analysis/ConstantFolding.h>
#include <llvm/IR/BasicBlock.h>
#ifdef LLVM_OLDER_THAN_11_0
#include <llvm/IR/CallSite.h>
#endif
#include <llvm/IR/Constants.h>
#include <llvm/IR/DerivedTypes.h>
#include <llvm/IR/IRBuilder.h>
#ifdef LLVM_OLDER_THAN_7_0
#include <llvm/IR/TypeBuilder.h>
#endif
#include <llvm/IR/DIBuilder.h>
#include <llvm/IR/InlineAsm.h>
#include <llvm/IR/InstrTypes.h>
#include <llvm/IR/MDBuilder.h>
#include <llvm/Support/CommandLine.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Transforms/Utils/BasicBlockUtils.h>
#include <llvm/Transforms/Utils/Cloning.h>
#ifdef LLVM_OLDER_THAN_7_0
#include <llvm/Transforms/Utils/Local.h>
#endif
#include <llvm-c/Core.h>
#include <llvm-c/Target.h>
#include "Barrier.h"
#include "BarrierTailReplication.h"
#include "CanonicalizeBarriers.h"
#include "LLVMUtils.h"
#include "Workgroup.h"
#include "WorkitemReplication.h"
#include <cstdio>
#include <map>
#include <iostream>
#include <sstream>
#if _MSC_VER
# include "vccompat.hpp"
#endif
#define STRING_LENGTH 32
POP_COMPILER_DIAGS
using namespace std;
using namespace llvm;
using namespace pocl;
#ifdef LLVM_OLDER_THAN_7_0
namespace llvm {
typedef struct _pocl_context PoclContext;
template<bool xcompile> class TypeBuilder<PoclContext, xcompile> {
public:
static StructType *get(LLVMContext &Context) {
if (size_t_width == 64)
{
SmallVector<Type *, 10> Elements;
Elements.push_back(
TypeBuilder<types::i<64>[3], xcompile>::get(Context));
Elements.push_back(
TypeBuilder<types::i<64>[3], xcompile>::get(Context));
Elements.push_back(
TypeBuilder<types::i<64>[3], xcompile>::get(Context));
Elements.push_back(TypeBuilder<types::i<8> *, xcompile>::get(Context));
Elements.push_back(TypeBuilder<types::i<32> *, xcompile>::get(Context));
Elements.push_back(TypeBuilder<types::i<32>, xcompile>::get(Context));
Elements.push_back(TypeBuilder<types::i<32>, xcompile>::get(Context));
return StructType::get(Context, Elements);
}
else if (size_t_width == 32)
{
SmallVector<Type *, 10> Elements;
Elements.push_back(
TypeBuilder<types::i<32>[3], xcompile>::get(Context));
Elements.push_back(
TypeBuilder<types::i<32>[3], xcompile>::get(Context));
Elements.push_back(
TypeBuilder<types::i<32>[3], xcompile>::get(Context));
Elements.push_back(
TypeBuilder<types::i<8> *, xcompile>::get(Context));
Elements.push_back(
TypeBuilder<types::i<32> *, xcompile>::get(Context));
Elements.push_back(TypeBuilder<types::i<32>, xcompile>::get(Context));
Elements.push_back(
TypeBuilder<types::i<32>, xcompile>::get(Context));
return StructType::get(Context, Elements);
}
else
{
assert (false && "Unsupported size_t width.");
return NULL;
}
}
static void setSizeTWidth(int width) {
size_t_width = width;
}
private:
static int size_t_width;
};
template<bool xcompile>
int TypeBuilder<PoclContext, xcompile>::size_t_width = 0;
} // namespace llvm
#endif
enum PoclContextStructFields {
PC_NUM_GROUPS,
PC_GLOBAL_OFFSET,
PC_LOCAL_SIZE,
PC_PRINTF_BUFFER,
PC_PRINTF_BUFFER_POSITION,
PC_PRINTF_BUFFER_CAPACITY,
PC_WORK_DIM
};
char Workgroup::ID = 0;
static RegisterPass<Workgroup> X("workgroup", "Workgroup creation pass");
bool
Workgroup::runOnModule(Module &M) {
this->M = &M;
this->C = &M.getContext();
getModuleIntMetadata(M, "device_address_bits", address_bits);
getModuleBoolMetadata(M, "device_arg_buffer_launcher",
DeviceUsingArgBufferLauncher);
getModuleBoolMetadata(M, "device_grid_launcher",
DeviceUsingGridLauncher);
getModuleBoolMetadata(M, "device_is_spmd", DeviceIsSPMD);
getModuleStringMetadata(M, "KernelName", KernelName);
getModuleIntMetadata(M, "WGMaxGridDimWidth", WGMaxGridDimWidth);
getModuleIntMetadata(M, "WGLocalSizeX", WGLocalSizeX);
getModuleIntMetadata(M, "WGLocalSizeY", WGLocalSizeY);
getModuleIntMetadata(M, "WGLocalSizeZ", WGLocalSizeZ);
getModuleBoolMetadata(M, "WGDynamicLocalSize", WGDynamicLocalSize);
getModuleBoolMetadata(M, "WGAssumeZeroGlobalOffset",
WGAssumeZeroGlobalOffset);
getModuleIntMetadata(M, "device_global_as_id", DeviceGlobalASid);
getModuleIntMetadata(M, "device_local_as_id", DeviceLocalASid);
getModuleIntMetadata(M, "device_constant_as_id", DeviceConstantASid);
getModuleIntMetadata(M, "device_args_as_id", DeviceArgsASid);
getModuleIntMetadata(M, "device_context_as_id", DeviceContextASid);
getModuleBoolMetadata(M, "device_side_printf", DeviceSidePrintf);
getModuleBoolMetadata(M, "device_alloca_locals", DeviceAllocaLocals);
getModuleIntMetadata(M, "device_max_witem_dim", DeviceMaxWItemDim);
getModuleIntMetadata(M, "device_max_witem_sizes_0", DeviceMaxWItemSizes[0]);
getModuleIntMetadata(M, "device_max_witem_sizes_1", DeviceMaxWItemSizes[1]);
getModuleIntMetadata(M, "device_max_witem_sizes_2", DeviceMaxWItemSizes[2]);
HiddenArgs = 0;
SizeTWidth = address_bits;
SizeT = IntegerType::get(*C, SizeTWidth);
#ifdef LLVM_OLDER_THAN_7_0
TypeBuilder<PoclContext, true>::setSizeTWidth(SizeTWidth);
PoclContextT = TypeBuilder<PoclContext, true>::get(*C);
LauncherFuncT =
SizeTWidth == 32
? TypeBuilder<void(types::i<8> *[], PoclContext *, types::i<32>,
types::i<32>, types::i<32>),
true>::get(M.getContext())
: TypeBuilder<void(types::i<8> *[], PoclContext *, types::i<64>,
types::i<64>, types::i<64>),
true>::get(M.getContext());
#else
// LLVM 8.0 dropped the TypeBuilder API. This is a cleaner version
// anyways as it builds the context type using the SizeT directly.
llvm::Type *Int32T = Type::getInt32Ty(*C);
llvm::Type *Int8T = Type::getInt8Ty(*C);
PoclContextT =
StructType::get(
ArrayType::get(SizeT, 3), // NUM_GROUPS
ArrayType::get(SizeT, 3), // GLOBAL_OFFSET
ArrayType::get(SizeT, 3), // LOCAL_SIZE
PointerType::get(Int8T, 0), // PRINTF_BUFFER
PointerType::get(Int32T, 0), // PRINTF_BUFFER_POSITION
Int32T, // PRINTF_BUFFER_CAPACITY
Int32T); // WORK_DIM
LauncherFuncT = FunctionType::get(
Type::getVoidTy(*C),
{PointerType::get(PointerType::get(Type::getInt8Ty(*C), 0),
DeviceArgsASid),
PointerType::get(PoclContextT, DeviceContextASid), SizeT, SizeT, SizeT},
false);
#endif
assert ((SizeTWidth == 64 || SizeTWidth == 32) &&
"Target has an unsupported pointer width.");
for (Module::iterator i = M.begin(), e = M.end(); i != e; ++i) {
// Don't internalize functions starting with "__wrap_" for the use of GNU
// linker's switch --wrap=symbol, where calls to the "symbol" are replaced
// with "__wrap_symbol" at link time. These functions may not be referenced
// until final link and being deleted by LLVM optimizations before it.
if (!i->isDeclaration() && !i->getName().startswith("__wrap_"))
i->setLinkage(Function::InternalLinkage);
}
// Store the new and old kernel pairs in order to regenerate
// all the metadata that used to point to the unmodified
// kernels.
FunctionMapping kernels;
// Mapping of all functions which have been transformed to take
// extra printf arguments.
FunctionMapping printfCache;
for (Module::iterator i = M.begin(), e = M.end(); i != e; ++i) {
Function &OrigKernel = *i;
if (!isKernelToProcess(OrigKernel)) continue;
Function *L = createWrapper(&OrigKernel, printfCache);
privatizeContext(L);
if (DeviceUsingArgBufferLauncher) {
Function *WGLauncher =
createArgBufferWorkgroupLauncher(L, OrigKernel.getName().str());
L->addFnAttr(Attribute::NoInline);
L->removeFnAttr(Attribute::AlwaysInline);
WGLauncher->addFnAttr(Attribute::AlwaysInline);
if (DeviceUsingGridLauncher)
createGridLauncher(L, WGLauncher, OrigKernel.getName().str());
} else if (DeviceIsSPMD) {
// For SPMD machines there is no need for a WG launcher, the device will
// call/handle the single-WI kernel function directly.
kernels[&OrigKernel] = L;
} else {
createDefaultWorkgroupLauncher(L);
// This is used only by TCE anymore. TODO: Replace all with the
// ArgBuffer one.
createFastWorkgroupLauncher(L);
}
}
if (!DeviceUsingArgBufferLauncher && DeviceIsSPMD) {
regenerate_kernel_metadata(M, kernels);
// Delete the old kernels.
for (FunctionMapping::const_iterator i = kernels.begin(),
e = kernels.end(); i != e; ++i) {
Function *old_kernel = (*i).first;
Function *new_kernel = (*i).second;
if (old_kernel == new_kernel) continue;
old_kernel->eraseFromParent();
}
}
return true;
}
// Ensures the given value is not optimized away even if it's not used
// by LLVM IR.
void Workgroup::addPlaceHolder(llvm::IRBuilder<> &Builder,
llvm::Value *Val,
const std::string TypeStr="r") {
// For the lack of a better holder, add a dummy inline asm that reads the
// arg arguments.
FunctionType *DummyIAType =
FunctionType::get(Type::getVoidTy(M->getContext()), Val->getType(),
false);
llvm::InlineAsm *DummyIA =
llvm::InlineAsm::get(DummyIAType, "", TypeStr, false, false);
Builder.CreateCall(DummyIA, Val);
}
// Adds Range metadata with range [Min, Max] to the given instruction.
static void addRangeMetadata(llvm::Instruction *Instr, size_t Min, size_t Max) {
MDBuilder MDB(Instr->getContext());
size_t BitWidth = Instr->getType()->getIntegerBitWidth();
MDNode *Range =
MDB.createRange(APInt(BitWidth, Min), APInt(BitWidth, Max + 1));
Instr->setMetadata(LLVMContext::MD_range, Range);
}
void Workgroup::addRangeMetadataForPCField(llvm::Instruction *Instr,
int StructFieldIndex,
int FieldIndex) {
uint64_t Min = 0;
uint64_t Max = 0;
uint64_t LocalSizes[] = {WGLocalSizeX, WGLocalSizeY, WGLocalSizeZ};
switch (StructFieldIndex) {
case PC_WORK_DIM:
Min = 1;
Max = DeviceMaxWItemDim;
break;
case PC_NUM_GROUPS:
Min = 1;
switch (FieldIndex) {
case 0:
case 1:
case 2: {
Max = WGMaxGridDimWidth > 0 ? WGMaxGridDimWidth : 0;
if (!WGDynamicLocalSize) {
// If we know also the local size, we can minimize the known max group
// count by dividing by it. Upwards rounding due to 2.0 partial WGs.
Max = (Max + LocalSizes[FieldIndex] - 1) / LocalSizes[FieldIndex];
}
break;
}
default:
llvm_unreachable("More than 3 grid dimensions unsupported.");
}
break;
case PC_GLOBAL_OFFSET:
switch (FieldIndex) {
case 0:
case 1:
case 2:
// WGAssumeZeroGlobalOffset will be used to convert to a constant 0, so
// here we just speculate on the range in case of non-zero offset.
Max = WGMaxGridDimWidth;
break;
default:
llvm_unreachable("More than 3 grid dimensions unsupported.");
}
break;
case PC_LOCAL_SIZE:
Min = 1;
switch (FieldIndex) {
case 0:
case 1:
case 2:
if (WGDynamicLocalSize) {
Max = (WGMaxGridDimWidth > 0
? WGMaxGridDimWidth
: min(DeviceMaxWItemSizes[FieldIndex], WGMaxGridDimWidth));
} else {
// The local size is converted to constant with static WGs, so this is
// actually useless.
Max = LocalSizes[FieldIndex];
}
break;
default:
llvm_unreachable("More than 3 grid dimensions unsupported.");
}
break;
default:
break;
}
if (Max > 0) {
addRangeMetadata(Instr, Min, Max);
#if 0
std::cerr << "Added range [" << Min << ", " << Max << "] " << std::endl;
std::cerr << StructFieldIndex << " " << FieldIndex << std::endl;
#endif
}
return;
}
// Creates a load from the hidden context structure argument for
// the given element.
llvm::Value *
Workgroup::createLoadFromContext(
IRBuilder<> &Builder, int StructFieldIndex, int FieldIndex=-1) {
Value *GEP;
Type *ContextType = ContextArg->getType()->getPointerElementType();
GEP = Builder.CreateStructGEP(ContextType, ContextArg, StructFieldIndex);
Type *GEPType = GEP->getType()->getPointerElementType();
llvm::LoadInst *Load = nullptr;
if (SizeTWidth == 64) {
if (FieldIndex == -1)
Load = Builder.CreateLoad(Builder.CreateConstGEP1_64(
#ifndef LLVM_OLDER_THAN_13_0
GEPType,
#endif
GEP, 0));
else
Load = Builder.CreateLoad(Builder.CreateConstGEP2_64(
#ifndef LLVM_OLDER_THAN_13_0
GEPType,
#endif
GEP, 0, FieldIndex));
} else {
if (FieldIndex == -1)
Load = Builder.CreateLoad(Builder.CreateConstGEP1_32(
#ifndef LLVM_OLDER_THAN_13_0
GEPType,
#endif
GEP, 0));
else
Load = Builder.CreateLoad(Builder.CreateConstGEP2_32(
GEPType,
GEP, 0, FieldIndex));
}
addRangeMetadataForPCField(Load, StructFieldIndex, FieldIndex);
return Load;
}
// TODO we should use printf users instead of searching the call tree
static bool callsPrintf(Function *F) {
for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE; ++BI) {
Instruction *Instr = dyn_cast<Instruction>(BI);
if (!llvm::isa<CallInst>(Instr))
continue;
CallInst *CallInstr = dyn_cast<CallInst>(Instr);
if (CallInstr->isInlineAsm())
continue;
Function *callee = CallInstr->getCalledFunction();
if (callee->getName().startswith("llvm."))
continue;
if (callee->getName().equals("printf"))
return true;
if (callee->getName().equals("__pocl_printf"))
return true;
if (callsPrintf(callee))
return true;
}
}
return false;
}
// Clones a function while adding 3 new arguments for printf calls.
static Function *cloneFunctionWithPrintfArgs(Value *pb, Value *pbp, Value *pbc,
Function *F, Module *M) {
SmallVector<Type *, 8> Parameters;
Parameters.push_back(pb->getType());
Parameters.push_back(pbp->getType());
Parameters.push_back(pbc->getType());
for (Function::const_arg_iterator i = F->arg_begin(), e = F->arg_end();
i != e; ++i)
Parameters.push_back(i->getType());
// Create the new function.
FunctionType *FT =
FunctionType::get(F->getReturnType(), Parameters, F->isVarArg());
Function *NewF = Function::Create(FT, F->getLinkage(), "", M);
NewF->takeName(F);
ValueToValueMapTy VV;
Function::arg_iterator j = NewF->arg_begin();
j->setName("print_buffer");
++j;
j->setName("print_buffer_position");
++j;
j->setName("print_buffer_capacity");
++j;
for (Function::const_arg_iterator i = F->arg_begin(), e = F->arg_end();
i != e; ++i) {
j->setName(i->getName());
VV[&*i] = &*j;
++j;
}
SmallVector<ReturnInst *, 1> RI;
// As of LLVM 5.0 we need to let CFI to make module level changes,
// otherwise there will be an assertion. The changes are likely
// additional debug info nodes added when cloning the function into
// the other. For some reason it doesn't want to reuse the old ones.
CloneFunctionIntoAbs(NewF, F, VV, RI);
return NewF;
}
// Recursively replace _cl_printf calls with _pocl_printf calls, while
// propagating the required pocl_context->printf_buffer arguments.
static void replacePrintfCalls(Value *pb, Value *pbp, Value *pbc, bool isKernel,
Function *poclPrintf, Module &M, Function *L,
FunctionMapping &printfCache) {
// If none of the kernels use printf(), it will not be linked into the
// module.
if (poclPrintf == nullptr)
return;
// For kernel function, we are provided with proper printf arguments;
// for non-kernel functions, we assume the function was replaced with
// cloneFunctionWithPrintfArgs() and use the first three arguments.
if (!isKernel) {
auto i = L->arg_begin();
pb = &*i;
++i;
pbp = &*i;
++i;
pbc = &*i;
}
SmallDenseMap<CallInst *, CallInst *> replaceCIMap(16);
SmallVector<Value *, 8> ops;
SmallVector<CallInst *, 32> callsToCheck;
// First, replace printf calls in body of L.
for (Function::iterator I = L->begin(), E = L->end(); I != E; ++I) {
for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE; ++BI) {
Instruction *Instr = dyn_cast<Instruction>(BI);
if (!llvm::isa<CallInst>(Instr))
continue;
CallInst *CallInstr = dyn_cast<CallInst>(Instr);
if (CallInstr->isInlineAsm())
continue;
Function *oldF = CallInstr->getCalledFunction();
// Skip inline asm blocks.
if (oldF == nullptr)
continue;
if (oldF->getName().equals("printf")) {
ops.clear();
ops.push_back(pb);
ops.push_back(pbp);
ops.push_back(pbc);
unsigned j = CallInstr->getNumOperands() - 1;
for (unsigned i = 0; i < j; ++i)
ops.push_back(CallInstr->getOperand(i));
CallInst *NewCI = CallInst::Create(poclPrintf, ops);
NewCI->setCallingConv(poclPrintf->getCallingConv());
#ifdef LLVM_OLDER_THAN_11_0
CallSite CS(CallInstr);
NewCI->setTailCall(CS.isTailCall());
#else
auto *CB = dyn_cast<CallBase>(CallInstr);
NewCI->setTailCall(CB->isTailCall());
#endif
replaceCIMap.insert(
std::pair<CallInst *, CallInst *>(CallInstr, NewCI));
} else {
if (!oldF->getName().startswith("llvm."))
callsToCheck.push_back(CallInstr);
}
}
}
// replace printf calls
for (auto it : replaceCIMap) {
CallInst *CI = it.first;
CallInst *newCI = it.second;
// LLVM may modify the result type of the called function to void.
if (CI->getType()->isVoidTy()) {
newCI->insertBefore(CI);
CI->eraseFromParent();
} else {
CI->replaceAllUsesWith(newCI);
ReplaceInstWithInst(CI, newCI);
}
}
replaceCIMap.clear();
// check each called function recursively
for (auto it : callsToCheck) {
CallInst *CI = it;
CallInst *NewCI = nullptr;
Function *oldF = CI->getCalledFunction();
Function *newF = nullptr;
bool needsPrintf = false;
auto i = printfCache.find(oldF);
if (i != printfCache.end()) {
// function was already cloned
needsPrintf = true;
newF = i->second;
} else {
// create new clone
needsPrintf = callsPrintf(oldF);
if (needsPrintf) {
newF = cloneFunctionWithPrintfArgs(pb, pbp, pbc, oldF, &M);
replacePrintfCalls(nullptr, nullptr, nullptr, false, poclPrintf, M,
newF, printfCache);
printfCache.insert(
std::pair<llvm::Function *, llvm::Function *>(oldF, newF));
}
}
// if the called function calls Printf, replace with newF and add arguments
if (needsPrintf) {
ops.clear();
ops.push_back(pb);
ops.push_back(pbp);
ops.push_back(pbc);
unsigned j = CI->getNumOperands() - 1;
for (unsigned i = 0; i < j; ++i)
ops.push_back(CI->getOperand(i));
NewCI = CallInst::Create(newF, ops);
replaceCIMap.insert(std::pair<CallInst *, CallInst *>(CI, NewCI));
}
}
for (auto it : replaceCIMap) {
CallInst *CI = it.first;
CallInst *newCI = it.second;
CI->replaceAllUsesWith(newCI);
ReplaceInstWithInst(CI, newCI);
}
}
// Create a wrapper for the kernel and add pocl-specific hidden arguments.
// Also inlines the wrapped function to the wrapper.
Function *
Workgroup::createWrapper(Function *F, FunctionMapping &printfCache) {
SmallVector<Type *, 8> sv;
LLVMContext &C = M->getContext();
for (Function::const_arg_iterator i = F->arg_begin(), e = F->arg_end();
i != e; ++i)
sv.push_back(i->getType());
if (!DeviceUsingArgBufferLauncher && DeviceIsSPMD) {
sv.push_back(PointerType::get(PoclContextT, DeviceContextASid));
HiddenArgs = 1;
} else {
// pocl_context
sv.push_back(PointerType::get(PoclContextT, DeviceContextASid));
// group_x
sv.push_back(SizeT);
// group_y
sv.push_back(SizeT);
// group_z
sv.push_back(SizeT);
// we might not have all of the globals anymore in the module in case the
// kernel does not refer to them and they are optimized away
HiddenArgs = 4;
}
FunctionType *ft =
FunctionType::get(Type::getVoidTy(C), ArrayRef<Type *>(sv), false);
std::string funcName = "";
funcName = F->getName().str();
Function *L = NULL;
if (!DeviceUsingArgBufferLauncher && DeviceIsSPMD) {
Function *F = M->getFunction(funcName);
F->setName(funcName + "_original");
L = Function::Create(ft, Function::ExternalLinkage, funcName, M);
} else
L = Function::Create(ft, Function::ExternalLinkage,
"_pocl_kernel_" + funcName, M);
SmallVector<Value *, 8> arguments;
Function::arg_iterator ai = L->arg_begin();
for (unsigned i = 0, e = F->arg_size(); i != e; ++i) {
arguments.push_back(&*ai);
++ai;
}
ContextArg = &*(ai++);
GroupIdArgs.resize(3);
GroupIdArgs[0] = &*(ai++);
GroupIdArgs[1] = &*(ai++);
GroupIdArgs[2] = &*(ai++);
// Copy the function attributes to transfer noalias etc. from the
// original kernel which will be inlined into the launcher.
L->setAttributes(F->getAttributes());
// At least the argument address space metadata is useful. The argument
// indices should still hold even though we appended the hidden args.
L->copyMetadata(F, 0);
// We need to mark the generated function to avoid it being considered a
// new kernel to process (which results in infinite recursion). This is
// because kernels are detected by the presense of the argument metadata
// we just copied from the original kernel function.
L->setMetadata("pocl_generated", MDNode::get(C, {createConstantIntMD(C, 1)}));
IRBuilder<> Builder(BasicBlock::Create(C, "", L));
Value *pb, *pbp, *pbc;
if (DeviceSidePrintf) {
pb = createLoadFromContext(Builder, PC_PRINTF_BUFFER);
pbp = createLoadFromContext(Builder, PC_PRINTF_BUFFER_POSITION);
pbc = createLoadFromContext(Builder, PC_PRINTF_BUFFER_CAPACITY);
} else {
pb = pbp = pbc = nullptr;
}
CallInst *c = Builder.CreateCall(F, ArrayRef<Value*>(arguments));
Builder.CreateRetVoid();
std::set<CallInst *> CallsToRemove;
// At least with LLVM 4.0, the runtime of AddAliasScopeMetadata of
// llvm::InlineFunction explodes in case of kernels with restrict
// metadata and a lot of lifetime markers. The issue produces at
// least with EinsteinToolkit which has a lot of restrict kernel
// args). Remove them here before inlining to speed it up.
// TODO: Investigate the root cause.
for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE; ++BI) {
Instruction *Instr = dyn_cast<Instruction>(BI);
if (!llvm::isa<CallInst>(Instr)) continue;
CallInst *CallInstr = dyn_cast<CallInst>(Instr);
if (CallInstr->isInlineAsm()) continue;
Function *Callee = CallInstr->getCalledFunction();
// At least with LLVM 4.0, the runtime of AddAliasScopeMetadata of
// llvm::InlineFunction explodes in case of kernels with restrict
// metadata and a lot of lifetime markers. The issue produces at
// least with EinsteinToolkit which has a lot of restrict kernel
// args). Remove them here before inlining to speed it up.
// TODO: Investigate the root cause.
if (Callee != nullptr &&
(Callee->getName().startswith("llvm.lifetime.end") ||
Callee->getName().startswith("llvm.lifetime.start"))) {
CallsToRemove.insert(CallInstr);
continue;
}
}
}
for (auto C : CallsToRemove) {
C->eraseFromParent();
}
// needed for printf
InlineFunctionInfo IFI;
#ifdef LLVM_OLDER_THAN_11_0
InlineFunction(c, IFI);
#else
InlineFunction(*c, IFI);
#endif
if (DeviceSidePrintf) {
Function *poclPrintf = M->getFunction("__pocl_printf");
replacePrintfCalls(pb, pbp, pbc, true, poclPrintf, *M, L, printfCache);
}
L->setSubprogram(F->getSubprogram());
// SPMD machines might need a special calling convention to mark the
// kernels that should be executed in SPMD fashion. For MIMD/CPU,
// we want to use the default calling convention for the work group
// function.
if (DeviceIsSPMD)
L->setCallingConv(F->getCallingConv());
return L;
}
// Converts the given global context variable handles to loads from the
// hidden context struct argument. If there is no reference to the global,
// the corresponding entry in the returned vector will contain a nullptr.
std::vector<llvm::Value*>
Workgroup::globalHandlesToContextStructLoads(
IRBuilder<> &Builder,
const std::vector<std::string> &&GlobalHandleNames,
int StructFieldIndex) {
std::vector<Value*> StructLoads(GlobalHandleNames.size());
for (size_t i = 0; i < GlobalHandleNames.size(); ++i) {
if (M->getGlobalVariable(GlobalHandleNames.at(i)) == nullptr) {
StructLoads[i] = nullptr;
continue;
}
StructLoads[i] = createLoadFromContext(
Builder, StructFieldIndex, GlobalHandleNames.size() == 1 ? -1 : i);
}
return StructLoads;
}
// Converts uses of the given variable handles (external global variables) to
// use the given function-private values instead.
void
Workgroup::privatizeGlobals(llvm::Function *F, llvm::IRBuilder<> &Builder,
const std::vector<std::string> &&GlobalHandleNames,
std::vector<llvm::Value*> PrivateValues) {
for (Function::iterator i = F->begin(), e = F->end();
i != e; ++i) {
for (BasicBlock::iterator ii = i->begin(), ee = i->end(),
Next = std::next(ii); ii != ee; ii = Next) {
Next = std::next(ii);
for (size_t j = 0; j < GlobalHandleNames.size(); ++j) {
if (PrivateValues[j] == nullptr) {
continue;
}
if (!isa<llvm::LoadInst>(ii)) {
continue;
}
llvm::LoadInst *L = cast<llvm::LoadInst>(ii);
llvm::GlobalValue *GlobalHandle =
M->getGlobalVariable(GlobalHandleNames.at(j));
if (GlobalHandle == nullptr)
continue;
if (L->getPointerOperand()->stripPointerCasts() != GlobalHandle)
continue;
llvm::Value *Cast =
Builder.CreateTruncOrBitCast(PrivateValues[j], L->getType());
ii->replaceAllUsesWith(Cast);
ii->eraseFromParent();
break;
}
}
}
}
void
Workgroup::privatizeContext(Function *F)
{
char TempStr[STRING_LENGTH];
IRBuilder<> Builder(F->getEntryBlock().getFirstNonPHI());
std::vector<GlobalVariable*> LocalIdGlobals(3);
std::vector<AllocaInst*> LocalIdAllocas(3);
// Privatize _local_id to allocas. They are used as iteration variables in
// WorkItemLoops, thus referred to later on.
for (int i = 0; i < 3; ++i) {
snprintf(TempStr, STRING_LENGTH, "_local_id_%c", 'x' + i);
LocalIdGlobals[i] = M->getGlobalVariable(TempStr);
if (LocalIdGlobals[i] != NULL) {
LocalIdAllocas[i] =
Builder.CreateAlloca(LocalIdGlobals[i]->getType()->getElementType(), 0,
TempStr);
if (LocalIdGlobals[i]->hasInitializer()) {
Constant *C = LocalIdGlobals[i]->getInitializer();
Builder.CreateStore(C, LocalIdAllocas[i]);
}
}
}
for (Function::iterator i = F->begin(), e = F->end(); i != e; ++i) {
for (BasicBlock::iterator ii = i->begin(), ee = i->end();
ii != ee; ++ii) {
for (int j = 0; j < 3; ++j)
ii->replaceUsesOfWith(LocalIdGlobals[j], LocalIdAllocas[j]);
}
}
std::vector<GlobalVariable*> LocalSizeGlobals(3, nullptr);
std::vector<AllocaInst*> LocalSizeAllocas(3, nullptr);
// Privatize _local_size* to private allocas.
// They are referred to by WorkItemLoops to fetch the WI loop bounds.
for (int i = 0; i < 3; ++i) {
snprintf(TempStr, STRING_LENGTH, "_local_size_%c", 'x' + i);
LocalSizeGlobals[i] = M->getGlobalVariable(TempStr);
if (LocalSizeGlobals[i] != NULL) {
LocalSizeAllocas[i] =
Builder.CreateAlloca(LocalSizeGlobals[i]->getType()->getElementType(),
0, TempStr);
if (LocalSizeGlobals[i]->hasInitializer()) {
Constant *C = LocalSizeGlobals[i]->getInitializer();
Builder.CreateStore(C, LocalSizeAllocas[i]);
}
}
}
for (Function::iterator i = F->begin(), e = F->end(); i != e; ++i) {
for (BasicBlock::iterator ii = i->begin(), ee = i->end();
ii != ee; ++ii) {
for (int j = 0; j < 3; ++j)
ii->replaceUsesOfWith(LocalSizeGlobals[j], LocalSizeAllocas[j]);
}
}
if (WGDynamicLocalSize) {
if (LocalSizeAllocas[0] != nullptr)
Builder.CreateStore(
createLoadFromContext(Builder, PC_LOCAL_SIZE, 0),
LocalSizeAllocas[0]);
if (LocalSizeAllocas[1] != nullptr)
Builder.CreateStore(
createLoadFromContext(Builder, PC_LOCAL_SIZE, 1),
LocalSizeAllocas[1]);
if (LocalSizeAllocas[2] != nullptr)
Builder.CreateStore(
createLoadFromContext(Builder, PC_LOCAL_SIZE, 2),
LocalSizeAllocas[2]);
} else {
if (LocalSizeAllocas[0] != nullptr)
Builder.CreateStore(
ConstantInt::get(
LocalSizeAllocas[0]->getAllocatedType(), WGLocalSizeX, 0),
LocalSizeAllocas[0]);
if (LocalSizeAllocas[1] != nullptr)
Builder.CreateStore(
ConstantInt::get(
LocalSizeAllocas[1]->getAllocatedType(), WGLocalSizeY, 1),
LocalSizeAllocas[1]);
if (LocalSizeAllocas[2] != nullptr)
Builder.CreateStore(
ConstantInt::get(
LocalSizeAllocas[2]->getAllocatedType(), WGLocalSizeZ, 2),
LocalSizeAllocas[2]);
}
privatizeGlobals(
F, Builder, {"_group_id_x", "_group_id_y", "_group_id_z"}, GroupIdArgs);
if (WGAssumeZeroGlobalOffset) {
privatizeGlobals(
F, Builder,
{"_global_offset_x", "_global_offset_y", "_global_offset_z"},
{ConstantInt::get(SizeT, 0), ConstantInt::get(SizeT, 0),
ConstantInt::get(SizeT, 0)});
} else {
privatizeGlobals(
F, Builder,
{"_global_offset_x", "_global_offset_y", "_global_offset_z"},
globalHandlesToContextStructLoads(
Builder,
{"_global_offset_x", "_global_offset_y", "_global_offset_z"},
PC_GLOBAL_OFFSET));
}
privatizeGlobals(
F, Builder, {"_work_dim"},
globalHandlesToContextStructLoads(Builder, {"_work_dim"}, PC_WORK_DIM));
privatizeGlobals(
F, Builder, {"_num_groups_x", "_num_groups_y", "_num_groups_z"},
globalHandlesToContextStructLoads(
Builder, {"_num_groups_x", "_num_groups_y", "_num_groups_z"},
PC_NUM_GROUPS));
if (DeviceSidePrintf) {
// Privatize _printf_buffer
privatizeGlobals(
F, Builder, {"_printf_buffer"}, {
createLoadFromContext(
Builder, PC_PRINTF_BUFFER)});
privatizeGlobals(
F, Builder, {"_printf_buffer_position"}, {
createLoadFromContext(
Builder, PC_PRINTF_BUFFER_POSITION)});
privatizeGlobals(
F, Builder, {"_printf_buffer_capacity"}, {
createLoadFromContext(
Builder, PC_PRINTF_BUFFER_CAPACITY)});
}
}
// Creates a work group launcher function (called KERNELNAME_workgroup)
// that assumes kernel pointer arguments are stored as pointers to the
// actual buffers and that scalar data is loaded from the default memory.
void
Workgroup::createDefaultWorkgroupLauncher(llvm::Function *F) {
IRBuilder<> Builder(M->getContext());
std::string FuncName = "";
FuncName = F->getName().str();
#ifdef LLVM_OLDER_THAN_9_0
Function *WorkGroup =
dyn_cast<Function>(M->getOrInsertFunction(
FuncName + "_workgroup", LauncherFuncT));
#else
FunctionCallee fc = M->getOrInsertFunction(FuncName + "_workgroup", LauncherFuncT);
Function *WorkGroup = dyn_cast<Function>(fc.getCallee());
#endif
assert(WorkGroup != nullptr);
BasicBlock *Block = BasicBlock::Create(M->getContext(), "", WorkGroup);
Builder.SetInsertPoint(Block);
Function::arg_iterator ai = WorkGroup->arg_begin();
SmallVector<Value *, 8> Arguments;
size_t i = 0;
for (Function::const_arg_iterator ii = F->arg_begin(), ee = F->arg_end();
ii != ee; ++ii) {
if (i == F->arg_size() - 4)
break;
Type *ArgType = ii->getType();
Type* I32Ty = Type::getInt32Ty(M->getContext());
Value *AI = &*ai;
Value *GEP = Builder.CreateGEP(AI->getType()->getPointerElementType(),
AI, ConstantInt::get(I32Ty, i));
Value *Pointer = Builder.CreateLoad(GEP->getType()->getPointerElementType(), GEP);
Value *Arg;
if (DeviceAllocaLocals && isLocalMemFunctionArg(F, i)) {
// Generate allocas for the local buffer arguments.
PointerType *ParamType = dyn_cast<PointerType>(ArgType);
Type *ArgElementType = ParamType->getElementType();
if (ArgElementType->isArrayTy()) {
// Known static local size (converted automatic local).
Arg =
new llvm::AllocaInst(ArgElementType, ParamType->getAddressSpace(),
ConstantInt::get(IntegerType::get(*C, 32), 1),
#ifndef LLVM_OLDER_THAN_10_0
#ifndef LLVM_OLDER_THAN_11_0
llvm::Align(
#else
llvm::MaybeAlign(
#endif
#endif
MAX_EXTENDED_ALIGNMENT
#ifndef LLVM_OLDER_THAN_10_0
)
#endif
,
"local_auto", Block);
} else {
// Dynamic (runtime-set) size local argument.
const DataLayout &DL = M->getDataLayout();
// The size is passed directly instead of the pointer.
uint64_t ParamByteSize = DL.getTypeStoreSize(ParamType);
uint64_t ElementSize = DL.getTypeStoreSize(ArgElementType);
Type *SizeIntType = IntegerType::get(*C, ParamByteSize * 8);
Value *LocalArgByteSize =
Builder.CreatePointerCast(Pointer, SizeIntType);
Value *ElementCount = Builder.CreateUDiv(
LocalArgByteSize, ConstantInt::get(SizeIntType, ElementSize));
Arg = new llvm::AllocaInst(ArgElementType, ParamType->getAddressSpace(),
ElementCount,
#ifndef LLVM_OLDER_THAN_10_0
#ifndef LLVM_OLDER_THAN_11_0
llvm::Align(
#else
llvm::MaybeAlign(
#endif
#endif
MAX_EXTENDED_ALIGNMENT
#ifndef LLVM_OLDER_THAN_10_0
)
#endif
,
"local_arg", Block);
}
} else {
// If it's a pass by value pointer argument, we just pass the pointer
// as is to the function, no need to load from it first.
if (ii->hasByValAttr()) {
Arg = Builder.CreatePointerCast(Pointer, ArgType);
} else {
Arg = Builder.CreatePointerCast(Pointer, ArgType->getPointerTo());
Arg = Builder.CreateLoad(ArgType, Arg);
}
}
Arguments.push_back(Arg);
++i;
}
++ai;
Arguments.push_back(&*ai);
++ai;
Arguments.push_back(&*ai);
++ai;
Arguments.push_back(&*ai);
++ai;
Arguments.push_back(&*ai);
Builder.CreateCall(F, ArrayRef<Value *>(Arguments));
Builder.CreateRetVoid();
}
static inline uint64_t
align64(uint64_t value, unsigned alignment)
{
return (value + alignment - 1) & ~((uint64_t)alignment - 1);
}
static bool isByValPtrArgument(llvm::Argument &Arg) {
return Arg.getType()->isPointerTy() && Arg.hasByValAttr();
}
static size_t getArgumentSize(llvm::Argument &Arg) {
llvm::Type *TypeInBuf = nullptr;
if (Arg.getType()->isPointerTy()) {
if (Arg.hasByValAttr()) {
TypeInBuf = Arg.getType()->getPointerElementType();
} else {
TypeInBuf = Arg.getType();
}
} else {
// Scalar argument.
TypeInBuf = Arg.getType();
}
const DataLayout &DL = Arg.getParent()->getParent()->getDataLayout();
return DL.getTypeStoreSize(TypeInBuf);
}
// Tofix: Why this is duplicated here? pocl_utils.c should be used?
static uint64_t pocl_size_ceil2_64(uint64_t x) {
/* Rounds up to the next highest power of two without branching and
* is as fast as a BSR instruction on x86, see:
*
* http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
*/
--x;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
x |= x >> 32;
return ++x;
}
static void computeArgBufferOffsets(LLVMValueRef F,
uint64_t *ArgBufferOffsets) {
uint64_t Offset = 0;
uint64_t ArgCount = LLVMCountParams(F);
// Compute the byte offsets of arguments in the arg buffer.
for (size_t i = 0; i < ArgCount; i++) {
LLVMValueRef Param = LLVMGetParam(F, i);
// TODO: This is a target specific type? We would like to get the
// natural size or the "packed size" instead...
uint64_t ByteSize = getArgumentSize(cast<Argument>(*unwrap(Param)));
uint64_t Alignment = pocl_size_ceil2_64(ByteSize);
assert(ByteSize > 0 && "Arg type size is zero?");
Offset = align64(Offset, Alignment);
ArgBufferOffsets[i] = Offset;
Offset += ByteSize;
}
}
LLVMValueRef
Workgroup::createAllocaMemcpyForStruct(LLVMModuleRef M, LLVMBuilderRef Builder,
llvm::Argument &Arg,
LLVMValueRef ArgByteOffset) {
LLVMContextRef LLVMContext = LLVMGetModuleContext(M);
LLVMValueRef MemCpy1 = LLVMGetNamedFunction(M, "_pocl_memcpy_1");
LLVMValueRef MemCpy4 = LLVMGetNamedFunction(M, "_pocl_memcpy_4");
LLVMTypeRef Int8Type = LLVMInt8TypeInContext(LLVMContext);
LLVMTypeRef Int32Type = LLVMInt32TypeInContext(LLVMContext);
llvm::Type *TypeInArg = Arg.getType()->getPointerElementType();
const DataLayout &DL = Arg.getParent()->getParent()->getDataLayout();
unsigned alignment = DL.getABITypeAlignment(TypeInArg);
uint64_t StoreSize = DL.getTypeStoreSize(TypeInArg);
LLVMValueRef Size =
LLVMConstInt(LLVMInt32TypeInContext(LLVMContext), StoreSize, 0);
LLVMValueRef LocalArgAlloca =
LLVMBuildAlloca(Builder, wrap(TypeInArg), "struct_arg");
if ((alignment % 4 == 0) && (StoreSize % 4 == 0)) {
LLVMTypeRef i32PtrAS0 = LLVMPointerType(Int32Type, 0);
LLVMTypeRef i32PtrAS1 = LLVMPointerType(Int32Type, DeviceArgsASid);
LLVMValueRef CARG0 =
LLVMBuildPointerCast(Builder, LocalArgAlloca, i32PtrAS0, "cargDst");
LLVMValueRef CARG1 =
LLVMBuildPointerCast(Builder, ArgByteOffset, i32PtrAS1, "cargSrc");
LLVMValueRef args[3];
args[0] = CARG0;
args[1] = CARG1;
args[2] = Size;
LLVMValueRef call4 = LLVMBuildCall(Builder, MemCpy4, args, 3, "");
} else {
LLVMTypeRef i8PtrAS0 = LLVMPointerType(Int8Type, 0);
LLVMTypeRef i8PtrAS1 = LLVMPointerType(Int8Type, DeviceArgsASid);
LLVMValueRef CARG0 =
LLVMBuildPointerCast(Builder, LocalArgAlloca, i8PtrAS0, "cargDst");
LLVMValueRef CARG1 =
LLVMBuildPointerCast(Builder, ArgByteOffset, i8PtrAS1, "cargSrc");
LLVMValueRef args[3];
args[0] = CARG0;
args[1] = CARG1;
args[2] = Size;
LLVMValueRef call1 = LLVMBuildCall(Builder, MemCpy1, args, 3, "");
}
return LocalArgAlloca;
}
LLVMValueRef Workgroup::createArgBufferLoad(LLVMBuilderRef Builder,
LLVMValueRef ArgBufferPtr,
uint64_t *ArgBufferOffsets,
LLVMValueRef F,
unsigned ParamIndex) {
LLVMValueRef Param = LLVMGetParam(F, ParamIndex);
LLVMTypeRef ParamType = LLVMTypeOf(Param);
LLVMModuleRef M = LLVMGetGlobalParent(F);
LLVMContextRef LLVMContext = LLVMGetModuleContext(M);
uint64_t ArgPos = ArgBufferOffsets[ParamIndex];
LLVMValueRef Offs =
LLVMConstInt(LLVMInt32TypeInContext(LLVMContext), ArgPos, 0);
LLVMValueRef ArgByteOffset =
LLVMBuildGEP(Builder, ArgBufferPtr, &Offs, 1, "arg_byte_offset");
llvm::Argument &Arg = cast<Argument>(*unwrap(Param));
// byval arguments (private structs), passed via pointer
if (isByValPtrArgument(Arg)) {
// the kernel AS for private structs is always zero (private).
// if the arg address space is also zero, nothing to do here just cast...
if (DeviceArgsASid == 0)
return LLVMBuildPointerCast(Builder, ArgByteOffset, ParamType,
"inval_arg_ptr");
// ... otherwise the arg AS is different, and we need an alloca+memcpy.
else
return createAllocaMemcpyForStruct(M, Builder, Arg, ArgByteOffset);
// not by-val argument
} else {
LLVMValueRef ArgOffsetBitcast = LLVMBuildPointerCast(
Builder, ArgByteOffset, LLVMPointerType(ParamType, DeviceArgsASid),
"arg_ptr");
return LLVMBuildLoad(Builder, ArgOffsetBitcast, "");
}
}
/**
* Creates a work group launcher with all the argument data passed
* in a single argument buffer.
*
* All argument values, including pointers are stored directly in the
* argument buffer with natural alignment. The rules for populating the
* buffer are those of the HSA kernel calling convention. The name of
* the generated function is KERNELNAME_workgroup_argbuffer.
*/
Function*
Workgroup::createArgBufferWorkgroupLauncher(Function *Func,
std::string KernName) {
LLVMValueRef F = wrap(Func);
uint64_t ArgCount = LLVMCountParams(F);
uint64_t ArgBufferOffsets[ArgCount];
LLVMModuleRef M = wrap(this->M);
computeArgBufferOffsets(F, ArgBufferOffsets);
LLVMContextRef LLVMContext = LLVMGetModuleContext(M);
LLVMTypeRef Int8Type = LLVMInt8TypeInContext(LLVMContext);
LLVMTypeRef Int32Type = LLVMInt32TypeInContext(LLVMContext);
LLVMTypeRef Int64Type = LLVMInt64TypeInContext(LLVMContext);
LLVMTypeRef ArgsPtrType = LLVMPointerType(Int8Type, DeviceArgsASid);
LLVMTypeRef CtxPtrType = LLVMPointerType(Int8Type, DeviceContextASid);
std::ostringstream StrStr;
StrStr << KernName;
StrStr << "_workgroup_argbuffer";
std::string FName = StrStr.str();
const char *FunctionName = FName.c_str();
LLVMTypeRef LauncherArgTypes[] = {
ArgsPtrType, // args
CtxPtrType, // pocl_ctx
wrap(SizeT), // group_x
wrap(SizeT), // group_y
wrap(SizeT), // group_z
};
LLVMTypeRef VoidType = LLVMVoidTypeInContext(LLVMContext);
LLVMTypeRef LauncherFuncType =
LLVMFunctionType(VoidType, LauncherArgTypes, 1 + HiddenArgs, 0);
LLVMValueRef WrapperKernel =
LLVMAddFunction(M, FunctionName, LauncherFuncType);
LLVMBasicBlockRef Block =
LLVMAppendBasicBlockInContext(LLVMContext, WrapperKernel, "entry");
LLVMBuilderRef Builder = LLVMCreateBuilderInContext(LLVMContext);
assert(Builder);
LLVMPositionBuilderAtEnd(Builder, Block);
LLVMValueRef Args[ArgCount];
LLVMValueRef ArgBuffer = LLVMGetParam(WrapperKernel, 0);
size_t i = 0;
for (; i < ArgCount - HiddenArgs; ++i) {
if (DeviceAllocaLocals && isLocalMemFunctionArg(Func, i)) {
// Generate allocas for the local buffer arguments.
LLVMValueRef Param = LLVMGetParam(F, i);
LLVMTypeRef ParamType = LLVMTypeOf(Param);
LLVMTargetDataRef DataLayout = LLVMGetModuleDataLayout(M);
LLVMTypeRef ArgElementType = LLVMGetElementType(ParamType);
LLVMValueRef LocalArgAlloca = nullptr;
if (LLVMGetTypeKind(ArgElementType) == LLVMArrayTypeKind) {
// Known static local size (converted automatic local).
LocalArgAlloca = wrap(new llvm::AllocaInst(
unwrap(ArgElementType), LLVMGetPointerAddressSpace(ParamType),
unwrap(LLVMConstInt(Int32Type, 1, 0)),
#ifndef LLVM_OLDER_THAN_10_0
#ifndef LLVM_OLDER_THAN_11_0
llvm::Align(
#else
llvm::MaybeAlign(
#endif
#endif
MAX_EXTENDED_ALIGNMENT
#ifndef LLVM_OLDER_THAN_10_0
)
#endif
,
"local_auto", unwrap(Block)));
} else {
// Dynamic (runtime-set) size local argument.
uint64_t ParamByteSize = LLVMStoreSizeOfType(DataLayout, ParamType);
LLVMTypeRef ParamIntType = ParamByteSize == 4 ? Int32Type : Int64Type;
uint64_t ArgPos = ArgBufferOffsets[i];
LLVMValueRef Offs = LLVMConstInt(Int32Type, ArgPos, 0);
LLVMValueRef SizeByteOffset =
LLVMBuildGEP(Builder, ArgBuffer, &Offs, 1, "size_byte_offset");
LLVMValueRef SizeOffsetBitcast =
LLVMBuildPointerCast(Builder, SizeByteOffset,
LLVMPointerType(ParamIntType, 0), "size_ptr");
// The buffer size passed from the runtime is a byte size, we
// need to convert it to an element count for the alloca.
LLVMValueRef LocalArgByteSize =
LLVMBuildLoad(Builder, SizeOffsetBitcast, "byte_size");
uint64_t ElementSize = LLVMStoreSizeOfType(DataLayout, ArgElementType);
LLVMValueRef ElementCount =
LLVMBuildUDiv(Builder, LocalArgByteSize,
LLVMConstInt(ParamIntType, ElementSize, 0), "");
LocalArgAlloca = wrap(new llvm::AllocaInst(
unwrap(LLVMGetElementType(ParamType)),
LLVMGetPointerAddressSpace(ParamType), unwrap(ElementCount),
#ifndef LLVM_OLDER_THAN_10_0
#ifndef LLVM_OLDER_THAN_11_0
llvm::Align(
#else
llvm::MaybeAlign(
#endif
#endif
MAX_EXTENDED_ALIGNMENT
#ifndef LLVM_OLDER_THAN_10_0
)
#endif
,
"local_arg", unwrap(Block)));
}
Args[i] = LocalArgAlloca;
} else {
Args[i] = createArgBufferLoad(Builder, ArgBuffer, ArgBufferOffsets, F, i);
}
}
size_t Arg = 1;
// Pass the context object
LLVMValueRef CtxParam = LLVMGetParam(WrapperKernel, Arg++);
LLVMTypeRef CtxT = wrap(PoclContextT);
LLVMTypeRef CtxPtrTypeActual = LLVMPointerType(CtxT, DeviceContextASid);
LLVMValueRef CastContext =
LLVMBuildPointerCast(Builder, CtxParam, CtxPtrTypeActual, "ctx_ptr");
Args[i++] = CastContext;
// Pass the group ids.
Args[i++] = LLVMGetParam(WrapperKernel, Arg++);
Args[i++] = LLVMGetParam(WrapperKernel, Arg++);
Args[i++] = LLVMGetParam(WrapperKernel, Arg++);
assert (i == ArgCount);
LLVMValueRef Call = LLVMBuildCall(Builder, F, Args, ArgCount, "");
LLVMBuildRetVoid(Builder);
llvm::CallInst *CallI = llvm::dyn_cast<llvm::CallInst>(llvm::unwrap(Call));
CallI->setCallingConv(Func->getCallingConv());
LLVMDisposeBuilder(Builder);
return llvm::dyn_cast<llvm::Function>(llvm::unwrap(WrapperKernel));
}
/**
* Creates a launcher function that executes all work-items in the grid by
* launching a given work-group function for all work-group ids.
*
* The function adheres to the PHSA calling convention where the first two
* arguments are for PHSA's context data, and the third one is the argument
* buffer. The name will be phsa_kernel.KERNELNAME_grid_launcher.
*/
void
Workgroup::createGridLauncher(Function *KernFunc, Function *WGFunc,
std::string KernName) {
LLVMValueRef Kernel = llvm::wrap(KernFunc);
LLVMValueRef WGF = llvm::wrap(WGFunc);
LLVMModuleRef M = llvm::wrap(this->M);
LLVMContextRef LLVMContext = LLVMGetModuleContext(M);
LLVMTypeRef Int8Type = LLVMInt8TypeInContext(LLVMContext);
LLVMTypeRef Int8PtrType = LLVMPointerType(Int8Type, 0);
LLVMTypeRef ArgsPtrType = LLVMPointerType(Int8Type, DeviceArgsASid);
std::ostringstream StrStr("phsa_kernel.", std::ios::ate);
StrStr << KernName;
StrStr << "_grid_launcher";
std::string FName = StrStr.str();
const char *FunctionName = FName.c_str();
LLVMTypeRef LauncherArgTypes[] = {
Int8PtrType /*phsactx0*/, Int8PtrType /*phsactx1*/, ArgsPtrType /*args*/};
LLVMTypeRef VoidType = LLVMVoidTypeInContext(LLVMContext);
LLVMTypeRef LauncherFuncType =
LLVMFunctionType(VoidType, LauncherArgTypes, 3, 0);
LLVMValueRef Launcher =
LLVMAddFunction(M, FunctionName, LauncherFuncType);
LLVMBasicBlockRef Block =
LLVMAppendBasicBlockInContext(LLVMContext, Launcher, "entry");
LLVMBuilderRef Builder = LLVMCreateBuilderInContext(LLVMContext);
assert(Builder);
LLVMPositionBuilderAtEnd(Builder, Block);
LLVMValueRef RunnerFunc = LLVMGetNamedFunction(M, "_pocl_run_all_wgs");
assert (RunnerFunc != nullptr);
LLVMTypeRef ArgTypes[] = {
LLVMTypeOf(LLVMGetParam(RunnerFunc, 0)),
LLVMTypeOf(LLVMGetParam(RunnerFunc, 1)),
LLVMTypeOf(LLVMGetParam(RunnerFunc, 2))};
uint64_t KernArgCount = LLVMCountParams(Kernel);
uint64_t KernArgBufferOffsets[KernArgCount];
computeArgBufferOffsets(Kernel, KernArgBufferOffsets);
// The second argument in the native phsa interface is auxiliary
// driver-specific data that is passed as the last argument to
// the grid launcher.
LLVMValueRef AuxParam = LLVMGetParam(Launcher, 1);
LLVMValueRef ArgBuffer = LLVMGetParam(Launcher, 2);
// Load the pointer to the pocl context (in global memory),
// assuming it is stored as the 4th last argument in the kernel.
LLVMValueRef PoclCtx =
createArgBufferLoad(Builder, ArgBuffer, KernArgBufferOffsets, Kernel,
KernArgCount - HiddenArgs);
LLVMValueRef Args[4] = {
LLVMBuildPointerCast(Builder, WGF, ArgTypes[0], "wg_func"),
LLVMBuildPointerCast(Builder, ArgBuffer, ArgTypes[1], "args"),
LLVMBuildPointerCast(Builder, PoclCtx, ArgTypes[2], "ctx"),
LLVMBuildPointerCast(Builder, AuxParam, ArgTypes[1], "aux")};
LLVMValueRef Call = LLVMBuildCall(Builder, RunnerFunc, Args, 4, "");
LLVMBuildRetVoid(Builder);
InlineFunctionInfo IFI;
#ifndef LLVM_OLDER_THAN_11_0
InlineFunction(*dyn_cast<CallInst>(llvm::unwrap(Call)), IFI);
#else
InlineFunction(dyn_cast<CallInst>(llvm::unwrap(Call)), IFI);
#endif
}
/**
* Creates a work group launcher more suitable for the heterogeneous
* host-device setup (called KERNELNAME_workgroup_fast).
*
* 1) Pointer arguments are stored directly as pointers to the
* buffers in the argument buffer.
*
* 2) Scalar values are loaded from the global memory address
* space.
*
* This should minimize copying of data and memory allocation
* at the device.
*/
void
Workgroup::createFastWorkgroupLauncher(llvm::Function *F) {
IRBuilder<> builder(M->getContext());
std::string funcName = "";
funcName = F->getName().str();
#ifdef LLVM_OLDER_THAN_9_0
Function *WorkGroup =
dyn_cast<Function>(M->getOrInsertFunction(
funcName + "_workgroup_fast", LauncherFuncT));
#else
FunctionCallee fc = M->getOrInsertFunction(
funcName + "_workgroup_fast", LauncherFuncT);
Function *WorkGroup = dyn_cast<Function>(fc.getCallee());
#endif
assert(WorkGroup != NULL);
builder.SetInsertPoint(BasicBlock::Create(M->getContext(), "", WorkGroup));
Function::arg_iterator ai = WorkGroup->arg_begin();
SmallVector<Value*, 8> arguments;
size_t i = 0;
for (Function::const_arg_iterator ii = F->arg_begin(), ee = F->arg_end();
ii != ee; ++ii, ++i) {
if (i == F->arg_size() - 4)
break;
Type *T = ii->getType();
Type* I32Ty = Type::getInt32Ty(M->getContext());
Value *AI = &*ai;
Value *GEP = builder.CreateGEP(AI->getType()->getPointerElementType(),
AI, ConstantInt::get(I32Ty, i));
Value *Pointer = builder.CreateLoad(GEP->getType()->getPointerElementType(), GEP);
Value *V;
if (T->isPointerTy()) {
if (!ii->hasByValAttr()) {
// Assume the pointer is directly in the arg array.
V = builder.CreatePointerCast(Pointer, T);
arguments.push_back(V);
continue;
} else {
// It's a pass by value pointer argument, use the underlying
// element type in subsequent load.
T = T->getPointerElementType();
}
}
// If it's a pass by value pointer argument, we just pass the pointer
// as is to the function, no need to load from it first.
if (ii->hasByValAttr() && (((PointerType *)T)->getAddressSpace() != DeviceGlobalASid)) {
V = builder.CreatePointerCast(Pointer, T->getPointerTo());
} else {
V =
builder.CreatePointerCast(Pointer, T->getPointerTo(DeviceGlobalASid));
}
if (!ii->hasByValAttr()) {
V = builder.CreateLoad(T, V);
}
arguments.push_back(V);
}
++ai;
arguments.push_back(&*ai);
++ai;
arguments.push_back(&*ai);
++ai;
arguments.push_back(&*ai);
++ai;
arguments.push_back(&*ai);
builder.CreateCall(F, ArrayRef<Value*>(arguments));
builder.CreateRetVoid();
}
// Returns true in case the given function is a kernel that
// should be processed by the kernel compiler.
bool Workgroup::isKernelToProcess(const Function &F) {
const Module *m = F.getParent();
if (F.getMetadata("kernel_arg_access_qual") &&
F.getMetadata("pocl_generated") == nullptr)
return true;
NamedMDNode *kernels = m->getNamedMetadata("opencl.kernels");
if (kernels == NULL) {
std::string KernelName;
getModuleStringMetadata(*m, "KernelName", KernelName);
if (KernelName == "")
return true;
if (F.getName().str() == KernelName)
return true;
return false;
}
for (unsigned i = 0, e = kernels->getNumOperands(); i != e; ++i) {
if (kernels->getOperand(i)->getOperand(0) == NULL)
continue; // globaldce might have removed uncalled kernels
Function *k =
cast<Function>(
dyn_cast<ValueAsMetadata>(kernels->getOperand(i)->getOperand(0))
->getValue());
if (&F == k)
return true;
}
return false;
}
// Returns true in case the given function is a kernel with work-group
// barriers inside it.
bool
Workgroup::hasWorkgroupBarriers(const Function &F)
{
for (llvm::Function::const_iterator i = F.begin(), e = F.end();
i != e; ++i) {
const llvm::BasicBlock* bb = &*i;
if (Barrier::hasBarrier(bb)) {
// Ignore the implicit entry and exit barriers.
if (Barrier::hasOnlyBarrier(bb) && bb == &F.getEntryBlock())
continue;
if (Barrier::hasOnlyBarrier(bb) &&
bb->getTerminator()->getNumSuccessors() == 0)
continue;
return true;
}
}
return false;
}
|
#include <iostream>
#include "tbb/tbb.h"
#define RADIUS 3
#define NELEMENTS 1048576
int main(void) {
int * h_in, *h_out;
size_t bytes = NELEMENTS*sizeof(int);
h_in = (int*)malloc(bytes);
h_out = (int*)malloc(bytes);
//initialization
for( int i = 0; i < NELEMENTS; i++ ) {
h_in[i] = 1;
}
//Applying the stencil
tbb::tick_count t0 = tbb::tick_count::now();
tbb::parallel_for(0, NELEMENTS, 1, [=](int i){
for(int j = -RADIUS; j <= RADIUS; j++){
h_out[i] += (i+j < 0) || (i+j >= NELEMENTS) ? 0 : h_in[i+j];
}
});
tbb::tick_count t1 = tbb::tick_count::now();
printf("time for action = %g seconds\n", (t1-t0).seconds() );
//print/check
//for(int j=0; j < NELEMENTS; j++){
// std::cout << "h_out[" << j << "]= " << h_out[j] << "\n";
//}
free(h_in);
free(h_out);
return 0;
}
|
#ifndef WSM_IMPL_HPP
#define WSM_IMPL_HPP
#include "util/scream_utils.hpp"
#include "scream_assert.hpp"
#include <map>
namespace scream {
/*
* An implementation header for wsm.hpp, this helps keep wsm.hpp clean by avoiding
* mixing interface and implementation. Clients should NOT ever include this file.
*/
template <typename T, typename D>
WorkspaceManager<T, D>::WorkspaceManager(int size, int max_used, TeamPolicy policy) :
m_tu(policy),
m_concurrent_teams(m_tu.get_num_concurrent_teams()),
m_reserve( (sizeof(T) > 2*sizeof(int)) ? 1 :
(2*sizeof(int) + sizeof(T) - 1)/sizeof(T) ),
m_size(size),
m_total(m_size + m_reserve),
m_max_used(max_used),
#ifndef NDEBUG
m_num_used("Workspace.m_num_used", m_concurrent_teams),
m_high_water("Workspace.m_high_water", m_concurrent_teams),
m_active("Workspace.m_active", m_concurrent_teams, m_max_used),
m_curr_names("Workspace.m_curr_names", m_concurrent_teams, m_max_used, m_max_name_len),
m_all_names("Workspace.m_all_names", m_concurrent_teams, m_max_names, m_max_name_len),
// A name's index in m_all_names is used to index into m_counts
m_counts("Workspace.m_counts", m_concurrent_teams, m_max_names, 2),
#endif
m_next_slot("Workspace.m_next_slot", m_pad_factor*m_concurrent_teams),
m_data(Kokkos::ViewAllocateWithoutInitializing("Workspace.m_data"),
m_concurrent_teams, m_total * m_max_used)
{
init(*this, m_data, m_concurrent_teams, m_max_used, m_total);
}
template <typename T, typename D>
void WorkspaceManager<T, D>::report() const
{
#ifndef NDEBUG
auto host_num_used = Kokkos::create_mirror_view(m_num_used);
auto host_high_water = Kokkos::create_mirror_view(m_high_water);
auto host_all_names = Kokkos::create_mirror_view(m_all_names);
auto host_counts = Kokkos::create_mirror_view(m_counts);
std::cout << "\nWS usage (capped at " << m_max_used << "): " << std::endl;
for (int t = 0; t < m_concurrent_teams; ++t) {
std::cout << "WS " << t << " currently using " << host_num_used(t) << std::endl;
std::cout << "WS " << t << " high-water " << host_high_water(t) << std::endl;
}
std::cout << "\nWS deep analysis" << std::endl;
struct Data {
int used, takes, releases;
Data (int u, int t, int r) : used(u), takes(t), releases(r) {}
};
std::map<std::string, Data> ws_usage_map;
for (int t = 0; t < m_concurrent_teams; ++t) {
std::cout << " For wsidx " << t << std::endl;
for (int n = 0; n < m_max_names; ++n) {
const char* name = &(host_all_names(t, n, 0));
if (util::strcmp(name, "") == 0) {
break;
}
else {
const int takes = host_counts(t, n, 0);
const int releases = host_counts(t, n, 1);
std::cout << " workspace '" << name << "' was taken " << takes
<< " times and released " << releases << " times" << std::endl;
if (takes != releases) {
std::cout << " POSSIBLE LEAK" << std::endl;
}
std::string sname(name);
if (ws_usage_map.find(sname) == ws_usage_map.end()) {
ws_usage_map[sname] = Data(1, takes, releases);
}
else {
auto& e = ws_usage_map[sname];
e.used += 1;
e.takes += takes;
e.releases += releases;
}
}
}
}
std::cout << "\nWS workspace summary" << std::endl;
for (auto& kv : ws_usage_map) {
auto data = kv.second;
std::cout << "Workspace '" << kv.first << "' was used by " << data.used << " wsindices with "
<< data.takes << " takes and " << data.releases << " releases." << std::endl;
}
#endif
}
template <typename T, typename D>
KOKKOS_INLINE_FUNCTION
typename WorkspaceManager<T, D>::Workspace
WorkspaceManager<T, D>::get_workspace(const MemberType& team) const
{ return Workspace(*this, m_tu.get_workspace_idx(team), team); }
template <typename T, typename D>
void WorkspaceManager<T, D>::init(const WorkspaceManager<T, D>& wm, const view_2d<T>& data,
const int concurrent_teams, const int max_used, const int total)
{
Kokkos::parallel_for(
"WorkspaceManager ctor",
util::ExeSpaceUtils<ExeSpace>::get_default_team_policy(concurrent_teams, max_used),
KOKKOS_LAMBDA(const MemberType& team) {
Kokkos::parallel_for(
Kokkos::TeamThreadRange(team, max_used), [&] (int i) {
wm.init_metadata(team.league_rank(), i);
});
});
}
template <typename T, typename D>
template <typename S>
KOKKOS_FORCEINLINE_FUNCTION
int WorkspaceManager<T, D>::set_next_and_get_index(const ko::Unmanaged<view_1d<S> >& space, int next) const
{
const auto metadata = reinterpret_cast<int*>(reinterpret_cast<T*>(space.data()) - m_reserve);
metadata[1] = next;
return metadata[0];
}
template <typename T, typename D>
template <typename S>
KOKKOS_FORCEINLINE_FUNCTION
ko::Unmanaged<typename WorkspaceManager<T, D>::template view_1d<S> >
WorkspaceManager<T, D>::get_space_in_slot(const int team_idx, const int slot) const
{
return ko::Unmanaged<view_1d<S> >(
reinterpret_cast<S*>(&m_data(team_idx, slot*m_total) + m_reserve),
sizeof(T) == sizeof(S) ?
m_size :
(m_size*sizeof(T))/sizeof(S));
}
template <typename T, typename D>
KOKKOS_INLINE_FUNCTION
void WorkspaceManager<T, D>::init_metadata(const int ws_idx, const int slot) const
{
int* const metadata = reinterpret_cast<int*>(&m_data(ws_idx, slot*m_total));
metadata[0] = slot; // idx
metadata[1] = slot + 1; // next
}
template <typename T, typename D>
KOKKOS_INLINE_FUNCTION
WorkspaceManager<T, D>::Workspace::Workspace(
const WorkspaceManager& parent, int ws_idx, const MemberType& team) :
m_parent(parent), m_team(team), m_ws_idx(ws_idx),
m_next_slot(parent.m_next_slot(m_pad_factor*ws_idx))
{}
template <typename T, typename D>
template <typename S>
KOKKOS_INLINE_FUNCTION
ko::Unmanaged<typename WorkspaceManager<T, D>::template view_1d<S> > WorkspaceManager<T, D>::Workspace::take(
const char* name) const
{
#ifndef NDEBUG
change_num_used(1);
#endif
const auto space = m_parent.get_space_in_slot<S>(m_ws_idx, m_next_slot);
// We need a barrier here so get_space_in_slot returns consistent results
// w/in the team.
m_team.team_barrier();
Kokkos::single(Kokkos::PerTeam(m_team), [&] () {
m_next_slot = m_parent.get_next<S>(space);
#ifndef NDEBUG
change_indv_meta<S>(space, name);
#endif
});
// We need a barrier here so that a subsequent call to take or release
// starts with the metadata in the correct state.
m_team.team_barrier();
return space;
}
template <typename T, typename D>
template <size_t N, typename S>
KOKKOS_INLINE_FUNCTION
void WorkspaceManager<T, D>::Workspace::take_many_contiguous_unsafe(
const Kokkos::Array<const char*, N>& names,
const view_1d_ptr_array<S, N>& ptrs) const
{
#ifndef NDEBUG
change_num_used(N);
// Verify contiguous
for (int n = 0; n < static_cast<int>(N); ++n) {
const auto space = m_parent.get_space_in_slot<S>(m_ws_idx, m_next_slot + n);
scream_kassert(m_parent.get_next<S>(space) == m_next_slot + n + 1);
}
#endif
for (int n = 0; n < static_cast<int>(N); ++n) {
const auto space = m_parent.get_space_in_slot<S>(m_ws_idx, m_next_slot+n);
*ptrs[n] = space;
}
// We need a barrier here so get_space_in_slot above returns consistent results
// w/in the team.
m_team.team_barrier();
Kokkos::single(Kokkos::PerTeam(m_team), [&] () {
m_next_slot += N;
#ifndef NDEBUG
for (int n = 0; n < static_cast<int>(N); ++n) {
change_indv_meta<S>(*ptrs[n], names[n]);
}
#endif
});
// We need a barrier here so that a subsequent call to take or release
// starts with the metadata in the correct state.
m_team.team_barrier();
}
template <typename T, typename D>
template <size_t N, typename S>
KOKKOS_INLINE_FUNCTION
void WorkspaceManager<T, D>::Workspace::take_many(
const Kokkos::Array<const char*, N>& names,
const view_1d_ptr_array<S, N>& ptrs) const
{
#ifndef NDEBUG
change_num_used(N);
#endif
int next_slot = m_next_slot;
for (int n = 0; n < static_cast<int>(N); ++n) {
auto& space = *ptrs[n];
space = m_parent.get_space_in_slot<S>(m_ws_idx, next_slot);
next_slot = m_parent.get_next<S>(space);
}
// We need a barrier here so get_space_in_slot above returns consistent results
// w/in the team.
m_team.team_barrier();
Kokkos::single(Kokkos::PerTeam(m_team), [&] () {
m_next_slot = next_slot;
#ifndef NDEBUG
for (int n = 0; n < static_cast<int>(N); ++n) {
change_indv_meta<S>(*ptrs[n], names[n]);
}
#endif
});
// We need a barrier here so that a subsequent call to take or release
// starts with the metadata in the correct state.
m_team.team_barrier();
}
template <typename T, typename D>
template <size_t N, typename S>
KOKKOS_INLINE_FUNCTION
void WorkspaceManager<T, D>::Workspace::take_many_and_reset(
const Kokkos::Array<const char*, N>& names,
const view_1d_ptr_array<S, N>& ptrs) const
{
#ifndef NDEBUG
change_num_used(N - m_parent.m_num_used(m_ws_idx));
#endif
for (int n = 0; n < static_cast<int>(N); ++n) {
const auto space = m_parent.get_space_in_slot<S>(m_ws_idx, n);
*ptrs[n] = space;
}
// We only need to reset the metadata for spaces that are being left free
Kokkos::parallel_for(
Kokkos::TeamThreadRange(m_team, m_parent.m_max_used - N), [&] (int i) {
m_parent.init_metadata(m_ws_idx, i+N);
});
Kokkos::single(Kokkos::PerTeam(m_team), [&] () {
m_next_slot = N;
#ifndef NDEBUG
// Mark all old spaces as released
for (int a = 0; a < m_parent.m_max_used; ++a) {
if (m_parent.m_active(m_ws_idx, a)) {
change_indv_meta<S>(m_parent.get_space_in_slot<S>(m_ws_idx, a), "", true);
}
}
// Mark all new spaces as taken
for (int n = 0; n < static_cast<int>(N); ++n) {
change_indv_meta<S>(*ptrs[n], names[n]);
}
#endif
});
// We need a barrier here so that a subsequent call to take or release
// starts with the metadata in the correct state.
m_team.team_barrier();
}
template <typename T, typename D>
KOKKOS_INLINE_FUNCTION
void WorkspaceManager<T, D>::Workspace::reset() const
{
m_team.team_barrier();
#ifndef NDEBUG
change_num_used(-m_parent.m_num_used(m_ws_idx));
#endif
m_next_slot = 0;
Kokkos::parallel_for(
Kokkos::TeamThreadRange(m_team, m_parent.m_max_used), [&] (int i) {
m_parent.init_metadata(m_ws_idx, i);
});
#ifndef NDEBUG
Kokkos::single(Kokkos::PerTeam(m_team), [&] () {
// Mark all old spaces as released
for (int a = 0; a < m_parent.m_max_used; ++a) {
if (m_parent.m_active(m_ws_idx, a)) {
change_indv_meta<T>(m_parent.get_space_in_slot<T>(m_ws_idx, a), "", true);
}
}
});
#endif
m_team.team_barrier();
}
// Print the linked list. Obviously not a device function.
template <typename T, typename D>
void WorkspaceManager<T, D>::Workspace::print() const
{
m_team.team_barrier();
Kokkos::single(
Kokkos::PerTeam(m_team), [&] () {
std::stringstream ss;
ss << m_ws_idx << ":";
auto space = m_parent.get_space_in_slot<T>(m_ws_idx, m_next_slot);
for (int cnt = 0, nmax = m_parent.m_max_used;
cnt < nmax;
++cnt) {
ss << " (" << m_parent.get_index<T>(space) << ", "
<< m_parent.get_next<T>(space) << ")";
space = m_parent.get_space_in_slot<T>(m_ws_idx, m_parent.get_next<T>(space));
}
ss << "\n";
std::cout << ss.str();
});
}
#ifndef NDEBUG
template <typename T, typename D>
template <typename S>
KOKKOS_INLINE_FUNCTION
const char* WorkspaceManager<T, D>::Workspace::get_name_impl(const ko::Unmanaged<view_1d<S> >& space) const
{
const int slot = m_parent.get_index<S>(space);
return &(m_parent.m_curr_names(m_ws_idx, slot, 0));
}
template <typename T, typename D>
KOKKOS_INLINE_FUNCTION
void WorkspaceManager<T, D>::Workspace::change_num_used(int change_by) const
{
Kokkos::single(Kokkos::PerTeam(m_team), [&] () {
int curr_used = m_parent.m_num_used(m_ws_idx) += change_by;
scream_kassert(curr_used <= m_parent.m_max_used);
scream_kassert(curr_used >= 0);
if (curr_used > m_parent.m_high_water(m_ws_idx)) {
m_parent.m_high_water(m_ws_idx) = curr_used;
}
});
}
template <typename T, typename D>
template <typename S>
KOKKOS_INLINE_FUNCTION
void WorkspaceManager<T, D>::Workspace::change_indv_meta(
const ko::Unmanaged<view_1d<S> >& space, const char* name, bool release) const
{
Kokkos::single(Kokkos::PerTeam(m_team), [&] () {
const int slot = m_parent.get_index<S>(space);
if (!release) {
scream_kassert(util::strlen(name) < m_max_name_len); // leave one char for null terminator
scream_kassert(util::strlen(name) > 0);
scream_kassert(!m_parent.m_active(m_ws_idx, slot));
char* val = &(m_parent.m_curr_names(m_ws_idx, slot, 0));
util::strcpy(val, name);
}
else {
scream_kassert(m_parent.m_active(m_ws_idx, slot));
name = get_name(space);
}
const int name_idx = get_name_idx(name, !release);
const int count_idx = release ? 1 : 0;
m_parent.m_counts(m_ws_idx, name_idx, count_idx) += 1;
m_parent.m_active(m_ws_idx, slot) = !release;
});
}
template <typename T, typename D>
KOKKOS_INLINE_FUNCTION
int WorkspaceManager<T, D>::Workspace::get_name_idx(const char* name, bool add) const
{
int name_idx = -1;
for (int n = 0; n < m_max_names; ++n) {
char* old_name = &(m_parent.m_all_names(m_ws_idx, n, 0));
if (util::strcmp(old_name, name) == 0) {
name_idx = n;
break;
}
else if (add && util::strcmp(old_name, "") == 0) {
util::strcpy(old_name, name);
name_idx = n;
break;
}
}
scream_kassert(name_idx != -1);
return name_idx;
}
#endif
template <typename T, typename D>
template <typename S>
KOKKOS_INLINE_FUNCTION
void WorkspaceManager<T, D>::Workspace::release_impl(const ko::Unmanaged<view_1d<S> >& space) const
{
#ifndef NDEBUG
change_num_used(-1);
change_indv_meta<S>(space, "", true);
#endif
// We don't need a barrier before this block b/c it's OK for metadata to
// change while some threads in the team are still using the bulk data.
Kokkos::single(Kokkos::PerTeam(m_team), [&] () {
m_next_slot = m_parent.set_next_and_get_index<S>(space, m_next_slot);
});
m_team.team_barrier();
}
} // namespace scream
#endif
|
// Copyright (C) 2014-2017 Bayerische Motoren Werke Aktiengesellschaft (BMW AG)
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include <vsomeip/constants.hpp>
#include <vsomeip/internal/logger.hpp>
#include "../include/channel_impl.hpp"
#include "../include/connector_impl.hpp"
#include "../include/defines.hpp"
#include "../../configuration/include/trace.hpp"
#include "../../utility/include/byteorder.hpp"
namespace vsomeip_v3 {
namespace trace {
const char *VSOMEIP_TC_DEFAULT_CHANNEL_ID = "TC";
std::shared_ptr<connector_impl> connector_impl::get() {
static std::shared_ptr<connector_impl> instance = std::make_shared<connector_impl>();
return instance;
}
connector_impl::connector_impl() :
is_enabled_(false),
is_sd_enabled_(false) {
channels_[VSOMEIP_TC_DEFAULT_CHANNEL_ID]
= std::make_shared<channel_impl>(VSOMEIP_TC_DEFAULT_CHANNEL_ID,
VSOMEIP_TC_DEFAULT_CHANNEL_NAME);
#ifdef USE_DLT
std::shared_ptr<DltContext> its_default_context
= std::make_shared<DltContext>();
contexts_[VSOMEIP_TC_DEFAULT_CHANNEL_ID] = its_default_context;
DLT_REGISTER_CONTEXT_LL_TS(*(its_default_context.get()),
VSOMEIP_TC_DEFAULT_CHANNEL_ID, VSOMEIP_TC_DEFAULT_CHANNEL_NAME,
DLT_LOG_INFO, DLT_TRACE_STATUS_ON);
#endif
}
connector_impl::~connector_impl() {
reset();
}
void connector_impl::configure(const std::shared_ptr<cfg::trace> &_configuration) {
if (_configuration) {
is_enabled_ = _configuration->is_enabled_;
is_sd_enabled_ = _configuration->is_sd_enabled_;
}
if (is_enabled_) { // No need to create filters if tracing is disabled!
for (auto &its_channel : _configuration->channels_) {
if (!add_channel(its_channel->id_, its_channel->name_)) {
VSOMEIP_ERROR << "Channel " << its_channel->id_
<< " has multiple definitions.";
}
}
for (auto &its_filter : _configuration->filters_) {
for (auto &its_channel : its_filter->channels_) {
std::shared_ptr<channel> its_channel_ptr = get_channel(its_channel);
if (its_channel_ptr) {
if (its_filter->is_range_) {
its_channel_ptr->add_filter(its_filter->matches_[0],
its_filter->matches_[1], its_filter->is_positive_);
} else {
its_channel_ptr->add_filter(its_filter->matches_,
its_filter->is_positive_);
}
}
}
}
}
VSOMEIP_INFO << "vsomeip tracing "
<< (is_enabled_ ? "enabled " : "not enabled. ")
<< ". vsomeip service discovery tracing "
<< (is_sd_enabled_ ? "enabled " : "not enabled. ");
}
void connector_impl::reset() {
#ifdef USE_DLT
std::lock_guard<std::mutex> its_contexts_lock(contexts_mutex_);
contexts_.clear();
#endif
// reset to default
std::lock_guard<std::mutex> its_lock_channels(channels_mutex_);
channels_.clear();
}
void connector_impl::set_enabled(const bool _enabled) {
is_enabled_ = _enabled;
}
bool connector_impl::is_enabled() const {
return is_enabled_;
}
void connector_impl::set_sd_enabled(const bool _sd_enabled) {
is_sd_enabled_ = _sd_enabled;
}
bool connector_impl::is_sd_enabled() const {
return is_sd_enabled_;
}
bool connector_impl::is_sd_message(const byte_t *_data, uint16_t _data_size) const {
if (VSOMEIP_METHOD_POS_MAX < _data_size) {
return (_data[VSOMEIP_SERVICE_POS_MIN] == 0xFF && _data[VSOMEIP_SERVICE_POS_MAX] == 0xFF &&
_data[VSOMEIP_METHOD_POS_MIN] == 0x81 && _data[VSOMEIP_METHOD_POS_MAX] == 0x00);
}
return false;
}
std::shared_ptr<channel> connector_impl::add_channel(
const trace_channel_t &_id, const std::string &_name) {
std::lock_guard<std::mutex> its_channels_lock(channels_mutex_);
// check whether we already know the requested channel
if (channels_.find(_id) != channels_.end())
return nullptr;
// create new channel
std::shared_ptr<channel_impl> its_channel
= std::make_shared<channel_impl>(_id, _name);
// add channel
channels_[_id] = its_channel;
// register context
#ifdef USE_DLT
std::lock_guard<std::mutex> its_contexts_lock(contexts_mutex_);
std::shared_ptr<DltContext> its_context = std::make_shared<DltContext>();
contexts_[_id] = its_context;
DLT_REGISTER_CONTEXT_LL_TS(*(its_context.get()), _id.c_str(), _name.c_str(),
DLT_LOG_INFO, DLT_TRACE_STATUS_ON);
#endif
return its_channel;
}
bool connector_impl::remove_channel(const trace_channel_t &_id) {
if (_id == VSOMEIP_TC_DEFAULT_CHANNEL_ID) {
// the default channel can not be removed
return false;
}
std::lock_guard<std::mutex> its_channels_lock(channels_mutex_);
bool has_removed = (channels_.erase(_id) == 1);
if (has_removed) {
// unregister context
#ifdef USE_DLT
std::lock_guard<std::mutex> its_contexts_lock(contexts_mutex_);
auto its_context = contexts_.find(_id);
if (its_context != contexts_.end()) {
DLT_UNREGISTER_CONTEXT(*(its_context->second.get()));
}
#endif
}
return true;
}
std::shared_ptr<channel> connector_impl::get_channel(const std::string &_id) const {
std::lock_guard<std::mutex> its_channels_lock(channels_mutex_);
auto its_channel = channels_.find(_id);
return (its_channel != channels_.end() ? its_channel->second : nullptr);
}
void connector_impl::trace(const byte_t *_header, uint16_t _header_size,
const byte_t *_data, uint16_t _data_size) {
#ifdef USE_DLT
if (!is_enabled_)
return;
if (_data_size == 0)
return; // no data
if (is_sd_message(_data, _data_size) && !is_sd_enabled_)
return; // tracing of service discovery messages is disabled!
service_t its_service = VSOMEIP_BYTES_TO_WORD(
_data[VSOMEIP_SERVICE_POS_MIN],
_data[VSOMEIP_SERVICE_POS_MAX]);
// Instance is not part of the SOME/IP header, read it from the trace
// header
instance_t its_instance = VSOMEIP_BYTES_TO_WORD(
_header[VSOMEIP_TC_INSTANCE_POS_MIN],
_header[VSOMEIP_TC_INSTANCE_POS_MAX]);
method_t its_method = VSOMEIP_BYTES_TO_WORD(
_data[VSOMEIP_METHOD_POS_MIN],
_data[VSOMEIP_METHOD_POS_MAX]);
// Forward to channel if the filter set of the channel allows
std::lock_guard<std::mutex> its_channels_lock(channels_mutex_);
std::lock_guard<std::mutex> its_contexts_lock(contexts_mutex_);
for (auto its_channel : channels_) {
if (its_channel.second->matches(its_service, its_instance, its_method)) {
auto its_context = contexts_.find(its_channel.second->get_id());
if (its_context != contexts_.end()) {
DLT_TRACE_NETWORK_SEGMENTED(*(its_context->second.get()),
DLT_NW_TRACE_IPC,
_header_size, static_cast<void *>(const_cast<byte_t *>(_header)),
_data_size, static_cast<void *>(const_cast<byte_t *>(_data)));
} else {
// This should never happen!
VSOMEIP_ERROR << "tracing: found channel without DLT context!";
}
}
}
#else
(void)_header;
(void)_header_size;
(void)_data;
(void)_data_size;
#endif
}
} // namespace trace
} // namespace vsomeip_v3
|
#include "client.h"
#include <iostream>
#include <boost/array.hpp>
#include <boost/asio.hpp>
#include "str_queue.h"
#include "player.h"
#include "playlist.h"
#include "mainwindow.h"
#include "controler.h"
#include "clientcontroler.h"
#include <QtWidgets/QApplication>
#include "keeper.h"
#include <sys/file.h>
#include <errno.h>
using boost::asio::ip::tcp;
int main(int arg, char* argv[]){
int pid_file = open("/var/run/SmallStreamer.pid", O_CREAT | O_RDWR, 0666);
int rc = flock(pid_file, LOCK_EX | LOCK_NB);
if(rc) {
if(EWOULDBLOCK == errno)
std::cout<<"another instance is running"<<std::endl;
}
else {
QApplication a(arg, argv);
PlayList* playlist=new PlayList();
for(int i=1; i<arg; i++){
playlist->addFile(argv[i]);
}
Controler::getControl().setPlayList(playlist);
Client client( true);
std::cout<<"Start"<<std::endl;
Keeper::getInstance().open();
client.start();
ClientControler::getControl().setClient(&client);
MainWindow w;
w.show();
a.exec();
client.stop();
// client.joinMainThread(); TODO This not working because client sleep on getSample() from Controler class and later it waits on his own loop
Keeper::getInstance().save();
}
return 0;
}
|
/*******************************************************************************
* Copyright (c) 2011, Jean-David Gadina - www.xs-labs.com
* Distributed under the Boost Software License, Version 1.0.
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
******************************************************************************/
/* $Id$ */
#include "MP4.STDP.h"
using namespace MP4;
STDP::STDP( void )
{
this->_type.append( "STDP" );
}
std::string STDP::getContent( void )
{
std::ostringstream o;
return o.str();
}
void STDP::processData( MP4::BinaryStream * stream, uint64_t length )
{
stream->ignore( length );
}
|
/*
* Copyright (c) 2019, Intel Corporation
*
* 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 copies 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 all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER 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 "MDF_FC_common_genx.h"
_GENX_MAIN_ void Y210_444DScale16_Buf_1_Rot_180(
CURBE_INPUT_OUTPUT,
GLOBAL_BUFFER_INPUT_OUTPUT)
{
#define BUFFER_1
#define ROTATE_180
#include "Y210_DScale_Buf.h"
#undef ROTATE_180
#undef BUFFER_1
}
|
//======================================================================================================================
// Project: OpenRGB - C++ SDK
//----------------------------------------------------------------------------------------------------------------------
// Author: Jan Broz (Youda008)
// Description: Representation of a color
//======================================================================================================================
#include "OpenRGB/Color.hpp"
#include "Essential.hpp"
#include "MiscUtils.hpp"
#include "StringUtils.hpp"
#include "BinaryStream.hpp"
using own::BinaryOutputStream;
using own::BinaryInputStream;
#include <cstdio>
#include <iostream>
#include <ios>
#include <iomanip>
#include <string>
#include <unordered_map>
namespace orgb {
//======================================================================================================================
// Color
const Color Color::Black (0x00, 0x00, 0x00);
const Color Color::White (0xFF, 0xFF, 0xFF);
const Color Color::Red (0xFF, 0x00, 0x00);
const Color Color::Green (0x00, 0xFF, 0x00);
const Color Color::Blue (0x00, 0x00, 0xFF);
const Color Color::Yellow (0xFF, 0xFF, 0x00);
const Color Color::Magenta (0xFF, 0x00, 0xFF);
const Color Color::Cyan (0x00, 0xFF, 0xFF);
static const std::unordered_map< std::string, Color > colorNames =
{
{ "black", Color::Black },
{ "white", Color::White },
{ "red", Color::Red },
{ "green", Color::Green },
{ "blue", Color::Blue },
{ "yellow", Color::Yellow },
{ "magenta", Color::Magenta },
{ "cyan", Color::Cyan },
};
bool Color::fromString( const std::string & str ) noexcept
{
if (str.empty())
return false;
uint red, green, blue;
if (str[0] == '#' && sscanf( str.c_str() + 1, "%02x%02x%02x", &red, &green, &blue ) == 3)
{
r = uint8_t( red );
g = uint8_t( green );
b = uint8_t( blue );
return true;
}
else if (sscanf( str.c_str(), "%02x%02x%02x", &red, &green, &blue ) == 3)
{
r = uint8_t( red );
g = uint8_t( green );
b = uint8_t( blue );
return true;
}
else
{
std::string strLower = own::to_lower( str );
auto colorIter = colorNames.find( strLower );
if (colorIter != colorNames.end())
{
*this = colorIter->second;
return true;
}
}
return false;
}
BinaryOutputStream & operator<<( BinaryOutputStream & stream, Color color )
{
stream << color.r << color.g << color.b << color.padding;
return stream;
}
BinaryInputStream & operator>>( BinaryInputStream & stream, Color & color ) noexcept
{
stream >> color.r >> color.g >> color.b >> color.padding;
return stream;
}
std::ostream & operator<<( std::ostream & os, Color color ) noexcept
{
std::ios_base::fmtflags origFlags( os.flags() );
os << std::uppercase << std::hex << std::setfill('0');
os << '#' << std::setw(2) << uint(color.r) << std::setw(2) << uint(color.g) << std::setw(2) << uint(color.b);
os.flags( origFlags );
return os;
}
std::istream & operator>>( std::istream & is, Color & color ) noexcept
{
std::string colorStr;
is >> colorStr;
if (!color.fromString( colorStr ))
{
is.setstate( std::ios::failbit );
}
return is;
}
void print( Color color )
{
printf( "#%02X%02X%02X", uint(color.r), uint(color.g), uint(color.b) );
}
//======================================================================================================================
} // namespace orgb
|
// Copyright 2016 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*
* The implementation of the OutputJar methods.
*/
#include "src/tools/singlejar/output_jar.h"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <time.h>
#ifndef _WIN32
#include <unistd.h>
#else
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif // WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif // _WIN32
#include "src/main/cpp/util/path_platform.h"
#include "src/tools/singlejar/combiners.h"
#include "src/tools/singlejar/diag.h"
#include "src/tools/singlejar/input_jar.h"
#include "src/tools/singlejar/mapped_file.h"
#include "src/tools/singlejar/options.h"
#include "src/tools/singlejar/zip_headers.h"
#include <zlib.h>
#define TODO(cond, msg) \
if (!(cond)) { \
diag_errx(2, "%s:%d: TODO(asmundak): " msg, __FILE__, __LINE__); \
}
OutputJar::OutputJar()
: options_(nullptr),
file_(nullptr),
outpos_(0),
buffer_(nullptr),
entries_(0),
duplicate_entries_(0),
cen_(nullptr),
cen_size_(0),
cen_capacity_(0),
spring_handlers_("META-INF/spring.handlers"),
spring_schemas_("META-INF/spring.schemas"),
protobuf_meta_handler_("protobuf.meta", false),
manifest_("META-INF/MANIFEST.MF"),
build_properties_("build-data.properties") {
known_members_.emplace(spring_handlers_.filename(),
EntryInfo{&spring_handlers_});
known_members_.emplace(spring_schemas_.filename(),
EntryInfo{&spring_schemas_});
known_members_.emplace(manifest_.filename(), EntryInfo{&manifest_});
known_members_.emplace(protobuf_meta_handler_.filename(),
EntryInfo{&protobuf_meta_handler_});
manifest_.Append(
"Manifest-Version: 1.0\r\n"
"Created-By: singlejar\r\n");
}
static std::string Basename(const std::string &path) {
size_t pos = path.rfind('/');
if (pos == std::string::npos) {
return path;
} else {
return std::string(path, pos + 1);
}
}
int OutputJar::Doit(Options *options) {
if (nullptr != options_) {
diag_errx(1, "%s:%d: Doit() can be called only once.", __FILE__, __LINE__);
}
options_ = options;
// Register the handler for the build-data.properties file unless
// --exclude_build_data is present. Otherwise we do not generate this file,
// and it will be copied from the first source archive containing it.
if (!options_->exclude_build_data) {
known_members_.emplace(build_properties_.filename(),
EntryInfo{&build_properties_});
}
// TODO(b/28294322): do we need to resolve the path to be absolute or
// canonical?
build_properties_.AddProperty("build.target", options_->output_jar.c_str());
if (options_->verbose) {
fprintf(stderr, "combined_file_name=%s\n", options_->output_jar.c_str());
if (!options_->main_class.empty()) {
fprintf(stderr, "main_class=%s\n", options_->main_class.c_str());
}
if (!options_->java_launcher.empty()) {
fprintf(stderr, "java_launcher_file=%s\n",
options_->java_launcher.c_str());
}
fprintf(stderr, "%zu source files\n", options_->input_jars.size());
fprintf(stderr, "%zu manifest lines\n", options_->manifest_lines.size());
}
if (!Open()) {
exit(1);
}
// Copy launcher if it is set.
if (!options_->java_launcher.empty()) {
AppendFile(options_, options_->java_launcher.c_str());
}
if (!options_->main_class.empty()) {
build_properties_.AddProperty("main.class", options_->main_class);
manifest_.Append("Main-Class: ");
manifest_.Append(options_->main_class);
manifest_.Append("\r\n");
}
// Copy CDS archive file (.jsa) if it is set.
if (!options_->cds_archive.empty()) {
AppendCDSArchive(options->cds_archive);
}
for (auto &manifest_line : options_->manifest_lines) {
if (!manifest_line.empty()) {
manifest_.Append(manifest_line);
if (manifest_line[manifest_line.size() - 1] != '\n') {
manifest_.Append("\r\n");
}
}
}
for (auto &build_info_line : options_->build_info_lines) {
build_properties_.Append(build_info_line);
build_properties_.Append("\n");
}
for (auto &build_info_file : options_->build_info_files) {
MappedFile mapped_file;
if (!mapped_file.Open(build_info_file)) {
diag_err(1, "%s:%d: Bad build info file %s", __FILE__, __LINE__,
build_info_file.c_str());
}
const char *data = reinterpret_cast<const char *>(mapped_file.start());
const char *data_end = reinterpret_cast<const char *>(mapped_file.end());
// TODO(asmundak): this isn't right, we should parse properties file.
while (data < data_end) {
const char *next_data = strchr(static_cast<const char *>(data), '\n');
if (next_data) {
++next_data;
} else {
next_data = data_end;
}
build_properties_.Append(data, next_data - data);
data = next_data;
}
mapped_file.Close();
}
for (auto &rpath : options_->classpath_resources) {
ClasspathResource(Basename(rpath), rpath);
}
for (auto &rdesc : options_->resources) {
// A resource description is either NAME or PATH:NAME
// Find the last ':' instead of the first because Windows uses ':' as volume
// separator in absolute path.
std::size_t colon = rdesc.find_last_of(':');
if (0 == colon) {
diag_errx(1, "%s:%d: Bad resource description %s", __FILE__, __LINE__,
rdesc.c_str());
}
bool shouldSplit = colon != std::string::npos;
#ifdef _WIN32
// If colon points to volume separator, don't split.
if (colon == 1 && blaze_util::IsAbsolute(rdesc)) {
shouldSplit = false;
}
#endif
if (shouldSplit) {
ClasspathResource(rdesc.substr(colon + 1), rdesc.substr(0, colon));
} else {
ClasspathResource(rdesc, rdesc);
}
}
// Ready to write zip entries. Decide whether created entries should be
// compressed.
bool compress = options_->force_compression || options_->preserve_compression;
// Write a directory entry for the META-INF
WriteMetaInf();
// Write the build properties file.
if (!options_->exclude_build_data) {
WriteEntry(build_properties_.OutputEntry(compress));
}
// Write classpath resources.
for (auto &classpath_resource : classpath_resources_) {
bool do_compress = compress;
if (do_compress && !options_->nocompress_suffixes.empty()) {
for (auto &suffix : options_->nocompress_suffixes) {
auto entry_name = classpath_resource->filename();
if (entry_name.length() >= suffix.size() &&
!entry_name.compare(entry_name.length() - suffix.size(),
suffix.size(), suffix)) {
do_compress = false;
break;
}
}
}
// Add parent directory entries.
size_t pos = classpath_resource->filename().find('/');
while (pos != std::string::npos) {
std::string dir(classpath_resource->filename(), 0, pos + 1);
if (NewEntry(dir)) {
WriteDirEntry(dir, nullptr, 0);
}
pos = classpath_resource->filename().find('/', pos + 1);
}
WriteEntry(classpath_resource->OutputEntry(do_compress));
}
// Copy source files' contents.
for (size_t ix = 0; ix < options_->input_jars.size(); ++ix) {
if (!AddJar(ix)) {
exit(1);
}
}
// Write the manifest file
WriteEntry(manifest_.OutputEntry(compress));
// All entries written, write Central Directory and close.
Close();
return 0;
}
OutputJar::~OutputJar() {
if (file_) {
diag_warnx("%s:%d: Close() should be called first", __FILE__, __LINE__);
}
}
// Try to perform I/O in units of this size.
// (128KB is the default max request size for fuse filesystems.)
static constexpr size_t kBufferSize = 128 << 10;
bool OutputJar::Open() {
if (file_) {
diag_errx(1, "%s:%d: Cannot open output archive twice", __FILE__, __LINE__);
}
int mode = O_CREAT | O_WRONLY | O_TRUNC;
#ifdef _WIN32
std::wstring wpath;
std::string error;
if (!blaze_util::AsAbsoluteWindowsPath(path(), &wpath, &error)) {
diag_warn("%s:%d: AsAbsoluteWindowsPath failed: %s", __FILE__, __LINE__,
error.c_str());
return false;
}
HANDLE hFile =
CreateFileW(wpath.c_str(), GENERIC_READ | GENERIC_WRITE,
// Must share for reading, otherwise
// symlink-following file existence checks (e.g.
// java.nio.file.Files.exists()) fail.
FILE_SHARE_READ, nullptr, CREATE_ALWAYS, 0, nullptr);
if (hFile == INVALID_HANDLE_VALUE) {
diag_warn("%s:%d: CreateFileW failed for %S", __FILE__, __LINE__,
wpath.c_str());
return false;
}
// Make sure output file is in binary mode, or \r\n will be converted to \n.
mode |= _O_BINARY;
int fd = _open_osfhandle(reinterpret_cast<intptr_t>(hFile), mode);
#else
// Set execute bits since we may produce an executable output file.
int fd = open(path(), mode, 0777);
#endif
if (fd < 0) {
diag_warn("%s:%d: %s", __FILE__, __LINE__, path());
return false;
}
file_ = fdopen(fd, "w");
if (file_ == nullptr) {
diag_warn("%s:%d: fdopen of %s", __FILE__, __LINE__, path());
close(fd);
return false;
}
outpos_ = 0;
buffer_.reset(new char[kBufferSize]);
setvbuf(file_, buffer_.get(), _IOFBF, kBufferSize);
if (options_->verbose) {
fprintf(stderr, "Writing to %s\n", path());
}
return true;
}
// January 1, 2010 as a DOS date
static const uint16_t kDefaultDate = 30 << 9 | 1 << 5 | 1;
bool OutputJar::AddJar(int jar_path_index) {
const std::string &input_jar_path =
options_->input_jars[jar_path_index].first;
const std::string &input_jar_aux_label =
options_->input_jars[jar_path_index].second;
InputJar input_jar;
if (!input_jar.Open(input_jar_path)) {
return false;
}
const CDH *jar_entry;
const LH *lh;
while ((jar_entry = input_jar.NextEntry(&lh))) {
const char *file_name = jar_entry->file_name();
auto file_name_length = jar_entry->file_name_length();
if (!file_name_length) {
diag_errx(
1, "%s:%d: Bad central directory record in %s at offset 0x%" PRIx64,
__FILE__, __LINE__, input_jar_path.c_str(),
input_jar.CentralDirectoryRecordOffset(jar_entry));
}
// Special files that cannot be handled by looking up known_members_ map:
// * ignore *.SF, *.RSA, *.DSA
// (TODO(asmundak): should this be done only in META-INF?
//
if (ends_with(file_name, file_name_length, ".SF") ||
ends_with(file_name, file_name_length, ".RSA") ||
ends_with(file_name, file_name_length, ".DSA")) {
continue;
}
bool include_entry = true;
if (!options_->include_prefixes.empty()) {
for (auto &prefix : options_->include_prefixes) {
if ((include_entry =
(prefix.size() <= file_name_length &&
0 == strncmp(file_name, prefix.c_str(), prefix.size())))) {
break;
}
}
}
if (!include_entry) {
continue;
}
bool is_file = (file_name[file_name_length - 1] != '/');
if (is_file &&
begins_with(file_name, file_name_length, "META-INF/services/")) {
// The contents of the META-INF/services/<SERVICE> on the output is the
// concatenation of the META-INF/services/<SERVICE> files from all inputs.
std::string service_path(file_name, file_name_length);
if (NewEntry(service_path)) {
// Create a concatenator and add it to the known_members_ map.
// The call to Merge() below will then take care of the rest.
Concatenator *service_handler = new Concatenator(service_path);
service_handlers_.emplace_back(service_handler);
known_members_.emplace(service_path, EntryInfo{service_handler});
}
} else {
ExtraHandler(input_jar_path, jar_entry, &input_jar_aux_label);
}
if (options_->check_desugar_deps &&
begins_with(file_name, file_name_length, "j$/")) {
diag_errx(1, "%s:%d: desugar_jdk_libs file %.*s unexpectedly found in %s",
__FILE__, __LINE__, file_name_length, file_name,
input_jar_path.c_str());
}
// Install a new entry unless it is already present. All the plain (non-dir)
// entries that require a combiner have been already installed, so the call
// will add either a directory entry whose handler will ignore subsequent
// duplicates, or an ordinary plain entry, for which we save the index of
// the first input jar (in order to provide diagnostics on duplicate).
auto got =
known_members_.emplace(std::string(file_name, file_name_length),
EntryInfo{is_file ? nullptr : &null_combiner_,
is_file ? jar_path_index : -1});
if (!got.second) {
auto &entry_info = got.first->second;
// Handle special entries (the ones that have a combiner).
if (entry_info.combiner_ != nullptr) {
// TODO(kmb,asmundak): Should be checking Merge() return value but fails
// for build-data.properties when merging deploy jars into deploy jars.
entry_info.combiner_->Merge(jar_entry, lh);
continue;
}
// Plain file entry. If duplicates are not allowed, bail out. Otherwise
// just ignore this entry.
if (options_->no_duplicates ||
(options_->no_duplicate_classes &&
ends_with(file_name, file_name_length, ".class"))) {
diag_errx(
1, "%s:%d: %.*s is present both in %s and %s", __FILE__, __LINE__,
file_name_length, file_name,
options_->input_jars[entry_info.input_jar_index_].first.c_str(),
input_jar_path.c_str());
} else {
duplicate_entries_++;
continue;
}
}
// Add any missing parent directory entries (first) if requested.
if (options_->add_missing_directories) {
// Ignore very last character in case this entry is a directory itself.
for (size_t pos = 0; pos < static_cast<size_t>(file_name_length - 1);
++pos) {
if (file_name[pos] == '/') {
std::string dir(file_name, 0, pos + 1);
if (NewEntry(dir)) {
WriteDirEntry(dir, nullptr, 0);
}
}
}
}
// For the file entries, decide whether output should be compressed.
if (is_file) {
bool input_compressed =
jar_entry->compression_method() != Z_NO_COMPRESSION;
bool output_compressed =
options_->force_compression ||
(options_->preserve_compression && input_compressed);
if (output_compressed && !options_->nocompress_suffixes.empty()) {
for (auto &suffix : options_->nocompress_suffixes) {
if (file_name_length >= suffix.size() &&
!strncmp(file_name + file_name_length - suffix.size(),
suffix.c_str(), suffix.size())) {
output_compressed = false;
break;
}
}
}
if (input_compressed != output_compressed) {
Concatenator combiner(jar_entry->file_name_string());
if (!combiner.Merge(jar_entry, lh)) {
diag_err(1, "%s:%d: cannot add %.*s", __FILE__, __LINE__,
jar_entry->file_name_length(), jar_entry->file_name());
}
WriteEntry(combiner.OutputEntry(output_compressed));
continue;
}
}
// Now we have to copy:
// local header
// file data
// data descriptor, if present.
off64_t copy_from = jar_entry->local_header_offset();
size_t num_bytes = lh->size();
if (jar_entry->no_size_in_local_header()) {
const DDR *ddr = reinterpret_cast<const DDR *>(
lh->data() + jar_entry->compressed_file_size());
num_bytes +=
jar_entry->compressed_file_size() +
ddr->size(
ziph::zfield_has_ext64(jar_entry->compressed_file_size32()),
ziph::zfield_has_ext64(jar_entry->uncompressed_file_size32()));
} else {
num_bytes += lh->compressed_file_size();
}
off64_t local_header_offset = Position();
// When normalize_timestamps is set, entry's timestamp is to be set to
// 01/01/2010 00:00:00 (or to 01/01/2010 00:00:02, if an entry is a .class
// file). This is somewhat expensive because we have to copy the local
// header to memory as input jar is memory mapped as read-only. Try to copy
// as little as possible.
uint16_t normalized_time = 0;
const UnixTimeExtraField *lh_field_to_remove = nullptr;
bool fix_timestamp = false;
if (options_->normalize_timestamps) {
if (ends_with(file_name, file_name_length, ".class")) {
normalized_time = 1;
}
lh_field_to_remove = lh->unix_time_extra_field();
fix_timestamp = jar_entry->last_mod_file_date() != kDefaultDate ||
jar_entry->last_mod_file_time() != normalized_time ||
lh_field_to_remove != nullptr;
}
if (fix_timestamp) {
uint8_t lh_buffer[512];
size_t lh_size = lh->size();
LH *lh_new = lh_size > sizeof(lh_buffer)
? reinterpret_cast<LH *>(malloc(lh_size))
: reinterpret_cast<LH *>(lh_buffer);
// Remove Unix timestamp field.
if (lh_field_to_remove != nullptr) {
auto from_end = ziph::byte_ptr(lh) + lh->size();
size_t removed_size = lh_field_to_remove->size();
size_t chunk1_size =
ziph::byte_ptr(lh_field_to_remove) - ziph::byte_ptr(lh);
size_t chunk2_size = lh->size() - (chunk1_size + removed_size);
memcpy(lh_new, lh, chunk1_size);
if (chunk2_size) {
memcpy(reinterpret_cast<uint8_t *>(lh_new) + chunk1_size,
from_end - chunk2_size, chunk2_size);
}
lh_new->extra_fields(lh_new->extra_fields(),
lh->extra_fields_length() - removed_size);
} else {
memcpy(lh_new, lh, lh_size);
}
lh_new->last_mod_file_date(kDefaultDate);
lh_new->last_mod_file_time(normalized_time);
// Now write these few bytes and adjust read/write positions accordingly.
if (!WriteBytes(lh_new, lh_new->size())) {
diag_err(1, "%s:%d: Cannot copy modified local header for %.*s",
__FILE__, __LINE__, file_name_length, file_name);
}
copy_from += lh_size;
num_bytes -= lh_size;
if (reinterpret_cast<uint8_t *>(lh_new) != lh_buffer) {
free(lh_new);
}
}
// Do the actual copy.
if (!WriteBytes(input_jar.mapped_start() + copy_from, num_bytes)) {
diag_err(1, "%s:%d: Cannot write %zu bytes of %.*s from %s", __FILE__,
__LINE__, num_bytes, file_name_length, file_name,
input_jar_path.c_str());
}
AppendToDirectoryBuffer(jar_entry, local_header_offset, normalized_time,
fix_timestamp);
++entries_;
}
return input_jar.Close();
}
off64_t OutputJar::Position() {
if (file_ == nullptr) {
diag_err(1, "%s:%d: output file is not open", __FILE__, __LINE__);
}
// You'd think this could be "return ftell(file_);", but that
// generates a needless call to lseek. So instead we cache our
// current position in the output.
return outpos_;
}
// Writes an entry. The argument is the pointer to the contiguous block of
// memory containing Local Header for the entry, immediately followed by
// the data. The memory is freed after the data has been written.
void OutputJar::WriteEntry(void *buffer) {
if (buffer == nullptr) {
return;
}
LH *entry = reinterpret_cast<LH *>(buffer);
if (options_->verbose) {
fprintf(stderr, "%-.*s combiner has %zu bytes, %s to %zu\n",
entry->file_name_length(), entry->file_name(),
entry->uncompressed_file_size(),
entry->compression_method() == Z_NO_COMPRESSION ? "copied"
: "compressed",
entry->compressed_file_size());
}
// Set this entry's timestamp.
// MSDOS file timestamp format that Zip uses is described here:
// https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx
// ("32-Bit Windows Time/Date Formats")
if (options_->normalize_timestamps) {
// Regular "normalized" timestamp is 01/01/2010 00:00:00, while for the
// .class file it is 01/01/2010 00:00:02
entry->last_mod_file_date(kDefaultDate);
entry->last_mod_file_time(
ends_with(entry->file_name(), entry->file_name_length(), ".class") ? 1
: 0);
} else {
struct tm tm;
// Time has 2-second resolution, so round up:
time_t t_adjusted = (time(nullptr) + 1) & ~1;
localtime_r(&t_adjusted, &tm);
uint16_t dos_date =
((tm.tm_year - 80) << 9) | ((tm.tm_mon + 1) << 5) | tm.tm_mday;
uint16_t dos_time =
(tm.tm_hour << 11) | (tm.tm_min << 5) | (tm.tm_sec >> 1);
entry->last_mod_file_time(dos_time);
entry->last_mod_file_date(dos_date);
}
uint8_t *data = reinterpret_cast<uint8_t *>(entry);
off64_t output_position = Position();
if (!WriteBytes(data, entry->data() + entry->in_zip_size() - data)) {
diag_err(1, "%s:%d: write", __FILE__, __LINE__);
}
// Data written, allocate CDH space and populate CDH.
// Space needed for the CDH varies depending on whether output position field
// fits into 32 bits (we do not handle compressed/uncompressed entry sizes
// exceeding 32 bits at the moment).
uint16_t zip64_size = ziph::zfield_needs_ext64(output_position)
? Zip64ExtraField::space_needed(1)
: 0;
CDH *cdh = reinterpret_cast<CDH *>(
ReserveCdh(sizeof(CDH) + entry->file_name_length() +
entry->extra_fields_length() + zip64_size));
cdh->signature();
// Note: do not set the version to Unix 3.0 spec, otherwise
// unzip will think that 'external_attributes' field contains access mode
cdh->version(20);
cdh->version_to_extract(20); // 2.0
cdh->bit_flag(0x0);
cdh->compression_method(entry->compression_method());
cdh->last_mod_file_time(entry->last_mod_file_time());
cdh->last_mod_file_date(entry->last_mod_file_date());
cdh->crc32(entry->crc32());
TODO(entry->compressed_file_size32() != 0xFFFFFFFF, "Handle Zip64");
cdh->compressed_file_size32(entry->compressed_file_size32());
TODO(entry->uncompressed_file_size32() != 0xFFFFFFFF, "Handle Zip64");
cdh->uncompressed_file_size32(entry->uncompressed_file_size32());
cdh->file_name(entry->file_name(), entry->file_name_length());
cdh->extra_fields(entry->extra_fields(), entry->extra_fields_length());
if (zip64_size > 0) {
Zip64ExtraField *zip64_ef = reinterpret_cast<Zip64ExtraField *>(
cdh->extra_fields() + cdh->extra_fields_length());
zip64_ef->signature();
zip64_ef->attr_count(1);
zip64_ef->attr64(0, output_position);
cdh->local_header_offset32(0xFFFFFFFF);
// Field address argument points to the already existing field,
// so the call just updates the length.
cdh->extra_fields(cdh->extra_fields(),
cdh->extra_fields_length() + zip64_size);
} else {
cdh->local_header_offset32(output_position);
}
cdh->comment_length(0);
cdh->start_disk_nr(0);
cdh->internal_attributes(0);
cdh->external_attributes(0);
++entries_;
free(reinterpret_cast<void *>(entry));
}
void OutputJar::WriteMetaInf() {
std::string path("META-INF/");
// META_INF/ is always the first entry, and as such it should have an extra
// field with the tag 0xCAFE and zero bytes of data. This is not the part of
// the jar file spec, but Unix 'file' utility relies on it to distiguish jar
// file from zip file. See https://bugs.openjdk.java.net/browse/JDK-6808540
const uint8_t extra_fields[] = {0xFE, 0xCA, 0, 0};
const uint16_t n_extra_fields =
sizeof(extra_fields) / sizeof(extra_fields[0]);
WriteDirEntry(path, extra_fields, n_extra_fields);
}
// Writes a directory entry with the given name and extra fields.
void OutputJar::WriteDirEntry(const std::string &name,
const uint8_t *extra_fields,
const uint16_t n_extra_fields) {
size_t lh_size = sizeof(LH) + name.size() + n_extra_fields;
LH *lh = reinterpret_cast<LH *>(malloc(lh_size));
lh->signature();
lh->version(20); // 2.0
lh->bit_flag(0); // TODO(asmundak): should I set UTF8 flag?
lh->compression_method(Z_NO_COMPRESSION);
lh->crc32(0);
lh->compressed_file_size32(0);
lh->uncompressed_file_size32(0);
lh->file_name(name.c_str(), name.size());
lh->extra_fields(extra_fields, n_extra_fields);
known_members_.emplace(name, EntryInfo{&null_combiner_});
WriteEntry(lh);
}
// Create output Central Directory entry for the input jar entry.
void OutputJar::AppendToDirectoryBuffer(const CDH *cdh, off64_t lh_pos,
uint16_t normalized_time,
bool fix_timestamp) {
// While copying from the input CDH pointed to by 'cdh', we may need to drop
// Unix timestamp extra field, and we might need to change the number of
// attributes of the Zip64 extra field, or create it, or destroy it if entry's
// position relative to 4G boundary changes.
// The rest of the input CDH is copied.
// 1. Decide if we need to drop UnixTime.
size_t removed_unix_time_field_size = 0;
if (fix_timestamp) {
auto unix_time_field = cdh->unix_time_extra_field();
if (unix_time_field != nullptr) {
removed_unix_time_field_size = unix_time_field->size();
}
}
// 2. Figure out how many attributes input entry has and how many
// the output entry is going to have.
const Zip64ExtraField *zip64_ef = cdh->zip64_extra_field();
const int zip64_attr_count = zip64_ef == nullptr ? 0 : zip64_ef->attr_count();
const bool lh_pos_needs64 = ziph::zfield_needs_ext64(lh_pos);
int out_zip64_attr_count;
if (zip64_attr_count > 0) {
out_zip64_attr_count = zip64_attr_count;
// The number of attributes may remain the same, or it may increase or
// decrease by 1, depending on local_header_offset value.
if (ziph::zfield_has_ext64(cdh->local_header_offset32()) !=
lh_pos_needs64) {
if (lh_pos_needs64) {
out_zip64_attr_count += 1;
} else {
out_zip64_attr_count -= 1;
}
}
} else {
out_zip64_attr_count = lh_pos_needs64 ? 1 : 0;
}
const uint16_t zip64_size = Zip64ExtraField::space_needed(zip64_attr_count);
const uint16_t out_zip64_size =
Zip64ExtraField::space_needed(out_zip64_attr_count);
// Allocate output CDH and copy everything but extra fields.
const uint16_t ef_size = cdh->extra_fields_length();
const uint16_t out_ef_size =
(ef_size + out_zip64_size) - (removed_unix_time_field_size + zip64_size);
const size_t out_cdh_size = cdh->size() + out_ef_size - ef_size;
CDH *out_cdh = reinterpret_cast<CDH *>(ReserveCdr(out_cdh_size));
// Calculate ExtraFields boundaries in the input and output entries.
auto ef_begin = reinterpret_cast<const ExtraField *>(cdh->extra_fields());
auto ef_end =
reinterpret_cast<const ExtraField *>(ziph::byte_ptr(ef_begin) + ef_size);
// Copy [cdh..ef_begin) -> [out_cdh..out_ef_begin)
memcpy(out_cdh, cdh, ziph::byte_ptr(ef_begin) - ziph::byte_ptr(cdh));
auto out_ef_begin = reinterpret_cast<ExtraField *>(
const_cast<uint8_t *>(out_cdh->extra_fields()));
auto out_ef_end = reinterpret_cast<ExtraField *>(
reinterpret_cast<uint8_t *>(out_ef_begin) + out_ef_size);
// Copy [ef_end..cdh_end) -> [out_ef_end..out_cdh_end)
memcpy(out_ef_end, ef_end,
ziph::byte_ptr(cdh) + cdh->size() - ziph::byte_ptr(ef_end));
// Copy extra fields, dropping Zip64 and possibly UnixTime fields.
ExtraField *out_ef = out_ef_begin;
for (const ExtraField *ef = ef_begin; ef < ef_end; ef = ef->next()) {
if ((fix_timestamp && ef->is_unix_time()) || ef->is_zip64()) {
// Skip this one.
} else {
memcpy(out_ef, ef, ef->size());
out_ef = reinterpret_cast<ExtraField *>(
reinterpret_cast<uint8_t *>(out_ef) + ef->size());
}
}
// Set up Zip64 extra field if necessary.
if (out_zip64_size > 0) {
Zip64ExtraField *out_zip64_ef = reinterpret_cast<Zip64ExtraField *>(out_ef);
out_zip64_ef->signature();
out_zip64_ef->attr_count(out_zip64_attr_count);
int copy_count = out_zip64_attr_count < zip64_attr_count
? out_zip64_attr_count
: zip64_attr_count;
if (copy_count > 0) {
out_zip64_ef->attr64(0, zip64_ef->attr64(0));
if (copy_count > 1) {
out_zip64_ef->attr64(1, zip64_ef->attr64(1));
}
}
// Set 64-bit local_header_offset if necessary. It's always the last
// attribute.
if (lh_pos_needs64) {
out_zip64_ef->attr64(out_zip64_attr_count - 1, lh_pos);
}
}
out_cdh->extra_fields(ziph::byte_ptr(out_ef_begin), out_ef_size);
out_cdh->local_header_offset32(lh_pos_needs64 ? 0xFFFFFFFF : lh_pos);
if (fix_timestamp) {
out_cdh->last_mod_file_time(normalized_time);
out_cdh->last_mod_file_date(kDefaultDate);
}
}
uint8_t *OutputJar::ReserveCdr(size_t chunk_size) {
if (cen_size_ + chunk_size > cen_capacity_) {
cen_capacity_ += 1000000;
cen_ = reinterpret_cast<uint8_t *>(realloc(cen_, cen_capacity_));
if (!cen_) {
diag_errx(1, "%s:%d: Cannot allocate %zu bytes for the directory",
__FILE__, __LINE__, cen_capacity_);
}
}
uint8_t *entry = cen_ + cen_size_;
cen_size_ += chunk_size;
return entry;
}
uint8_t *OutputJar::ReserveCdh(size_t size) {
return static_cast<uint8_t *>(memset(ReserveCdr(size), 0, size));
}
// Write out combined jar.
bool OutputJar::Close() {
if (file_ == nullptr) {
return true;
}
for (auto &service_handler : service_handlers_) {
WriteEntry(service_handler->OutputEntry(options_->force_compression));
}
for (auto &extra_combiner : extra_combiners_) {
WriteEntry(extra_combiner->OutputEntry(options_->force_compression));
}
WriteEntry(spring_handlers_.OutputEntry(options_->force_compression));
WriteEntry(spring_schemas_.OutputEntry(options_->force_compression));
WriteEntry(protobuf_meta_handler_.OutputEntry(options_->force_compression));
// TODO(asmundak): handle manifest;
off64_t output_position = Position();
bool write_zip64_ecd = output_position >= 0xFFFFFFFF || entries_ >= 0xFFFF ||
cen_size_ >= 0xFFFFFFFF;
size_t cen_size = cen_size_; // Save it before ReserveCdh updates it.
if (write_zip64_ecd) {
{
ECD64 *ecd64 = reinterpret_cast<ECD64 *>(ReserveCdh(sizeof(ECD64)));
ecd64->signature();
ecd64->remaining_size(sizeof(ECD64) - 12);
ecd64->version(0x031E); // Unix, version 3.0
ecd64->version_to_extract(45); // 4.5 (Zip64 support)
ecd64->this_disk_entries(entries_);
ecd64->total_entries(entries_);
ecd64->cen_size(cen_size);
ecd64->cen_offset(output_position);
}
{
ECD64Locator *ecd64_locator =
reinterpret_cast<ECD64Locator *>(ReserveCdh(sizeof(ECD64Locator)));
ecd64_locator->signature();
ecd64_locator->ecd64_offset(output_position + cen_size);
ecd64_locator->total_disks(1);
}
{
ECD *ecd = reinterpret_cast<ECD *>(ReserveCdh(sizeof(ECD)));
ecd->signature();
ecd->this_disk_entries16(0xFFFF);
ecd->total_entries16(0xFFFF);
// Java Compiler (javac) uses its own "optimized" Zip handler (see
// https://bugs.openjdk.java.net/browse/JDK-7018859) which may fail
// to handle 0xFFFFFFFF in the CEN size and CEN offset fields. Try
// to use 32-bit values here, too. Hopefully by the time we need to
// handle really large archives, this is fixes upstream. Note that this
// affects javac and javah only, 'jar' experiences no problems.
ecd->cen_size32(std::min(cen_size, static_cast<size_t>(0xFFFFFFFFUL)));
ecd->cen_offset32(
std::min(output_position, static_cast<off64_t>(0x0FFFFFFFFL)));
}
} else {
ECD *ecd = reinterpret_cast<ECD *>(ReserveCdh(sizeof(ECD)));
ecd->signature();
ecd->this_disk_entries16((uint16_t)entries_);
ecd->total_entries16((uint16_t)entries_);
ecd->cen_size32(cen_size);
ecd->cen_offset32(output_position);
}
// Save Central Directory and wrap up.
if (!WriteBytes(cen_, cen_size_)) {
diag_err(1, "%s:%d: Cannot write central directory", __FILE__, __LINE__);
}
free(cen_);
if (fclose(file_)) {
diag_err(1, "%s:%d: %s", __FILE__, __LINE__, path());
}
file_ = nullptr;
// Free the buffer only after fclose(); stdio may flush data from the
// buffer on close.
buffer_.reset();
if (options_->verbose) {
fprintf(stderr, "Wrote %s with %d entries", path(), entries_);
if (duplicate_entries_) {
fprintf(stderr, ", skipped %d entries", duplicate_entries_);
}
fprintf(stderr, "\n");
}
return true;
}
bool IsDir(const std::string &path) {
struct stat st;
if (stat(path.c_str(), &st)) {
diag_warn("%s:%d: stat %s:", __FILE__, __LINE__, path.c_str());
return false;
}
return (st.st_mode & S_IFDIR) == S_IFDIR;
}
void OutputJar::ClasspathResource(const std::string &resource_name,
const std::string &resource_path) {
if (known_members_.count(resource_name)) {
if (options_->warn_duplicate_resources) {
diag_warnx(
"%s:%d: Duplicate resource name %s in the --classpath_resource or "
"--resource option",
__FILE__, __LINE__, resource_name.c_str());
// TODO(asmundak): this mimics old behaviour. Confirm that unless
// we run with --warn_duplicate_resources, the output zip file contains
// the concatenated contents of the all the resources with the same name.
return;
}
}
MappedFile mapped_file;
if (mapped_file.Open(resource_path)) {
Concatenator *classpath_resource = new Concatenator(resource_name);
classpath_resource->Append(
reinterpret_cast<const char *>(mapped_file.start()),
mapped_file.size());
classpath_resources_.emplace_back(classpath_resource);
known_members_.emplace(resource_name, EntryInfo{classpath_resource});
} else if (IsDir(resource_path)) {
// add an empty entry for the directory so its path ends up in the
// manifest
classpath_resources_.emplace_back(new Concatenator(resource_name + "/"));
known_members_.emplace(resource_name, EntryInfo{&null_combiner_});
} else {
diag_err(1, "%s:%d: %s", __FILE__, __LINE__, resource_path.c_str());
}
}
ssize_t OutputJar::CopyAppendData(int in_fd, off64_t offset, size_t count) {
if (count == 0) {
return 0;
}
std::unique_ptr<void, decltype(free) *> buffer(malloc(kBufferSize), free);
if (buffer == nullptr) {
diag_err(1, "%s:%d: malloc", __FILE__, __LINE__);
}
ssize_t total_written = 0;
#ifdef _WIN32
HANDLE hFile = reinterpret_cast<HANDLE>(_get_osfhandle(in_fd));
while (static_cast<size_t>(total_written) < count) {
ssize_t len = std::min(kBufferSize, count - total_written);
DWORD n_read;
if (!::ReadFile(hFile, buffer.get(), len, &n_read, nullptr)) {
return -1;
}
if (n_read == 0) {
break;
}
if (!WriteBytes(buffer.get(), n_read)) {
return -1;
}
total_written += n_read;
}
#else
while (static_cast<size_t>(total_written) < count) {
size_t len = std::min(kBufferSize, count - total_written);
ssize_t n_read = pread(in_fd, buffer.get(), len, offset + total_written);
if (n_read > 0) {
if (!WriteBytes(buffer.get(), n_read)) {
return -1;
}
total_written += n_read;
} else if (n_read == 0) {
break;
} else {
return -1;
}
}
#endif // _WIN32
return total_written;
}
void OutputJar::AppendFile(Options *options, const char *const file_path) {
int in_fd = open(file_path, O_RDONLY);
struct stat statbuf;
if (fstat(in_fd, &statbuf)) {
diag_err(1, "%s", file_path);
}
// TODO(asmundak): Consider going back to sendfile() or reflink
// (BTRFS_IOC_CLONE/XFS_IOC_CLONE) here. The launcher preamble can
// be very large for targets with many native deps.
ssize_t byte_count = CopyAppendData(in_fd, 0, statbuf.st_size);
if (byte_count < 0) {
diag_err(1, "%s:%d: Cannot copy %s to %s", __FILE__, __LINE__,
file_path, options->output_jar.c_str());
} else if (byte_count != statbuf.st_size) {
diag_err(1, "%s:%d: Copied only %zu bytes out of %" PRIu64 " from %s",
__FILE__, __LINE__, byte_count, statbuf.st_size, file_path);
}
close(in_fd);
if (options->verbose) {
fprintf(stderr, "Prepended %s (%" PRIu64 " bytes)\n", file_path,
statbuf.st_size);
}
}
void OutputJar::AppendCDSArchive(const std::string &cds_archive) {
// Align the shared archive start offset at page alignment, which is
// required by mmap.
off64_t cur_offset = Position();
size_t pagesize;
#ifdef _WIN32
SYSTEM_INFO si;
GetSystemInfo(&si);
pagesize = si.dwPageSize;
#else
pagesize = sysconf(_SC_PAGESIZE);
#endif
off64_t aligned_offset = (cur_offset + (pagesize - 1)) & ~(pagesize - 1);
size_t gap = aligned_offset - cur_offset;
size_t written;
if (gap > 0) {
char *zeros = (char *)malloc(gap);
if (!zeros) {
return;
}
memset(zeros, 0, gap);
written = fwrite(zeros, 1, gap, file_);
outpos_ += written;
free(zeros);
}
// Copy archived data
AppendFile(options_, cds_archive.c_str());
// Write the file offset of the shared archive section as a manifest
// attribute.
char cds_manifest_attr[50];
snprintf( cds_manifest_attr, sizeof(cds_manifest_attr),
"Jsa-Offset: %ld", (long)aligned_offset); // NOLINT(runtime/int,
// google-runtime-int)
manifest_.Append(cds_manifest_attr);
manifest_.Append("\r\n");
// Add to build_properties
build_properties_.AddProperty("cds.archive",
cds_archive.c_str());
}
void OutputJar::ExtraCombiner(const std::string &entry_name,
Combiner *combiner) {
extra_combiners_.emplace_back(combiner);
known_members_.emplace(entry_name, EntryInfo{combiner});
}
bool OutputJar::WriteBytes(const void *buffer, size_t count) {
size_t written = fwrite(buffer, 1, count, file_);
outpos_ += written;
return written == count;
}
void OutputJar::ExtraHandler(const std::string &input_jar_path, const CDH *,
const std::string *) {}
|
# include <cmath>
# include <cstdlib>
# include <ctime>
# include <iostream>
# include <fstream>
using namespace std;
# include "lebedev2.h"
using namespace std;
//****************************************************************************80
int available_table ( int rule )
//****************************************************************************80
//
// Purpose:
//
// AVAILABLE_TABLE returns the availability of a Lebedev rule.
//
// Modified:
//
// 12 September 2010
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Input, int RULE, the index of the rule, between 1 and 65.
//
// Output, int AVAILABLE_TABLE, the availability of the rule.
// * -1, there is no such rule;
// * 0, there is such a rule, but it is not available in this library.
// * 1, the rule is available in this library.
//
{
int rule_max = 65;
int table[65] = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 0, 1, 0, 0, 1,
0, 0, 1, 0, 0, 1, 0, 0, 1, 0,
0, 1, 0, 0, 1, 0, 0, 1, 0, 0,
1, 0, 0, 1, 0, 0, 1, 0, 0, 1,
0, 0, 1, 0, 0, 1, 0, 0, 1, 0,
0, 1, 0, 0, 1 };
int value;
if ( rule < 1 )
{
value = - 1;
}
else if ( rule_max < rule )
{
value = - 1;
}
else
{
value = table[rule-1];
}
return value;
}
//****************************************************************************80
int gen_oh ( int code, double a, double b, double v, double *x,
double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// GEN_OH generates points under OH symmetry.
//
// Discussion:
//
// Given a point on a sphere, specified by A and B, this routine generates
// all the equivalent points under OH symmetry, making grid points with
// weight V.
//
// The variable NUM is increased by the number of different points
// generated.
//
// Depending on CODE, there are from 6 to 48 different but equivalent
// points that are generated:
//
// CODE=1: (0,0,1) etc ( 6 points)
// CODE=2: (0,A,A) etc, A=1/sqrt(2) ( 12 points)
// CODE=3: (A,A,A) etc, A=1/sqrt(3) ( 8 points)
// CODE=4: (A,A,B) etc, B=sqrt(1-2 A^2) ( 24 points)
// CODE=5: (A,B,0) etc, B=sqrt(1-A^2), A input ( 24 points)
// CODE=6: (A,B,C) etc, C=sqrt(1-A^2-B^2), A, B input ( 48 points)
//
// Modified:
//
// 11 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Input, int CODE, selects the symmetry group.
//
// Input/output, int &NUM, the number of points. This is incremented
// upon output by the number of points generated on this call.
//
// Input, double A, B, information that may be needed to
// generate the coordinates of the points (for code = 5 or 6 only).
//
// Input, double V, the weight to be assigned the points.
//
// Output, double X[*], Y[*], Z[*], W[*], the coordinates
// and weights of the symmetric points generated on this call.
//
// Output, int GEN_OH, the number of points generated on this call.
//
{
double c;
int num;
if ( code == 1 )
{
a = 1.0;
x[0] = a;
y[0] = 0.0;
z[0] = 0.0;
w[0] = v;
x[1] = -a;
y[1] = 0.0;
z[1] = 0.0;
w[1] = v;
x[2] = 0.0;
y[2] = a;
z[2] = 0.0;
w[2] = v;
x[3] = 0.0;
y[3] = -a;
z[3] = 0.0;
w[3] = v;
x[4] = 0.0;
y[4] = 0.0;
z[4] = a;
w[4] = v;
x[5] = 0.0;
y[5] = 0.0;
z[5] = -a;
w[5] = v;
num = 6;
}
else if ( code == 2 )
{
a = sqrt ( 0.5 );
x[0] = 0;
y[0] = a;
z[0] = a;
w[0] = v;
x[1] = 0;
y[1] = -a;
z[1] = a;
w[1] = v;
x[2] = 0;
y[2] = a;
z[2] = -a;
w[2] = v;
x[3] = 0;
y[3] = -a;
z[3] = -a;
w[3] = v;
x[4] = a;
y[4] = 0;
z[4] = a;
w[4] = v;
x[5] = -a;
y[5] = 0;
z[5] = a;
w[5] = v;
x[6] = a;
y[6] = 0;
z[6] = -a;
w[6] = v;
x[7] = -a;
y[7] = 0;
z[7] = -a;
w[7] = v;
x[8] = a;
y[8] = a;
z[8] = 0;
w[8] = v;
x[9] = -a;
y[9] = a;
z[9] = 0;
w[9] = v;
x[10] = a;
y[10] = -a;
z[10] = 0;
w[10] = v;
x[11] = -a;
y[11] = -a;
z[11] = 0;
w[11] = v;
num = 12;
}
else if ( code == 3 )
{
a = sqrt ( 1.0 / 3.0 );
x[0] = a;
y[0] = a;
z[0] = a;
w[0] = v;
x[1] = -a;
y[1] = a;
z[1] = a;
w[1] = v;
x[2] = a;
y[2] = -a;
z[2] = a;
w[2] = v;
x[3] = -a;
y[3] = -a;
z[3] = a;
w[3] = v;
x[4] = a;
y[4] = a;
z[4] = -a;
w[4] = v;
x[5] = -a;
y[5] = a;
z[5] = -a;
w[5] = v;
x[6] = a;
y[6] = -a;
z[6] = -a;
w[6] = v;
x[7] = -a;
y[7] = -a;
z[7] = -a;
w[7] = v;
num = 8;
}
else if ( code == 4 )
{
b = sqrt ( 1.0 - 2.0 * a * a );
x[0] = a;
y[0] = a;
z[0] = b;
w[0] = v;
x[1] = -a;
y[1] = a;
z[1] = b;
w[1] = v;
x[2] = a;
y[2] = -a;
z[2] = b;
w[2] = v;
x[3] = -a;
y[3] = -a;
z[3] = b;
w[3] = v;
x[4] = a;
y[4] = a;
z[4] = -b;
w[4] = v;
x[5] = -a;
y[5] = a;
z[5] = -b;
w[5] = v;
x[6] = a;
y[6] = -a;
z[6] = -b;
w[6] = v;
x[7] = -a;
y[7] = -a;
z[7] = -b;
w[7] = v;
x[8] = a;
y[8] = b;
z[8] = a;
w[8] = v;
x[9] = -a;
y[9] = b;
z[9] = a;
w[9] = v;
x[10] = a;
y[10] = -b;
z[10] = a;
w[10] = v;
x[11] = -a;
y[11] = -b;
z[11] = a;
w[11] = v;
x[12] = a;
y[12] = b;
z[12] = -a;
w[12] = v;
x[13] = -a;
y[13] = b;
z[13] = -a;
w[13] = v;
x[14] = a;
y[14] = -b;
z[14] = -a;
w[14] = v;
x[15] = -a;
y[15] = -b;
z[15] = -a;
w[15] = v;
x[16] = b;
y[16] = a;
z[16] = a;
w[16] = v;
x[17] = -b;
y[17] = a;
z[17] = a;
w[17] = v;
x[18] = b;
y[18] = -a;
z[18] = a;
w[18] = v;
x[19] = -b;
y[19] = -a;
z[19] = a;
w[19] = v;
x[20] = b;
y[20] = a;
z[20] = -a;
w[20] = v;
x[21] = -b;
y[21] = a;
z[21] = -a;
w[21] = v;
x[22] = b;
y[22] = -a;
z[22] = -a;
w[22] = v;
x[23] = -b;
y[23] = -a;
z[23] = -a;
w[23] = v;
num = 24;
}
else if ( code == 5 )
{
b = sqrt ( 1.0 - a * a );
x[0] = a;
y[0] = b;
z[0] = 0;
w[0] = v;
x[1] = -a;
y[1] = b;
z[1] = 0;
w[1] = v;
x[2] = a;
y[2] = -b;
z[2] = 0;
w[2] = v;
x[3] = -a;
y[3] = -b;
z[3] = 0;
w[3] = v;
x[4] = b;
y[4] = a;
z[4] = 0;
w[4] = v;
x[5] = -b;
y[5] = a;
z[5] = 0;
w[5] = v;
x[6] = b;
y[6] = -a;
z[6] = 0;
w[6] = v;
x[7] = -b;
y[7] = -a;
z[7] = 0;
w[7] = v;
x[8] = a;
y[8] = 0;
z[8] = b;
w[8] = v;
x[9] = -a;
y[9] = 0;
z[9] = b;
w[9] = v;
x[10] = a;
y[10] = 0;
z[10] = -b;
w[10] = v;
x[11] = -a;
y[11] = 0;
z[11] = -b;
w[11] = v;
x[12] = b;
y[12] = 0;
z[12] = a;
w[12] = v;
x[13] = -b;
y[13] = 0;
z[13] = a;
w[13] = v;
x[14] = b;
y[14] = 0;
z[14] = -a;
w[14] = v;
x[15] = -b;
y[15] = 0;
z[15] = -a;
w[15] = v;
x[16] = 0;
y[16] = a;
z[16] = b;
w[16] = v;
x[17] = 0;
y[17] = -a;
z[17] = b;
w[17] = v;
x[18] = 0;
y[18] = a;
z[18] = -b;
w[18] = v;
x[19] = 0;
y[19] = -a;
z[19] = -b;
w[19] = v;
x[20] = 0;
y[20] = b;
z[20] = a;
w[20] = v;
x[21] = 0;
y[21] = -b;
z[21] = a;
w[21] = v;
x[22] = 0;
y[22] = b;
z[22] = -a;
w[22] = v;
x[23] = 0;
y[23] = -b;
z[23] = -a;
w[23] = v;
num = 24;
}
else if ( code == 6 )
{
c = sqrt ( 1.0 - a * a - b * b );
x[0] = a;
y[0] = b;
z[0] = c;
w[0] = v;
x[1] = -a;
y[1] = b;
z[1] = c;
w[1] = v;
x[2] = a;
y[2] = -b;
z[2] = c;
w[2] = v;
x[3] = -a;
y[3] = -b;
z[3] = c;
w[3] = v;
x[4] = a;
y[4] = b;
z[4] = -c;
w[4] = v;
x[5] = -a;
y[5] = b;
z[5] = -c;
w[5] = v;
x[6] = a;
y[6] = -b;
z[6] = -c;
w[6] = v;
x[7] = -a;
y[7] = -b;
z[7] = -c;
w[7] = v;
x[8] = a;
y[8] = c;
z[8] = b;
w[8] = v;
x[9] = -a;
y[9] = c;
z[9] = b;
w[9] = v;
x[10] = a;
y[10] = -c;
z[10] = b;
w[10] = v;
x[11] = -a;
y[11] = -c;
z[11] = b;
w[11] = v;
x[12] = a;
y[12] = c;
z[12] = -b;
w[12] = v;
x[13] = -a;
y[13] = c;
z[13] = -b;
w[13] = v;
x[14] = a;
y[14] = -c;
z[14] = -b;
w[14] = v;
x[15] = -a;
y[15] = -c;
z[15] = -b;
w[15] = v;
x[16] = b;
y[16] = a;
z[16] = c;
w[16] = v;
x[17] = -b;
y[17] = a;
z[17] = c;
w[17] = v;
x[18] = b;
y[18] = -a;
z[18] = c;
w[18] = v;
x[19] = -b;
y[19] = -a;
z[19] = c;
w[19] = v;
x[20] = b;
y[20] = a;
z[20] = -c;
w[20] = v;
x[21] = -b;
y[21] = a;
z[21] = -c;
w[21] = v;
x[22] = b;
y[22] = -a;
z[22] = -c;
w[22] = v;
x[23] = -b;
y[23] = -a;
z[23] = -c;
w[23] = v;
x[24] = b;
y[24] = c;
z[24] = a;
w[24] = v;
x[25] = -b;
y[25] = c;
z[25] = a;
w[25] = v;
x[26] = b;
y[26] = -c;
z[26] = a;
w[26] = v;
x[27] = -b;
y[27] = -c;
z[27] = a;
w[27] = v;
x[28] = b;
y[28] = c;
z[28] = -a;
w[28] = v;
x[29] = -b;
y[29] = c;
z[29] = -a;
w[29] = v;
x[30] = b;
y[30] = -c;
z[30] = -a;
w[30] = v;
x[31] = -b;
y[31] = -c;
z[31] = -a;
w[31] = v;
x[32] = c;
y[32] = a;
z[32] = b;
w[32] = v;
x[33] = -c;
y[33] = a;
z[33] = b;
w[33] = v;
x[34] = c;
y[34] = -a;
z[34] = b;
w[34] = v;
x[35] = -c;
y[35] = -a;
z[35] = b;
w[35] = v;
x[36] = c;
y[36] = a;
z[36] = -b;
w[36] = v;
x[37] = -c;
y[37] = a;
z[37] = -b;
w[37] = v;
x[38] = c;
y[38] = -a;
z[38] = -b;
w[38] = v;
x[39] = -c;
y[39] = -a;
z[39] = -b;
w[39] = v;
x[40] = c;
y[40] = b;
z[40] = a;
w[40] = v;
x[41] = -c;
y[41] = b;
z[41] = a;
w[41] = v;
x[42] = c;
y[42] = -b;
z[42] = a;
w[42] = v;
x[43] = -c;
y[43] = -b;
z[43] = a;
w[43] = v;
x[44] = c;
y[44] = b;
z[44] = -a;
w[44] = v;
x[45] = -c;
y[45] = b;
z[45] = -a;
w[45] = v;
x[46] = c;
y[46] = -b;
z[46] = -a;
w[46] = v;
x[47] = -c;
y[47] = -b;
z[47] = -a;
w[47] = v;
num = 48;
}
else
{
cerr << "\n";
cerr << "GEN_OH - Fatal error!\n";
cerr << " Illegal value of code.\n";
exit ( 1 );
}
return num;
}
//****************************************************************************80
void ld_by_order ( int order, double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD_BY_ORDER returns a Lebedev angular grid given its order.
//
// Discussion:
//
// Only a certain set of such rules are available through this function.
//
// Modified:
//
// 13 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Input, int ORDER, the order of the rule.
//
// Output, double X[ORDER], Y[ORDER], Z[ORDER], W[ORDER], the coordinates
// and weights of the points.
//
{
if ( order == 6 )
{
ld0006 ( x, y, z, w );
}
else if ( order == 14 )
{
ld0014 ( x, y, z, w );
}
else if ( order == 26 )
{
ld0026 ( x, y, z, w );
}
else if ( order == 38 )
{
ld0038 ( x, y, z, w );
}
else if ( order == 50 )
{
ld0050 ( x, y, z, w );
}
else if ( order == 74 )
{
ld0074 ( x, y, z, w );
}
else if ( order == 86 )
{
ld0086 ( x, y, z, w );
}
else if ( order == 110 )
{
ld0110 ( x, y, z, w );
}
else if ( order == 146 )
{
ld0146 ( x, y, z, w );
}
else if ( order == 170 )
{
ld0170 ( x, y, z, w );
}
else if ( order == 194 )
{
ld0194 ( x, y, z, w );
}
else if ( order == 230 )
{
ld0230 ( x, y, z, w );
}
else if ( order == 266 )
{
ld0266 ( x, y, z, w );
}
else if ( order == 302 )
{
ld0302 ( x, y, z, w );
}
else if ( order == 350 )
{
ld0350 ( x, y, z, w );
}
else if ( order == 434 )
{
ld0434 ( x, y, z, w );
}
else if ( order == 590 )
{
ld0590 ( x, y, z, w );
}
else if ( order == 770 )
{
ld0770 ( x, y, z, w );
}
else if ( order == 974 )
{
ld0974 ( x, y, z, w );
}
else if ( order == 1202 )
{
ld1202 ( x, y, z, w );
}
else if ( order == 1454 )
{
ld1454 ( x, y, z, w );
}
else if ( order == 1730 )
{
ld1730 ( x, y, z, w );
}
else if ( order == 2030 )
{
ld2030 ( x, y, z, w );
}
else if ( order == 2354 )
{
ld2354 ( x, y, z, w );
}
else if ( order == 2702 )
{
ld2702 ( x, y, z, w );
}
else if ( order == 3074 )
{
ld3074 ( x, y, z, w );
}
else if ( order == 3470 )
{
ld3470 ( x, y, z, w );
}
else if ( order == 3890 )
{
ld3890 ( x, y, z, w );
}
else if ( order == 4334 )
{
ld4334 ( x, y, z, w );
}
else if ( order == 4802 )
{
ld4802 ( x, y, z, w );
}
else if ( order == 5294 )
{
ld5294 ( x, y, z, w );
}
else if ( order == 5810 )
{
ld5810 ( x, y, z, w );
}
else
{
cerr << "\n";
cerr << "LD_BY_ORDER - Fatal error!\n";
cerr << " Unexpected value of ORDER.\n";
exit ( 1 );
}
double pi4 = 4.*3.14159265358979323846;
for (int i=0;i<order;i++)
w[i] *= pi4;
return;
}
//****************************************************************************80
void ld0006 ( double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD0006 computes the 6 point Lebedev angular grid.
//
// Modified:
//
// 11 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Output, double X[N], Y[N], Z[N], W[N], the coordinates
// and weights of the points.
//
{
double a = 0.0;
double b = 0.0;
int n;
double v;
n = 0;
v = 0.1666666666666667;
n = n + gen_oh ( 1, a, b, v, x + n, y + n, z + n, w + n );
return;
}
//****************************************************************************80
void ld0014 ( double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD0014 computes the 14 point Lebedev angular grid.
//
// Modified:
//
// 12 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Output, double X[N], Y[N], Z[N], W[N], the coordinates
// and weights of the points.
//
{
double a = 0.0;
double b = 0.0;
int n;
double v;
n = 0;
v = 0.6666666666666667e-1;
n = n + gen_oh ( 1, a, b, v, x + n, y + n, z + n, w + n );
v = 0.7500000000000000e-1;
n = n + gen_oh ( 3, a, b, v, x + n, y + n, z + n, w + n );
n = n - 1;
return;
}
//****************************************************************************80
void ld0026 ( double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD0026 computes the 26 point Lebedev angular grid.
//
// Modified:
//
// 12 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Output, double X[N], Y[N], Z[N], W[N], the coordinates
// and weights of the points.
//
{
double a = 0.0;
double b = 0.0;
int n;
double v;
n = 0;
v = 0.4761904761904762e-1;
n = n + gen_oh ( 1, a, b, v, x + n, y + n, z + n, w + n );
v = 0.3809523809523810e-1;
n = n + gen_oh ( 2, a, b, v, x + n, y + n, z + n, w + n );
v = 0.3214285714285714e-1;
n = n + gen_oh ( 3, a, b, v, x + n, y + n, z + n, w + n );
n = n - 1;
return;
}
//****************************************************************************80
void ld0038 ( double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD0038 computes the 38 point Lebedev angular grid.
//
// Modified:
//
// 12 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Output, double X[N], Y[N], Z[N], W[N], the coordinates
// and weights of the points.
//
{
double a = 0.0;
double b = 0.0;
int n;
double v;
n = 0;
v = 0.9523809523809524e-2;
n = n + gen_oh ( 1, a, b, v, x + n, y + n, z + n, w + n );
v = 0.3214285714285714e-1;
n = n + gen_oh ( 3, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4597008433809831;
v = 0.2857142857142857e-1;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
n = n - 1;
return;
}
//****************************************************************************80
void ld0050 ( double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD0050 computes the 50 point Lebedev angular grid.
//
// Modified:
//
// 12 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Output, double X[N], Y[N], Z[N], W[N], the coordinates
// and weights of the points.
//
{
double a = 0.0;
double b = 0.0;
int n;
double v;
n = 0;
v = 0.1269841269841270e-1;
n = n + gen_oh ( 1, a, b, v, x + n, y + n, z + n, w + n );
v = 0.2257495590828924e-1;
n = n + gen_oh ( 2, a, b, v, x + n, y + n, z + n, w + n );
v = 0.2109375000000000e-1;
n = n + gen_oh ( 3, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3015113445777636;
v = 0.2017333553791887e-1;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
n = n - 1;
return;
}
//****************************************************************************80
void ld0074 ( double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD0074 computes the 74 point Lebedev angular grid.
//
// Modified:
//
// 12 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Output, double X[N], Y[N], Z[N], W[N], the coordinates
// and weights of the points.
//
{
double a = 0.0;
double b = 0.0;
int n;
double v;
n = 0;
v = 0.5130671797338464e-3;
n = n + gen_oh ( 1, a, b, v, x + n, y + n, z + n, w + n );
v = 0.1660406956574204e-1;
n = n + gen_oh ( 2, a, b, v, x + n, y + n, z + n, w + n );
v = -0.2958603896103896e-1;
n = n + gen_oh ( 3, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4803844614152614;
v = 0.2657620708215946e-1;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3207726489807764;
v = 0.1652217099371571e-1;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
n = n - 1;
return;
}
//****************************************************************************80
void ld0086 ( double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD0086 computes the 86 point Lebedev angular grid.
//
// Modified:
//
// 12 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Output, double X[N], Y[N], Z[N], W[N], the coordinates
// and weights of the points.
//
{
double a = 0.0;
double b = 0.0;
int n;
double v;
n = 0;
v = 0.1154401154401154e-1;
n = n + gen_oh ( 1, a, b, v, x + n, y + n, z + n, w + n );
v = 0.1194390908585628e-1;
n = n + gen_oh ( 3, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3696028464541502;
v = 0.1111055571060340e-1;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6943540066026664;
v = 0.1187650129453714e-1;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3742430390903412;
v = 0.1181230374690448e-1;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
n = n - 1;
return;
}
//****************************************************************************80
void ld0110 ( double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD0110 computes the 110 point Lebedev angular grid.
//
// Modified:
//
// 12 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Output, double X[N], Y[N], Z[N], W[N], the coordinates
// and weights of the points.
//
{
double a = 0.0;
double b = 0.0;
int n;
double v;
n = 0;
v = 0.3828270494937162e-2;
n = n + gen_oh ( 1, a, b, v, x + n, y + n, z + n, w + n );
v = 0.9793737512487512e-2;
n = n + gen_oh ( 3, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1851156353447362;
v = 0.8211737283191111e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6904210483822922;
v = 0.9942814891178103e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3956894730559419;
v = 0.9595471336070963e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4783690288121502;
v = 0.9694996361663028e-2;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
n = n - 1;
return;
}
//****************************************************************************80
void ld0146 ( double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD0146 computes the 146 point Lebedev angular grid.
//
// Modified:
//
// 12 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Output, double X[N], Y[N], Z[N], W[N], the coordinates
// and weights of the points.
//
{
double a = 0.0;
double b = 0.0;
int n;
double v;
n = 0;
v = 0.5996313688621381e-3;
n = n + gen_oh ( 1, a, b, v, x + n, y + n, z + n, w + n );
v = 0.7372999718620756e-2;
n = n + gen_oh ( 2, a, b, v, x + n, y + n, z + n, w + n );
v = 0.7210515360144488e-2;
n = n + gen_oh ( 3, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6764410400114264;
v = 0.7116355493117555e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4174961227965453;
v = 0.6753829486314477e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1574676672039082;
v = 0.7574394159054034e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1403553811713183;
b = 0.4493328323269557;
v = 0.6991087353303262e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
n = n - 1;
return;
}
//****************************************************************************80
void ld0170 ( double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD0170 computes the 170 point Lebedev angular grid.
//
// Modified:
//
// 12 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Output, double X[N], Y[N], Z[N], W[N], the coordinates
// and weights of the points.
//
{
double a = 0.0;
double b = 0.0;
int n;
double v;
n = 0;
v = 0.5544842902037365e-2;
n = n + gen_oh ( 1, a, b, v, x + n, y + n, z + n, w + n );
v = 0.6071332770670752e-2;
n = n + gen_oh ( 2, a, b, v, x + n, y + n, z + n, w + n );
v = 0.6383674773515093e-2;
n = n + gen_oh ( 3, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2551252621114134;
v = 0.5183387587747790e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6743601460362766;
v = 0.6317929009813725e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4318910696719410;
v = 0.6201670006589077e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2613931360335988;
v = 0.5477143385137348e-2;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4990453161796037;
b = 0.1446630744325115;
v = 0.5968383987681156e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
n = n - 1;
return;
}
//****************************************************************************80
void ld0194 ( double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD0194 computes the 194 point Lebedev angular grid.
//
// Modified:
//
// 12 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Output, double X[N], Y[N], Z[N], W[N], the coordinates
// and weights of the points.
//
{
double a = 0.0;
double b = 0.0;
int n;
double v;
n = 0;
v = 0.1782340447244611e-2;
n = n + gen_oh ( 1, a, b, v, x + n, y + n, z + n, w + n );
v = 0.5716905949977102e-2;
n = n + gen_oh ( 2, a, b, v, x + n, y + n, z + n, w + n );
v = 0.5573383178848738e-2;
n = n + gen_oh ( 3, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6712973442695226;
v = 0.5608704082587997e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2892465627575439;
v = 0.5158237711805383e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4446933178717437;
v = 0.5518771467273614e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1299335447650067;
v = 0.4106777028169394e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3457702197611283;
v = 0.5051846064614808e-2;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1590417105383530;
b = 0.8360360154824589;
v = 0.5530248916233094e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
n = n - 1;
return;
}
//****************************************************************************80
void ld0230 ( double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD0230 computes the 230 point Lebedev angular grid.
//
// Modified:
//
// 12 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Output, double X[N], Y[N], Z[N], W[N], the coordinates
// and weights of the points.
//
{
double a = 0.0;
double b = 0.0;
int n;
double v;
n = 0;
v = -0.5522639919727325e-1;
n = n + gen_oh ( 1, a, b, v, x + n, y + n, z + n, w + n );
v = 0.4450274607445226e-2;
n = n + gen_oh ( 3, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4492044687397611;
v = 0.4496841067921404e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2520419490210201;
v = 0.5049153450478750e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6981906658447242;
v = 0.3976408018051883e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6587405243460960;
v = 0.4401400650381014e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4038544050097660e-1;
v = 0.1724544350544401e-1;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5823842309715585;
v = 0.4231083095357343e-2;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3545877390518688;
v = 0.5198069864064399e-2;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2272181808998187;
b = 0.4864661535886647;
v = 0.4695720972568883e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
n = n - 1;
return;
}
//****************************************************************************80
void ld0266 ( double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD0266 computes the 266 point Lebedev angular grid.
//
// Modified:
//
// 12 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Output, double X[N], Y[N], Z[N], W[N], the coordinates
// and weights of the points.
//
{
double a = 0.0;
double b = 0.0;
int n;
double v;
n = 0;
v = -0.1313769127326952e-2;
n = n + gen_oh ( 1, a, b, v, x + n, y + n, z + n, w + n );
v = -0.2522728704859336e-2;
n = n + gen_oh ( 2, a, b, v, x + n, y + n, z + n, w + n );
v = 0.4186853881700583e-2;
n = n + gen_oh ( 3, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7039373391585475;
v = 0.5315167977810885e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1012526248572414;
v = 0.4047142377086219e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4647448726420539;
v = 0.4112482394406990e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3277420654971629;
v = 0.3595584899758782e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6620338663699974;
v = 0.4256131351428158e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.8506508083520399;
v = 0.4229582700647240e-2;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3233484542692899;
b = 0.1153112011009701;
v = 0.4080914225780505e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2314790158712601;
b = 0.5244939240922365;
v = 0.4071467593830964e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
n = n - 1;
return;
}
//****************************************************************************80
void ld0302 ( double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD0302 computes the 302 point Lebedev angular grid.
//
// Modified:
//
// 12 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Output, double X[N], Y[N], Z[N], W[N], the coordinates
// and weights of the points.
//
{
double a = 0.0;
double b = 0.0;
int n;
double v;
n = 0;
v = 0.8545911725128148e-3;
n = n + gen_oh ( 1, a, b, v, x + n, y + n, z + n, w + n );
v = 0.3599119285025571e-2;
n = n + gen_oh ( 3, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3515640345570105;
v = 0.3449788424305883e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6566329410219612;
v = 0.3604822601419882e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4729054132581005;
v = 0.3576729661743367e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.9618308522614784e-1;
v = 0.2352101413689164e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2219645236294178;
v = 0.3108953122413675e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7011766416089545;
v = 0.3650045807677255e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2644152887060663;
v = 0.2982344963171804e-2;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5718955891878961;
v = 0.3600820932216460e-2;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2510034751770465;
b = 0.8000727494073952;
v = 0.3571540554273387e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1233548532583327;
b = 0.4127724083168531;
v = 0.3392312205006170e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
n = n - 1;
return;
}
//****************************************************************************80
void ld0350 ( double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD0350 computes the 350 point Lebedev angular grid.
//
// Modified:
//
// 12 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Output, double X[N], Y[N], Z[N], W[N], the coordinates
// and weights of the points.
//
{
double a = 0.0;
double b = 0.0;
int n;
double v;
n = 0;
v = 0.3006796749453936e-2;
n = n + gen_oh ( 1, a, b, v, x + n, y + n, z + n, w + n );
v = 0.3050627745650771e-2;
n = n + gen_oh ( 3, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7068965463912316;
v = 0.1621104600288991e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4794682625712025;
v = 0.3005701484901752e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1927533154878019;
v = 0.2990992529653774e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6930357961327123;
v = 0.2982170644107595e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3608302115520091;
v = 0.2721564237310992e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6498486161496169;
v = 0.3033513795811141e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1932945013230339;
v = 0.3007949555218533e-2;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3800494919899303;
v = 0.2881964603055307e-2;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2899558825499574;
b = 0.7934537856582316;
v = 0.2958357626535696e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.9684121455103957e-1;
b = 0.8280801506686862;
v = 0.3036020026407088e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1833434647041659;
b = 0.9074658265305127;
v = 0.2832187403926303e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
n = n - 1;
return;
}
//****************************************************************************80
void ld0434 ( double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD0434 computes the 434 point Lebedev angular grid.
//
// Modified:
//
// 12 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Output, double X[N], Y[N], Z[N], W[N], the coordinates
// and weights of the points.
//
{
double a = 0.0;
double b = 0.0;
int n;
double v;
n = 0;
v = 0.5265897968224436e-3;
n = n + gen_oh ( 1, a, b, v, x + n, y + n, z + n, w + n );
v = 0.2548219972002607e-2;
n = n + gen_oh ( 2, a, b, v, x + n, y + n, z + n, w + n );
v = 0.2512317418927307e-2;
n = n + gen_oh ( 3, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6909346307509111;
v = 0.2530403801186355e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1774836054609158;
v = 0.2014279020918528e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4914342637784746;
v = 0.2501725168402936e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6456664707424256;
v = 0.2513267174597564e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2861289010307638;
v = 0.2302694782227416e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7568084367178018e-1;
v = 0.1462495621594614e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3927259763368002;
v = 0.2445373437312980e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.8818132877794288;
v = 0.2417442375638981e-2;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.9776428111182649;
v = 0.1910951282179532e-2;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2054823696403044;
b = 0.8689460322872412;
v = 0.2416930044324775e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5905157048925271;
b = 0.7999278543857286;
v = 0.2512236854563495e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5550152361076807;
b = 0.7717462626915901;
v = 0.2496644054553086e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.9371809858553722;
b = 0.3344363145343455 ;
v = 0.2236607760437849e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
n = n - 1;
return;
}
//****************************************************************************80
void ld0590 ( double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD0590 computes the 590 point Lebedev angular grid.
//
// Modified:
//
// 12 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Output, double X[N], Y[N], Z[N], W[N], the coordinates
// and weights of the points.
//
{
double a = 0.0;
double b = 0.0;
int n;
double v;
n = 0;
v = 0.3095121295306187e-3;
n = n + gen_oh ( 1, a, b, v, x + n, y + n, z + n, w + n );
v = 0.1852379698597489e-2;
n = n + gen_oh ( 3, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7040954938227469;
v = 0.1871790639277744e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6807744066455243;
v = 0.1858812585438317e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6372546939258752;
v = 0.1852028828296213e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5044419707800358;
v = 0.1846715956151242e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4215761784010967;
v = 0.1818471778162769e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3317920736472123;
v = 0.1749564657281154e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2384736701421887;
v = 0.1617210647254411e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1459036449157763;
v = 0.1384737234851692e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6095034115507196e-1;
v = 0.9764331165051050e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6116843442009876;
v = 0.1857161196774078e-2;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3964755348199858;
v = 0.1705153996395864e-2;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1724782009907724;
v = 0.1300321685886048e-2;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5610263808622060;
b = 0.3518280927733519;
v = 0.1842866472905286e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4742392842551980;
b = 0.2634716655937950;
v = 0.1802658934377451e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5984126497885380;
b = 0.1816640840360209;
v = 0.1849830560443660e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3791035407695563;
b = 0.1720795225656878;
v = 0.1713904507106709e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2778673190586244;
b = 0.8213021581932511e-1;
v = 0.1555213603396808e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5033564271075117;
b = 0.8999205842074875e-1;
v = 0.1802239128008525e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
n = n - 1;
return;
}
//****************************************************************************80
void ld0770 ( double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD0770 computes the 770 point Lebedev angular grid.
//
// Modified:
//
// 12 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Output, double X[N], Y[N], Z[N], W[N], the coordinates
// and weights of the points.
//
{
double a = 0.0;
double b = 0.0;
int n;
double v;
n = 0;
v = 0.2192942088181184e-3;
n = n + gen_oh ( 1, a, b, v, x + n, y + n, z + n, w + n );
v = 0.1436433617319080e-2;
n = n + gen_oh ( 2, a, b, v, x + n, y + n, z + n, w + n );
v = 0.1421940344335877e-2;
n = n + gen_oh ( 3, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5087204410502360e-1;
v = 0.6798123511050502e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1228198790178831;
v = 0.9913184235294912e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2026890814408786;
v = 0.1180207833238949e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2847745156464294;
v = 0.1296599602080921e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3656719078978026;
v = 0.1365871427428316e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4428264886713469;
v = 0.1402988604775325e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5140619627249735;
v = 0.1418645563595609e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6306401219166803;
v = 0.1421376741851662e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6716883332022612;
v = 0.1423996475490962e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6979792685336881;
v = 0.1431554042178567e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1446865674195309;
v = 0.9254401499865368e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3390263475411216;
v = 0.1250239995053509e-2;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5335804651263506;
v = 0.1394365843329230e-2;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6944024393349413e-1;
b = 0.2355187894242326;
v = 0.1127089094671749e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2269004109529460;
b = 0.4102182474045730;
v = 0.1345753760910670e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.8025574607775339e-1;
b = 0.6214302417481605;
v = 0.1424957283316783e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1467999527896572;
b = 0.3245284345717394;
v = 0.1261523341237750e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1571507769824727;
b = 0.5224482189696630;
v = 0.1392547106052696e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2365702993157246;
b = 0.6017546634089558;
v = 0.1418761677877656e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7714815866765732e-1;
b = 0.4346575516141163;
v = 0.1338366684479554e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3062936666210730;
b = 0.4908826589037616;
v = 0.1393700862676131e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3822477379524787;
b = 0.5648768149099500;
v = 0.1415914757466932e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
n = n - 1;
return;
}
//****************************************************************************80
void ld0974 ( double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD0974 computes the 974 point Lebedev angular grid.
//
// Modified:
//
// 12 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Output, double X[N], Y[N], Z[N], W[N], the coordinates
// and weights of the points.
//
{
double a = 0.0;
double b = 0.0;
int n;
double v;
n = 0;
v = 0.1438294190527431e-3;
n = n + gen_oh ( 1, a, b, v, x + n, y + n, z + n, w + n );
v = 0.1125772288287004e-2;
n = n + gen_oh ( 3, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4292963545341347e-1;
v = 0.4948029341949241e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1051426854086404;
v = 0.7357990109125470e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1750024867623087;
v = 0.8889132771304384e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2477653379650257;
v = 0.9888347838921435e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3206567123955957;
v = 0.1053299681709471e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3916520749849983;
v = 0.1092778807014578e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4590825874187624;
v = 0.1114389394063227e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5214563888415861;
v = 0.1123724788051555e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6253170244654199;
v = 0.1125239325243814e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6637926744523170;
v = 0.1126153271815905e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6910410398498301;
v = 0.1130286931123841e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7052907007457760;
v = 0.1134986534363955e-2;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1236686762657990;
v = 0.6823367927109931e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2940777114468387;
v = 0.9454158160447096e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4697753849207649;
v = 0.1074429975385679e-2;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6334563241139567;
v = 0.1129300086569132e-2;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5974048614181342e-1;
b = 0.2029128752777523;
v = 0.8436884500901954e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1375760408473636;
b = 0.4602621942484054;
v = 0.1075255720448885e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3391016526336286;
b = 0.5030673999662036;
v = 0.1108577236864462e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1271675191439820;
b = 0.2817606422442134;
v = 0.9566475323783357e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2693120740413512;
b = 0.4331561291720157;
v = 0.1080663250717391e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1419786452601918;
b = 0.6256167358580814;
v = 0.1126797131196295e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6709284600738255e-1;
b = 0.3798395216859157;
v = 0.1022568715358061e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7057738183256172e-1;
b = 0.5517505421423520;
v = 0.1108960267713108e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2783888477882155;
b = 0.6029619156159187;
v = 0.1122790653435766e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1979578938917407;
b = 0.3589606329589096;
v = 0.1032401847117460e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2087307061103274;
b = 0.5348666438135476;
v = 0.1107249382283854e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4055122137872836;
b = 0.5674997546074373;
v = 0.1121780048519972e-2;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
n = n - 1;
return;
}
//****************************************************************************80
void ld1202 ( double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD1202 computes the 1202 point Lebedev angular grid.
//
// Modified:
//
// 12 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Output, double X[N], Y[N], Z[N], W[N], the coordinates
// and weights of the points.
//
{
double a = 0.0;
double b = 0.0;
int n;
double v;
n = 0;
v = 0.1105189233267572e-3;
n = n + gen_oh ( 1, a, b, v, x + n, y + n, z + n, w + n );
v = 0.9205232738090741e-3;
n = n + gen_oh ( 2, a, b, v, x + n, y + n, z + n, w + n );
v = 0.9133159786443561e-3;
n = n + gen_oh ( 3, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3712636449657089e-1;
v = 0.3690421898017899e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.9140060412262223e-1;
v = 0.5603990928680660e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1531077852469906;
v = 0.6865297629282609e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2180928891660612;
v = 0.7720338551145630e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2839874532200175;
v = 0.8301545958894795e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3491177600963764;
v = 0.8686692550179628e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4121431461444309;
v = 0.8927076285846890e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4718993627149127;
v = 0.9060820238568219e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5273145452842337;
v = 0.9119777254940867e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6209475332444019;
v = 0.9128720138604181e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6569722711857291;
v = 0.9130714935691735e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6841788309070143;
v = 0.9152873784554116e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7012604330123631;
v = 0.9187436274321654e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1072382215478166;
v = 0.5176977312965694e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2582068959496968;
v = 0.7331143682101417e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4172752955306717;
v = 0.8463232836379928e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5700366911792503;
v = 0.9031122694253992e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.9827986018263947;
b = 0.1771774022615325;
v = 0.6485778453163257e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.9624249230326228;
b = 0.2475716463426288;
v = 0.7435030910982369e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.9402007994128811;
b = 0.3354616289066489;
v = 0.7998527891839054e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.9320822040143202;
b = 0.3173615246611977;
v = 0.8101731497468018e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.9043674199393299;
b = 0.4090268427085357;
v = 0.8483389574594331e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.8912407560074747;
b = 0.3854291150669224;
v = 0.8556299257311812e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.8676435628462708;
b = 0.4932221184851285;
v = 0.8803208679738260e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.8581979986041619;
b = 0.4785320675922435;
v = 0.8811048182425720e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.8396753624049856;
b = 0.4507422593157064;
v = 0.8850282341265444e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.8165288564022188;
b = 0.5632123020762100;
v = 0.9021342299040653e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.8015469370783529;
b = 0.5434303569693900;
v = 0.9010091677105086e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7773563069070351;
b = 0.5123518486419871;
v = 0.9022692938426915e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7661621213900394;
b = 0.6394279634749102;
v = 0.9158016174693465e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7553584143533510;
b = 0.6269805509024392;
v = 0.9131578003189435e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7344305757559503;
b = 0.6031161693096310;
v = 0.9107813579482705e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7043837184021765;
b = 0.5693702498468441;
v = 0.9105760258970126e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
n = n - 1;
return;
}
//****************************************************************************80
void ld1454 ( double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD1454 computes the 1454 point Lebedev angular grid.
//
// Modified:
//
// 12 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Output, double X[N], Y[N], Z[N], W[N], the coordinates
// and weights of the points.
//
{
double a = 0.0;
double b = 0.0;
int n;
double v;
n = 0;
v = 0.7777160743261247e-4;
n = n + gen_oh ( 1, a, b, v, x + n, y + n, z + n, w + n );
v = 0.7557646413004701e-3;
n = n + gen_oh ( 3, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3229290663413854e-1;
v = 0.2841633806090617e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.8036733271462222e-1;
v = 0.4374419127053555e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1354289960531653;
v = 0.5417174740872172e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1938963861114426;
v = 0.6148000891358593e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2537343715011275;
v = 0.6664394485800705e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3135251434752570;
v = 0.7025039356923220e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3721558339375338;
v = 0.7268511789249627e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4286809575195696;
v = 0.7422637534208629e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4822510128282994;
v = 0.7509545035841214e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5320679333566263;
v = 0.7548535057718401e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6172998195394274;
v = 0.7554088969774001e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6510679849127481;
v = 0.7553147174442808e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6777315251687360;
v = 0.7564767653292297e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6963109410648741;
v = 0.7587991808518730e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7058935009831749;
v = 0.7608261832033027e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.9955546194091857;
v = 0.4021680447874916e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.9734115901794209;
v = 0.5804871793945964e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.9275693732388626;
v = 0.6792151955945159e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.8568022422795103;
v = 0.7336741211286294e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7623495553719372;
v = 0.7581866300989608e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5707522908892223;
b = 0.4387028039889501;
v = 0.7538257859800743e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5196463388403083;
b = 0.3858908414762617;
v = 0.7483517247053123e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4646337531215351;
b = 0.3301937372343854;
v = 0.7371763661112059e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4063901697557691;
b = 0.2725423573563777;
v = 0.7183448895756934e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3456329466643087;
b = 0.2139510237495250;
v = 0.6895815529822191e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2831395121050332;
b = 0.1555922309786647;
v = 0.6480105801792886e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2197682022925330;
b = 0.9892878979686097e-1;
v = 0.5897558896594636e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1564696098650355;
b = 0.4598642910675510e-1;
v = 0.5095708849247346e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6027356673721295;
b = 0.3376625140173426;
v = 0.7536906428909755e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5496032320255096;
b = 0.2822301309727988;
v = 0.7472505965575118e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4921707755234567;
b = 0.2248632342592540;
v = 0.7343017132279698e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4309422998598483;
b = 0.1666224723456479;
v = 0.7130871582177445e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3664108182313672;
b = 0.1086964901822169;
v = 0.6817022032112776e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2990189057758436;
b = 0.5251989784120085e-1;
v = 0.6380941145604121e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6268724013144998;
b = 0.2297523657550023;
v = 0.7550381377920310e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5707324144834607;
b = 0.1723080607093800;
v = 0.7478646640144802e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5096360901960365;
b = 0.1140238465390513;
v = 0.7335918720601220e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4438729938312456;
b = 0.5611522095882537e-1;
v = 0.7110120527658118e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6419978471082389;
b = 0.1164174423140873;
v = 0.7571363978689501e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5817218061802611;
b = 0.5797589531445219e-1;
v = 0.7489908329079234e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
n = n - 1;
return;
}
//****************************************************************************80
void ld1730 ( double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD1730 computes the 1730 point Lebedev angular grid.
//
// Modified:
//
// 12 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Output, double X[N], Y[N], Z[N], W[N], the coordinates
// and weights of the points.
//
{
double a = 0.0;
double b = 0.0;
int n;
double v;
n = 0;
v = 0.6309049437420976e-4;
n = n + gen_oh ( 1, a, b, v, x + n, y + n, z + n, w + n );
v = 0.6398287705571748e-3;
n = n + gen_oh ( 2, a, b, v, x + n, y + n, z + n, w + n );
v = 0.6357185073530720e-3;
n = n + gen_oh ( 3, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2860923126194662e-1;
v = 0.2221207162188168e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7142556767711522e-1;
v = 0.3475784022286848e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1209199540995559;
v = 0.4350742443589804e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1738673106594379;
v = 0.4978569136522127e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2284645438467734;
v = 0.5435036221998053e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2834807671701512;
v = 0.5765913388219542e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3379680145467339;
v = 0.6001200359226003e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3911355454819537;
v = 0.6162178172717512e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4422860353001403;
v = 0.6265218152438485e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4907781568726057;
v = 0.6323987160974212e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5360006153211468;
v = 0.6350767851540569e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6142105973596603;
v = 0.6354362775297107e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6459300387977504;
v = 0.6352302462706235e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6718056125089225;
v = 0.6358117881417972e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6910888533186254;
v = 0.6373101590310117e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7030467416823252;
v = 0.6390428961368665e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.8354951166354646e-1;
v = 0.3186913449946576e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2050143009099486;
v = 0.4678028558591711e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3370208290706637;
v = 0.5538829697598626e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4689051484233963;
v = 0.6044475907190476e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5939400424557334;
v = 0.6313575103509012e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1394983311832261;
b = 0.4097581162050343e-1;
v = 0.4078626431855630e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1967999180485014;
b = 0.8851987391293348e-1;
v = 0.4759933057812725e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2546183732548967;
b = 0.1397680182969819;
v = 0.5268151186413440e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3121281074713875;
b = 0.1929452542226526;
v = 0.5643048560507316e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3685981078502492;
b = 0.2467898337061562;
v = 0.5914501076613073e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4233760321547856;
b = 0.3003104124785409;
v = 0.6104561257874195e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4758671236059246;
b = 0.3526684328175033;
v = 0.6230252860707806e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5255178579796463;
b = 0.4031134861145713;
v = 0.6305618761760796e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5718025633734589;
b = 0.4509426448342351;
v = 0.6343092767597889e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2686927772723415;
b = 0.4711322502423248e-1;
v = 0.5176268945737826e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3306006819904809;
b = 0.9784487303942695e-1;
v = 0.5564840313313692e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3904906850594983;
b = 0.1505395810025273;
v = 0.5856426671038980e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4479957951904390;
b = 0.2039728156296050;
v = 0.6066386925777091e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5027076848919780;
b = 0.2571529941121107;
v = 0.6208824962234458e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5542087392260217;
b = 0.3092191375815670;
v = 0.6296314297822907e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6020850887375187;
b = 0.3593807506130276;
v = 0.6340423756791859e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4019851409179594;
b = 0.5063389934378671e-1;
v = 0.5829627677107342e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4635614567449800;
b = 0.1032422269160612;
v = 0.6048693376081110e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5215860931591575;
b = 0.1566322094006254;
v = 0.6202362317732461e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5758202499099271;
b = 0.2098082827491099;
v = 0.6299005328403779e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6259893683876795;
b = 0.2618824114553391;
v = 0.6347722390609353e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5313795124811891;
b = 0.5263245019338556e-1;
v = 0.6203778981238834e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5893317955931995;
b = 0.1061059730982005;
v = 0.6308414671239979e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6426246321215801;
b = 0.1594171564034221;
v = 0.6362706466959498e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6511904367376113;
b = 0.5354789536565540e-1;
v = 0.6375414170333233e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
n = n - 1;
return;
}
//****************************************************************************80
void ld2030 ( double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD2030 computes the 2030 point Lebedev angular grid.
//
// Modified:
//
// 12 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Output, double X[N], Y[N], Z[N], W[N], the coordinates
// and weights of the points.
//
{
double a = 0.0;
double b = 0.0;
int n;
double v;
n = 0;
v = 0.4656031899197431e-4;
n = n + gen_oh ( 1, a, b, v, x + n, y + n, z + n, w + n );
v = 0.5421549195295507e-3;
n = n + gen_oh ( 3, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2540835336814348e-1;
v = 0.1778522133346553e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6399322800504915e-1;
v = 0.2811325405682796e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1088269469804125;
v = 0.3548896312631459e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1570670798818287;
v = 0.4090310897173364e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2071163932282514;
v = 0.4493286134169965e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2578914044450844;
v = 0.4793728447962723e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3085687558169623;
v = 0.5015415319164265e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3584719706267024;
v = 0.5175127372677937e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4070135594428709;
v = 0.5285522262081019e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4536618626222638;
v = 0.5356832703713962e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4979195686463577;
v = 0.5397914736175170e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5393075111126999;
v = 0.5416899441599930e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6115617676843916;
v = 0.5419308476889938e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6414308435160159;
v = 0.5416936902030596e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6664099412721607;
v = 0.5419544338703164e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6859161771214913;
v = 0.5428983656630975e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6993625593503890;
v = 0.5442286500098193e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7062393387719380;
v = 0.5452250345057301e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7479028168349763e-1;
v = 0.2568002497728530e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1848951153969366;
v = 0.3827211700292145e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3059529066581305;
v = 0.4579491561917824e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4285556101021362;
v = 0.5042003969083574e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5468758653496526;
v = 0.5312708889976025e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6565821978343439;
v = 0.5438401790747117e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1253901572367117;
b = 0.3681917226439641e-1;
v = 0.3316041873197344e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1775721510383941;
b = 0.7982487607213301e-1;
v = 0.3899113567153771e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2305693358216114;
b = 0.1264640966592335;
v = 0.4343343327201309e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2836502845992063;
b = 0.1751585683418957;
v = 0.4679415262318919e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3361794746232590;
b = 0.2247995907632670;
v = 0.4930847981631031e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3875979172264824;
b = 0.2745299257422246;
v = 0.5115031867540091e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4374019316999074;
b = 0.3236373482441118;
v = 0.5245217148457367e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4851275843340022;
b = 0.3714967859436741;
v = 0.5332041499895321e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5303391803806868;
b = 0.4175353646321745;
v = 0.5384583126021542e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5726197380596287;
b = 0.4612084406355461;
v = 0.5411067210798852e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2431520732564863;
b = 0.4258040133043952e-1;
v = 0.4259797391468714e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3002096800895869;
b = 0.8869424306722721e-1;
v = 0.4604931368460021e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3558554457457432;
b = 0.1368811706510655;
v = 0.4871814878255202e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4097782537048887;
b = 0.1860739985015033;
v = 0.5072242910074885e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4616337666067458;
b = 0.2354235077395853;
v = 0.5217069845235350e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5110707008417874;
b = 0.2842074921347011;
v = 0.5315785966280310e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5577415286163795;
b = 0.3317784414984102;
v = 0.5376833708758905e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6013060431366950;
b = 0.3775299002040700;
v = 0.5408032092069521e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3661596767261781;
b = 0.4599367887164592e-1;
v = 0.4842744917904866e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4237633153506581;
b = 0.9404893773654421e-1;
v = 0.5048926076188130e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4786328454658452;
b = 0.1431377109091971;
v = 0.5202607980478373e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5305702076789774;
b = 0.1924186388843570;
v = 0.5309932388325743e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5793436224231788;
b = 0.2411590944775190;
v = 0.5377419770895208e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6247069017094747;
b = 0.2886871491583605;
v = 0.5411696331677717e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4874315552535204;
b = 0.4804978774953206e-1;
v = 0.5197996293282420e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5427337322059053;
b = 0.9716857199366665e-1;
v = 0.5311120836622945e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5943493747246700;
b = 0.1465205839795055;
v = 0.5384309319956951e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6421314033564943;
b = 0.1953579449803574;
v = 0.5421859504051886e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6020628374713980;
b = 0.4916375015738108e-1;
v = 0.5390948355046314e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6529222529856881;
b = 0.9861621540127005e-1;
v = 0.5433312705027845e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
n = n - 1;
return;
}
//****************************************************************************80
void ld2354 ( double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD2354 computes the 2354 point Lebedev angular grid.
//
// Modified:
//
// 12 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Output, double X[N], Y[N], Z[N], W[N], the coordinates
// and weights of the points.
//
{
double a = 0.0;
double b = 0.0;
int n;
double v;
n = 0;
v = 0.3922616270665292e-4;
n = n + gen_oh ( 1, a, b, v, x + n, y + n, z + n, w + n );
v = 0.4703831750854424e-3;
n = n + gen_oh ( 2, a, b, v, x + n, y + n, z + n, w + n );
v = 0.4678202801282136e-3;
n = n + gen_oh ( 3, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2290024646530589e-1;
v = 0.1437832228979900e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5779086652271284e-1;
v = 0.2303572493577644e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.9863103576375984e-1;
v = 0.2933110752447454e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1428155792982185;
v = 0.3402905998359838e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1888978116601463;
v = 0.3759138466870372e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2359091682970210;
v = 0.4030638447899798e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2831228833706171;
v = 0.4236591432242211e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3299495857966693;
v = 0.4390522656946746e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3758840802660796;
v = 0.4502523466626247e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4204751831009480;
v = 0.4580577727783541e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4633068518751051;
v = 0.4631391616615899e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5039849474507313;
v = 0.4660928953698676e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5421265793440747;
v = 0.4674751807936953e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6092660230557310;
v = 0.4676414903932920e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6374654204984869;
v = 0.4674086492347870e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6615136472609892;
v = 0.4674928539483207e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6809487285958127;
v = 0.4680748979686447e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6952980021665196;
v = 0.4690449806389040e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7041245497695400;
v = 0.4699877075860818e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6744033088306065e-1;
v = 0.2099942281069176e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1678684485334166;
v = 0.3172269150712804e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2793559049539613;
v = 0.3832051358546523e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3935264218057639;
v = 0.4252193818146985e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5052629268232558;
v = 0.4513807963755000e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6107905315437531;
v = 0.4657797469114178e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1135081039843524;
b = 0.3331954884662588e-1;
v = 0.2733362800522836e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1612866626099378;
b = 0.7247167465436538e-1;
v = 0.3235485368463559e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2100786550168205;
b = 0.1151539110849745;
v = 0.3624908726013453e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2592282009459942;
b = 0.1599491097143677;
v = 0.3925540070712828e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3081740561320203;
b = 0.2058699956028027;
v = 0.4156129781116235e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3564289781578164;
b = 0.2521624953502911;
v = 0.4330644984623263e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4035587288240703;
b = 0.2982090785797674;
v = 0.4459677725921312e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4491671196373903;
b = 0.3434762087235733;
v = 0.4551593004456795e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4928854782917489;
b = 0.3874831357203437;
v = 0.4613341462749918e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5343646791958988;
b = 0.4297814821746926;
v = 0.4651019618269806e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5732683216530990;
b = 0.4699402260943537;
v = 0.4670249536100625e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2214131583218986;
b = 0.3873602040643895e-1;
v = 0.3549555576441708e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2741796504750071;
b = 0.8089496256902013e-1;
v = 0.3856108245249010e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3259797439149485;
b = 0.1251732177620872;
v = 0.4098622845756882e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3765441148826891;
b = 0.1706260286403185;
v = 0.4286328604268950e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4255773574530558;
b = 0.2165115147300408;
v = 0.4427802198993945e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4727795117058430;
b = 0.2622089812225259;
v = 0.4530473511488561e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5178546895819012;
b = 0.3071721431296201;
v = 0.4600805475703138e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5605141192097460;
b = 0.3508998998801138;
v = 0.4644599059958017e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6004763319352512;
b = 0.3929160876166931;
v = 0.4667274455712508e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3352842634946949;
b = 0.4202563457288019e-1;
v = 0.4069360518020356e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3891971629814670;
b = 0.8614309758870850e-1;
v = 0.4260442819919195e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4409875565542281;
b = 0.1314500879380001;
v = 0.4408678508029063e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4904893058592484;
b = 0.1772189657383859;
v = 0.4518748115548597e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5375056138769549;
b = 0.2228277110050294;
v = 0.4595564875375116e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5818255708669969;
b = 0.2677179935014386;
v = 0.4643988774315846e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6232334858144959;
b = 0.3113675035544165;
v = 0.4668827491646946e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4489485354492058;
b = 0.4409162378368174e-1;
v = 0.4400541823741973e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5015136875933150;
b = 0.8939009917748489e-1;
v = 0.4514512890193797e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5511300550512623;
b = 0.1351806029383365;
v = 0.4596198627347549e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5976720409858000;
b = 0.1808370355053196;
v = 0.4648659016801781e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6409956378989354;
b = 0.2257852192301602;
v = 0.4675502017157673e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5581222330827514;
b = 0.4532173421637160e-1;
v = 0.4598494476455523e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6074705984161695;
b = 0.9117488031840314e-1;
v = 0.4654916955152048e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6532272537379033;
b = 0.1369294213140155;
v = 0.4684709779505137e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6594761494500487;
b = 0.4589901487275583e-1;
v = 0.4691445539106986e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
n = n - 1;
return;
}
//****************************************************************************80
void ld2702 ( double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD2702 computes the 2702 point Lebedev angular grid.
//
// Modified:
//
// 12 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Output, double X[N], Y[N], Z[N], W[N], the coordinates
// and weights of the points.
//
{
double a = 0.0;
double b = 0.0;
int n;
double v;
n = 0;
v = 0.2998675149888161e-4;
n = n + gen_oh ( 1, a, b, v, x + n, y + n, z + n, w + n );
v = 0.4077860529495355e-3;
n = n + gen_oh ( 3, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2065562538818703e-1;
v = 0.1185349192520667e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5250918173022379e-1;
v = 0.1913408643425751e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.8993480082038376e-1;
v = 0.2452886577209897e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1306023924436019;
v = 0.2862408183288702e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1732060388531418;
v = 0.3178032258257357e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2168727084820249;
v = 0.3422945667633690e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2609528309173586;
v = 0.3612790520235922e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3049252927938952;
v = 0.3758638229818521e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3483484138084404;
v = 0.3868711798859953e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3908321549106406;
v = 0.3949429933189938e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4320210071894814;
v = 0.4006068107541156e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4715824795890053;
v = 0.4043192149672723e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5091984794078453;
v = 0.4064947495808078e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5445580145650803;
v = 0.4075245619813152e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6072575796841768;
v = 0.4076423540893566e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6339484505755803;
v = 0.4074280862251555e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6570718257486958;
v = 0.4074163756012244e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6762557330090709;
v = 0.4077647795071246e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6911161696923790;
v = 0.4084517552782530e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7012841911659961;
v = 0.4092468459224052e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7064559272410020;
v = 0.4097872687240906e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6123554989894765e-1;
v = 0.1738986811745028e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1533070348312393;
v = 0.2659616045280191e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2563902605244206;
v = 0.3240596008171533e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3629346991663361;
v = 0.3621195964432943e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4683949968987538;
v = 0.3868838330760539e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5694479240657952;
v = 0.4018911532693111e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6634465430993955;
v = 0.4089929432983252e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1033958573552305;
b = 0.3034544009063584e-1;
v = 0.2279907527706409e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1473521412414395;
b = 0.6618803044247135e-1;
v = 0.2715205490578897e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1924552158705967;
b = 0.1054431128987715;
v = 0.3057917896703976e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2381094362890328;
b = 0.1468263551238858;
v = 0.3326913052452555e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2838121707936760;
b = 0.1894486108187886;
v = 0.3537334711890037e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3291323133373415;
b = 0.2326374238761579;
v = 0.3700567500783129e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3736896978741460;
b = 0.2758485808485768;
v = 0.3825245372589122e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4171406040760013;
b = 0.3186179331996921;
v = 0.3918125171518296e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4591677985256915;
b = 0.3605329796303794;
v = 0.3984720419937579e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4994733831718418;
b = 0.4012147253586509;
v = 0.4029746003338211e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5377731830445096;
b = 0.4403050025570692;
v = 0.4057428632156627e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5737917830001331;
b = 0.4774565904277483;
v = 0.4071719274114857e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2027323586271389;
b = 0.3544122504976147e-1;
v = 0.2990236950664119e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2516942375187273;
b = 0.7418304388646328e-1;
v = 0.3262951734212878e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3000227995257181;
b = 0.1150502745727186;
v = 0.3482634608242413e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3474806691046342;
b = 0.1571963371209364;
v = 0.3656596681700892e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3938103180359209;
b = 0.1999631877247100;
v = 0.3791740467794218e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4387519590455703;
b = 0.2428073457846535;
v = 0.3894034450156905e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4820503960077787;
b = 0.2852575132906155;
v = 0.3968600245508371e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5234573778475101;
b = 0.3268884208674639;
v = 0.4019931351420050e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5627318647235282;
b = 0.3673033321675939;
v = 0.4052108801278599e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5996390607156954;
b = 0.4061211551830290;
v = 0.4068978613940934e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3084780753791947;
b = 0.3860125523100059e-1;
v = 0.3454275351319704e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3589988275920223;
b = 0.7928938987104867e-1;
v = 0.3629963537007920e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4078628415881973;
b = 0.1212614643030087;
v = 0.3770187233889873e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4549287258889735;
b = 0.1638770827382693;
v = 0.3878608613694378e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5000278512957279;
b = 0.2065965798260176;
v = 0.3959065270221274e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5429785044928199;
b = 0.2489436378852235;
v = 0.4015286975463570e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5835939850491711;
b = 0.2904811368946891;
v = 0.4050866785614717e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6216870353444856;
b = 0.3307941957666609;
v = 0.4069320185051913e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4151104662709091;
b = 0.4064829146052554e-1;
v = 0.3760120964062763e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4649804275009218;
b = 0.8258424547294755e-1;
v = 0.3870969564418064e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5124695757009662;
b = 0.1251841962027289;
v = 0.3955287790534055e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5574711100606224;
b = 0.1679107505976331;
v = 0.4015361911302668e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5998597333287227;
b = 0.2102805057358715;
v = 0.4053836986719548e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6395007148516600;
b = 0.2518418087774107;
v = 0.4073578673299117e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5188456224746252;
b = 0.4194321676077518e-1;
v = 0.3954628379231406e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5664190707942778;
b = 0.8457661551921499e-1;
v = 0.4017645508847530e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6110464353283153;
b = 0.1273652932519396;
v = 0.4059030348651293e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6526430302051563;
b = 0.1698173239076354;
v = 0.4080565809484880e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6167551880377548;
b = 0.4266398851548864e-1;
v = 0.4063018753664651e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6607195418355383;
b = 0.8551925814238349e-1;
v = 0.4087191292799671e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
n = n - 1;
return;
}
//****************************************************************************80
void ld3074 ( double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD3074 computes the 3074 point Lebedev angular grid.
//
// Modified:
//
// 12 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Output, double X[N], Y[N], Z[N], W[N], the coordinates
// and weights of the points.
//
{
double a = 0.0;
double b = 0.0;
int n;
double v;
n = 0;
v = 0.2599095953754734e-4;
n = n + gen_oh ( 1, a, b, v, x + n, y + n, z + n, w + n );
v = 0.3603134089687541e-3;
n = n + gen_oh ( 2, a, b, v, x + n, y + n, z + n, w + n );
v = 0.3586067974412447e-3;
n = n + gen_oh ( 3, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1886108518723392e-1;
v = 0.9831528474385880e-4;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4800217244625303e-1;
v = 0.1605023107954450e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.8244922058397242e-1;
v = 0.2072200131464099e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1200408362484023;
v = 0.2431297618814187e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1595773530809965;
v = 0.2711819064496707e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2002635973434064;
v = 0.2932762038321116e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2415127590139982;
v = 0.3107032514197368e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2828584158458477;
v = 0.3243808058921213e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3239091015338138;
v = 0.3349899091374030e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3643225097962194;
v = 0.3430580688505218e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4037897083691802;
v = 0.3490124109290343e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4420247515194127;
v = 0.3532148948561955e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4787572538464938;
v = 0.3559862669062833e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5137265251275234;
v = 0.3576224317551411e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5466764056654611;
v = 0.3584050533086076e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6054859420813535;
v = 0.3584903581373224e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6308106701764562;
v = 0.3582991879040586e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6530369230179584;
v = 0.3582371187963125e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6718609524611158;
v = 0.3584353631122350e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6869676499894013;
v = 0.3589120166517785e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6980467077240748;
v = 0.3595445704531601e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7048241721250522;
v = 0.3600943557111074e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5591105222058232e-1;
v = 0.1456447096742039e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1407384078513916;
v = 0.2252370188283782e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2364035438976309;
v = 0.2766135443474897e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3360602737818170;
v = 0.3110729491500851e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4356292630054665;
v = 0.3342506712303391e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5321569415256174;
v = 0.3491981834026860e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6232956305040554;
v = 0.3576003604348932e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.9469870086838469e-1;
b = 0.2778748387309470e-1;
v = 0.1921921305788564e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1353170300568141;
b = 0.6076569878628364e-1;
v = 0.2301458216495632e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1771679481726077;
b = 0.9703072762711040e-1;
v = 0.2604248549522893e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2197066664231751;
b = 0.1354112458524762;
v = 0.2845275425870697e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2624783557374927;
b = 0.1750996479744100;
v = 0.3036870897974840e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3050969521214442;
b = 0.2154896907449802;
v = 0.3188414832298066e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3472252637196021;
b = 0.2560954625740152;
v = 0.3307046414722089e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3885610219026360;
b = 0.2965070050624096;
v = 0.3398330969031360e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4288273776062765;
b = 0.3363641488734497;
v = 0.3466757899705373e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4677662471302948;
b = 0.3753400029836788;
v = 0.3516095923230054e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5051333589553359;
b = 0.4131297522144286;
v = 0.3549645184048486e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5406942145810492;
b = 0.4494423776081795;
v = 0.3570415969441392e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5742204122576457;
b = 0.4839938958841502;
v = 0.3581251798496118e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1865407027225188;
b = 0.3259144851070796e-1;
v = 0.2543491329913348e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2321186453689432;
b = 0.6835679505297343e-1;
v = 0.2786711051330776e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2773159142523882;
b = 0.1062284864451989;
v = 0.2985552361083679e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3219200192237254;
b = 0.1454404409323047;
v = 0.3145867929154039e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3657032593944029;
b = 0.1854018282582510;
v = 0.3273290662067609e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4084376778363622;
b = 0.2256297412014750;
v = 0.3372705511943501e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4499004945751427;
b = 0.2657104425000896;
v = 0.3448274437851510e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4898758141326335;
b = 0.3052755487631557;
v = 0.3503592783048583e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5281547442266309;
b = 0.3439863920645423;
v = 0.3541854792663162e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5645346989813992;
b = 0.3815229456121914;
v = 0.3565995517909428e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5988181252159848;
b = 0.4175752420966734;
v = 0.3578802078302898e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2850425424471603;
b = 0.3562149509862536e-1;
v = 0.2958644592860982e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3324619433027876;
b = 0.7330318886871096e-1;
v = 0.3119548129116835e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3785848333076282;
b = 0.1123226296008472;
v = 0.3250745225005984e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4232891028562115;
b = 0.1521084193337708;
v = 0.3355153415935208e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4664287050829722;
b = 0.1921844459223610;
v = 0.3435847568549328e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5078458493735726;
b = 0.2321360989678303;
v = 0.3495786831622488e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5473779816204180;
b = 0.2715886486360520;
v = 0.3537767805534621e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5848617133811376;
b = 0.3101924707571355;
v = 0.3564459815421428e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6201348281584888;
b = 0.3476121052890973;
v = 0.3578464061225468e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3852191185387871;
b = 0.3763224880035108e-1;
v = 0.3239748762836212e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4325025061073423;
b = 0.7659581935637135e-1;
v = 0.3345491784174287e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4778486229734490;
b = 0.1163381306083900;
v = 0.3429126177301782e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5211663693009000;
b = 0.1563890598752899;
v = 0.3492420343097421e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5623469504853703;
b = 0.1963320810149200;
v = 0.3537399050235257e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6012718188659246;
b = 0.2357847407258738;
v = 0.3566209152659172e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6378179206390117;
b = 0.2743846121244060;
v = 0.3581084321919782e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4836936460214534;
b = 0.3895902610739024e-1;
v = 0.3426522117591512e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5293792562683797;
b = 0.7871246819312640e-1;
v = 0.3491848770121379e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5726281253100033;
b = 0.1187963808202981;
v = 0.3539318235231476e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6133658776169068;
b = 0.1587914708061787;
v = 0.3570231438458694e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6515085491865307;
b = 0.1983058575227646;
v = 0.3586207335051714e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5778692716064976;
b = 0.3977209689791542e-1;
v = 0.3541196205164025e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6207904288086192;
b = 0.7990157592981152e-1;
v = 0.3574296911573953e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6608688171046802;
b = 0.1199671308754309;
v = 0.3591993279818963e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6656263089489130;
b = 0.4015955957805969e-1;
v = 0.3595855034661997e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
n = n - 1;
return;
}
//****************************************************************************80
void ld3470 ( double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD3470 computes the 3470 point Lebedev angular grid.
//
// Modified:
//
// 12 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Output, double X[N], Y[N], Z[N], W[N], the coordinates
// and weights of the points.
//
{
double a = 0.0;
double b = 0.0;
int n;
double v;
n = 0;
v = 0.2040382730826330e-4;
n = n + gen_oh ( 1, a, b, v, x + n, y + n, z + n, w + n );
v = 0.3178149703889544e-3;
n = n + gen_oh ( 3, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1721420832906233e-1;
v = 0.8288115128076110e-4;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4408875374981770e-1;
v = 0.1360883192522954e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7594680813878681e-1;
v = 0.1766854454542662e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1108335359204799;;
v = 0.2083153161230153e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1476517054388567;
v = 0.2333279544657158e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1856731870860615;
v = 0.2532809539930247e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2243634099428821;
v = 0.2692472184211158e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2633006881662727;
v = 0.2819949946811885e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3021340904916283;
v = 0.2920953593973030e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3405594048030089;
v = 0.2999889782948352e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3783044434007372;
v = 0.3060292120496902e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4151194767407910;
v = 0.3105109167522192e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4507705766443257;
v = 0.3136902387550312e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4850346056573187;
v = 0.3157984652454632e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5176950817792470;
v = 0.3170516518425422e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5485384240820989;
v = 0.3176568425633755e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6039117238943308;
v = 0.3177198411207062e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6279956655573113;
v = 0.3175519492394733e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6493636169568952;
v = 0.3174654952634756e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6677644117704504;
v = 0.3175676415467654e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6829368572115624;
v = 0.3178923417835410e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6946195818184121;
v = 0.3183788287531909e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7025711542057026;
v = 0.3188755151918807e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7066004767140119;
v = 0.3191916889313849e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5132537689946062e-1;
v = 0.1231779611744508e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1297994661331225;
v = 0.1924661373839880e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2188852049401307;
v = 0.2380881867403424e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3123174824903457;
v = 0.2693100663037885e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4064037620738195;
v = 0.2908673382834366e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4984958396944782;
v = 0.3053914619381535e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5864975046021365;
v = 0.3143916684147777e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6686711634580175;
v = 0.3187042244055363e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.8715738780835950e-1;
b = 0.2557175233367578e-1;
v = 0.1635219535869790e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1248383123134007;
b = 0.5604823383376681e-1;
v = 0.1968109917696070e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1638062693383378;
b = 0.8968568601900765e-1;
v = 0.2236754342249974e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2035586203373176;
b = 0.1254086651976279;
v = 0.2453186687017181e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2436798975293774;
b = 0.1624780150162012;
v = 0.2627551791580541e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2838207507773806;
b = 0.2003422342683208;
v = 0.2767654860152220e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3236787502217692;
b = 0.2385628026255263;
v = 0.2879467027765895e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3629849554840691;
b = 0.2767731148783578;
v = 0.2967639918918702e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4014948081992087;
b = 0.3146542308245309;
v = 0.3035900684660351e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4389818379260225;
b = 0.3519196415895088;
v = 0.3087338237298308e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4752331143674377;
b = 0.3883050984023654;
v = 0.3124608838860167e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5100457318374018;
b = 0.4235613423908649;
v = 0.3150084294226743e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5432238388954868;
b = 0.4574484717196220;
v = 0.3165958398598402e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5745758685072442;
b = 0.4897311639255524;
v = 0.3174320440957372e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1723981437592809;
b = 0.3010630597881105e-1;
v = 0.2182188909812599e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2149553257844597;
b = 0.6326031554204694e-1;
v = 0.2399727933921445e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2573256081247422;
b = 0.9848566980258631e-1;
v = 0.2579796133514652e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2993163751238106;
b = 0.1350835952384266;
v = 0.2727114052623535e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3407238005148000;
b = 0.1725184055442181;
v = 0.2846327656281355e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3813454978483264;
b = 0.2103559279730725;
v = 0.2941491102051334e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4209848104423343;
b = 0.2482278774554860;
v = 0.3016049492136107e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4594519699996300;
b = 0.2858099509982883;
v = 0.3072949726175648e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4965640166185930;
b = 0.3228075659915428;
v = 0.3114768142886460e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5321441655571562;
b = 0.3589459907204151;
v = 0.3143823673666223e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5660208438582166;
b = 0.3939630088864310;
v = 0.3162269764661535e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5980264315964364;
b = 0.4276029922949089;
v = 0.3172164663759821e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2644215852350733;
b = 0.3300939429072552e-1;
v = 0.2554575398967435e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3090113743443063;
b = 0.6803887650078501e-1;
v = 0.2701704069135677e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3525871079197808;
b = 0.1044326136206709;
v = 0.2823693413468940e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3950418005354029;
b = 0.1416751597517679;
v = 0.2922898463214289e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4362475663430163;
b = 0.1793408610504821;
v = 0.3001829062162428e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4760661812145854;
b = 0.2170630750175722;
v = 0.3062890864542953e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5143551042512103;
b = 0.2545145157815807;
v = 0.3108328279264746e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5509709026935597;
b = 0.2913940101706601;
v = 0.3140243146201245e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5857711030329428;
b = 0.3274169910910705;
v = 0.3160638030977130e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6186149917404392;
b = 0.3623081329317265;
v = 0.3171462882206275e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3586894569557064;
b = 0.3497354386450040e-1;
v = 0.2812388416031796e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4035266610019441;
b = 0.7129736739757095e-1;
v = 0.2912137500288045e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4467775312332510;
b = 0.1084758620193165;
v = 0.2993241256502206e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4883638346608543;
b = 0.1460915689241772;
v = 0.3057101738983822e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5281908348434601;
b = 0.1837790832369980;
v = 0.3105319326251432e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5661542687149311;
b = 0.2212075390874021;
v = 0.3139565514428167e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6021450102031452;
b = 0.2580682841160985;
v = 0.3161543006806366e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6360520783610050;
b = 0.2940656362094121;
v = 0.3172985960613294e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4521611065087196;
b = 0.3631055365867002e-1;
v = 0.2989400336901431e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4959365651560963;
b = 0.7348318468484350e-1;
v = 0.3054555883947677e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5376815804038283;
b = 0.1111087643812648;
v = 0.3104764960807702e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5773314480243768;
b = 0.1488226085145408;
v = 0.3141015825977616e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6148113245575056;
b = 0.1862892274135151;
v = 0.3164520621159896e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6500407462842380;
b = 0.2231909701714456;
v = 0.3176652305912204e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5425151448707213;
b = 0.3718201306118944e-1;
v = 0.3105097161023939e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5841860556907931;
b = 0.7483616335067346e-1;
v = 0.3143014117890550e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6234632186851500;
b = 0.1125990834266120;
v = 0.3168172866287200e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6602934551848843;
b = 0.1501303813157619;
v = 0.3181401865570968e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6278573968375105;
b = 0.3767559930245720e-1;
v = 0.3170663659156037e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6665611711264577;
b = 0.7548443301360158e-1;
v = 0.3185447944625510e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
n = n - 1;
return;
}
//****************************************************************************80
void ld3890 ( double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD3890 computes the 3890 point Lebedev angular grid.
//
// Modified:
//
// 12 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Output, double X[N], Y[N], Z[N], W[N], the coordinates
// and weights of the points.
//
{
double a = 0.0;
double b = 0.0;
int n;
double v;
n = 0;
v = 0.1807395252196920e-4;
n = n + gen_oh ( 1, a, b, v, x + n, y + n, z + n, w + n );
v = 0.2848008782238827e-3;
n = n + gen_oh ( 2, a, b, v, x + n, y + n, z + n, w + n );
v = 0.2836065837530581e-3;
n = n + gen_oh ( 3, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1587876419858352e-1;
v = 0.7013149266673816e-4;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4069193593751206e-1;
v = 0.1162798021956766e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7025888115257997e-1;
v = 0.1518728583972105e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1027495450028704;
v = 0.1798796108216934e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1371457730893426;
v = 0.2022593385972785e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1727758532671953;
v = 0.2203093105575464e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2091492038929037;
v = 0.2349294234299855e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2458813281751915;
v = 0.2467682058747003e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2826545859450066;
v = 0.2563092683572224e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3191957291799622;
v = 0.2639253896763318e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3552621469299578;
v = 0.2699137479265108e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3906329503406230;
v = 0.2745196420166739e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4251028614093031;
v = 0.2779529197397593e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4584777520111870;
v = 0.2803996086684265e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4905711358710193;
v = 0.2820302356715842e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5212011669847385;
v = 0.2830056747491068e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5501878488737995;
v = 0.2834808950776839e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6025037877479342;
v = 0.2835282339078929e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6254572689549016;
v = 0.2833819267065800e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6460107179528248;
v = 0.2832858336906784e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6639541138154251;
v = 0.2833268235451244e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6790688515667495;
v = 0.2835432677029253e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6911338580371512;
v = 0.2839091722743049e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6999385956126490;
v = 0.2843308178875841e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7053037748656896;
v = 0.2846703550533846e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4732224387180115e-1;
v = 0.1051193406971900e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1202100529326803;
v = 0.1657871838796974e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2034304820664855;
v = 0.2064648113714232e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2912285643573002;
v = 0.2347942745819741e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3802361792726768;
v = 0.2547775326597726e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4680598511056146;
v = 0.2686876684847025e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5528151052155599;
v = 0.2778665755515867e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6329386307803041;
v = 0.2830996616782929e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.8056516651369069e-1;
b = 0.2363454684003124e-1;
v = 0.1403063340168372e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1156476077139389;
b = 0.5191291632545936e-1;
v = 0.1696504125939477e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1520473382760421;
b = 0.8322715736994519e-1;
v = 0.1935787242745390e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1892986699745931;
b = 0.1165855667993712;
v = 0.2130614510521968e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2270194446777792;
b = 0.1513077167409504;
v = 0.2289381265931048e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2648908185093273;
b = 0.1868882025807859;
v = 0.2418630292816186e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3026389259574136;
b = 0.2229277629776224;
v = 0.2523400495631193e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3400220296151384;
b = 0.2590951840746235;
v = 0.2607623973449605e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3768217953335510;
b = 0.2951047291750847;
v = 0.2674441032689209e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4128372900921884;
b = 0.3307019714169930;
v = 0.2726432360343356e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4478807131815630;
b = 0.3656544101087634;
v = 0.2765787685924545e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4817742034089257;
b = 0.3997448951939695;
v = 0.2794428690642224e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5143472814653344;
b = 0.4327667110812024;
v = 0.2814099002062895e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5454346213905650;
b = 0.4645196123532293;
v = 0.2826429531578994e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5748739313170252;
b = 0.4948063555703345;
v = 0.2832983542550884e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1599598738286342;
b = 0.2792357590048985e-1;
v = 0.1886695565284976e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1998097412500951;
b = 0.5877141038139065e-1;
v = 0.2081867882748234e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2396228952566202;
b = 0.9164573914691377e-1;
v = 0.2245148680600796e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2792228341097746;
b = 0.1259049641962687;
v = 0.2380370491511872e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3184251107546741;
b = 0.1610594823400863;
v = 0.2491398041852455e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3570481164426244;
b = 0.1967151653460898;
v = 0.2581632405881230e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3949164710492144;
b = 0.2325404606175168;
v = 0.2653965506227417e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4318617293970503;
b = 0.2682461141151439;
v = 0.2710857216747087e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4677221009931678;
b = 0.3035720116011973;
v = 0.2754434093903659e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5023417939270955;
b = 0.3382781859197439;
v = 0.2786579932519380e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5355701836636128;
b = 0.3721383065625942;
v = 0.2809011080679474e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5672608451328771;
b = 0.4049346360466055;
v = 0.2823336184560987e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5972704202540162;
b = 0.4364538098633802;
v = 0.2831101175806309e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2461687022333596;
b = 0.3070423166833368e-1;
v = 0.2221679970354546e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2881774566286831;
b = 0.6338034669281885e-1;
v = 0.2356185734270703e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3293963604116978;
b = 0.9742862487067941e-1;
v = 0.2469228344805590e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3697303822241377;
b = 0.1323799532282290;
v = 0.2562726348642046e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4090663023135127;
b = 0.1678497018129336;
v = 0.2638756726753028e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4472819355411712;
b = 0.2035095105326114;
v = 0.2699311157390862e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4842513377231437;
b = 0.2390692566672091;
v = 0.2746233268403837e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5198477629962928;
b = 0.2742649818076149;
v = 0.2781225674454771e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5539453011883145;
b = 0.3088503806580094;
v = 0.2805881254045684e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5864196762401251;
b = 0.3425904245906614;
v = 0.2821719877004913e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6171484466668390;
b = 0.3752562294789468;
v = 0.2830222502333124e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3350337830565727;
b = 0.3261589934634747e-1;
v = 0.2457995956744870e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3775773224758284;
b = 0.6658438928081572e-1;
v = 0.2551474407503706e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4188155229848973;
b = 0.1014565797157954;
v = 0.2629065335195311e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4586805892009344;
b = 0.1368573320843822;
v = 0.2691900449925075e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4970895714224235;
b = 0.1724614851951608;
v = 0.2741275485754276e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5339505133960747;
b = 0.2079779381416412;
v = 0.2778530970122595e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5691665792531440;
b = 0.2431385788322288;
v = 0.2805010567646741e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6026387682680377;
b = 0.2776901883049853;
v = 0.2822055834031040e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6342676150163307;
b = 0.3113881356386632;
v = 0.2831016901243473e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4237951119537067;
b = 0.3394877848664351e-1;
v = 0.2624474901131803e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4656918683234929;
b = 0.6880219556291447e-1;
v = 0.2688034163039377e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5058857069185980;
b = 0.1041946859721635;
v = 0.2738932751287636e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5443204666713996;
b = 0.1398039738736393;
v = 0.2777944791242523e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5809298813759742;
b = 0.1753373381196155;
v = 0.2806011661660987e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6156416039447128;
b = 0.2105215793514010;
v = 0.2824181456597460e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6483801351066604;
b = 0.2450953312157051;
v = 0.2833585216577828e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5103616577251688;
b = 0.3485560643800719e-1;
v = 0.2738165236962878e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5506738792580681;
b = 0.7026308631512033e-1;
v = 0.2778365208203180e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5889573040995292;
b = 0.1059035061296403;
v = 0.2807852940418966e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6251641589516930;
b = 0.1414823925236026;
v = 0.2827245949674705e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6592414921570178;
b = 0.1767207908214530;
v = 0.2837342344829828e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5930314017533384;
b = 0.3542189339561672e-1;
v = 0.2809233907610981e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6309812253390175;
b = 0.7109574040369549e-1;
v = 0.2829930809742694e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6666296011353230;
b = 0.1067259792282730;
v = 0.2841097874111479e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6703715271049922;
b = 0.3569455268820809e-1;
v = 0.2843455206008783e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
n = n - 1;
return;
}
//****************************************************************************80
void ld4334 ( double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD4334 computes the 4334 point Lebedev angular grid.
//
// Modified:
//
// 12 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Output, double X[N], Y[N], Z[N], W[N], the coordinates
// and weights of the points.
//
{
double a = 0.0;
double b = 0.0;
int n;
double v;
n = 0;
v = 0.1449063022537883e-4;
n = n + gen_oh ( 1, a, b, v, x + n, y + n, z + n, w + n );
v = 0.2546377329828424e-3;
n = n + gen_oh ( 3, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1462896151831013e-1;
v = 0.6018432961087496e-4;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3769840812493139e-1;
v = 0.1002286583263673e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6524701904096891e-1;
v = 0.1315222931028093e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.9560543416134648e-1;
v = 0.1564213746876724e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1278335898929198;
v = 0.1765118841507736e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1613096104466031;
v = 0.1928737099311080e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1955806225745371;
v = 0.2062658534263270e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2302935218498028;
v = 0.2172395445953787e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2651584344113027;
v = 0.2262076188876047e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2999276825183209;
v = 0.2334885699462397e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3343828669718798;
v = 0.2393355273179203e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3683265013750518;
v = 0.2439559200468863e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4015763206518108;
v = 0.2475251866060002e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4339612026399770;
v = 0.2501965558158773e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4653180651114582;
v = 0.2521081407925925e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4954893331080803;
v = 0.2533881002388081e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5243207068924930;
v = 0.2541582900848261e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5516590479041704;
v = 0.2545365737525860e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6012371927804176;
v = 0.2545726993066799e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6231574466449819;
v = 0.2544456197465555e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6429416514181271;
v = 0.2543481596881064e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6604124272943595;
v = 0.2543506451429194e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6753851470408250;
v = 0.2544905675493763e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6876717970626160;
v = 0.2547611407344429e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6970895061319234;
v = 0.2551060375448869e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7034746912553310;
v = 0.2554291933816039e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7067017217542295;
v = 0.2556255710686343e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4382223501131123e-1;
v = 0.9041339695118195e-4;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1117474077400006;
v = 0.1438426330079022e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1897153252911440;
v = 0.1802523089820518e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2724023009910331;
v = 0.2060052290565496e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3567163308709902;
v = 0.2245002248967466e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4404784483028087;
v = 0.2377059847731150e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5219833154161411;
v = 0.2468118955882525e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5998179868977553;
v = 0.2525410872966528e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6727803154548222;
v = 0.2553101409933397e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7476563943166086e-1;
b = 0.2193168509461185e-1;
v = 0.1212879733668632e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1075341482001416;
b = 0.4826419281533887e-1;
v = 0.1472872881270931e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1416344885203259;
b = 0.7751191883575742e-1;
v = 0.1686846601010828e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1766325315388586;
b = 0.1087558139247680;
v = 0.1862698414660208e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2121744174481514;
b = 0.1413661374253096;
v = 0.2007430956991861e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2479669443408145;
b = 0.1748768214258880;
v = 0.2126568125394796e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2837600452294113;
b = 0.2089216406612073;
v = 0.2224394603372113e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3193344933193984;
b = 0.2431987685545972;
v = 0.2304264522673135e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3544935442438745;
b = 0.2774497054377770;
v = 0.2368854288424087e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3890571932288154;
b = 0.3114460356156915;
v = 0.2420352089461772e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4228581214259090;
b = 0.3449806851913012;
v = 0.2460597113081295e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4557387211304052;
b = 0.3778618641248256;
v = 0.2491181912257687e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4875487950541643;
b = 0.4099086391698978;
v = 0.2513528194205857e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5181436529962997;
b = 0.4409474925853973;
v = 0.2528943096693220e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5473824095600661;
b = 0.4708094517711291;
v = 0.2538660368488136e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5751263398976174;
b = 0.4993275140354637;
v = 0.2543868648299022e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1489515746840028;
b = 0.2599381993267017e-1;
v = 0.1642595537825183e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1863656444351767;
b = 0.5479286532462190e-1;
v = 0.1818246659849308e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2238602880356348;
b = 0.8556763251425254e-1;
v = 0.1966565649492420e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2612723375728160;
b = 0.1177257802267011;
v = 0.2090677905657991e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2984332990206190;
b = 0.1508168456192700;
v = 0.2193820409510504e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3351786584663333;
b = 0.1844801892177727;
v = 0.2278870827661928e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3713505522209120;
b = 0.2184145236087598;
v = 0.2348283192282090e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4067981098954663;
b = 0.2523590641486229;
v = 0.2404139755581477e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4413769993687534;
b = 0.2860812976901373;
v = 0.2448227407760734e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4749487182516394;
b = 0.3193686757808996;
v = 0.2482110455592573e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5073798105075426;
b = 0.3520226949547602;
v = 0.2507192397774103e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5385410448878654;
b = 0.3838544395667890;
v = 0.2524765968534880e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5683065353670530;
b = 0.4146810037640963;
v = 0.2536052388539425e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5965527620663510;
b = 0.4443224094681121;
v = 0.2542230588033068e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2299227700856157;
b = 0.2865757664057584e-1;
v = 0.1944817013047896e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2695752998553267;
b = 0.5923421684485993e-1;
v = 0.2067862362746635e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3086178716611389;
b = 0.9117817776057715e-1;
v = 0.2172440734649114e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3469649871659077;
b = 0.1240593814082605;
v = 0.2260125991723423e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3845153566319655;
b = 0.1575272058259175;
v = 0.2332655008689523e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4211600033403215;
b = 0.1912845163525413;
v = 0.2391699681532458e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4567867834329882;
b = 0.2250710177858171;
v = 0.2438801528273928e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4912829319232061;
b = 0.2586521303440910;
v = 0.2475370504260665e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5245364793303812;
b = 0.2918112242865407;
v = 0.2502707235640574e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5564369788915756;
b = 0.3243439239067890;
v = 0.2522031701054241e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5868757697775287;
b = 0.3560536787835351;
v = 0.2534511269978784e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6157458853519617;
b = 0.3867480821242581;
v = 0.2541284914955151e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3138461110672113;
b = 0.3051374637507278e-1;
v = 0.2161509250688394e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3542495872050569;
b = 0.6237111233730755e-1;
v = 0.2248778513437852e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3935751553120181;
b = 0.9516223952401907e-1;
v = 0.2322388803404617e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4317634668111147;
b = 0.1285467341508517;
v = 0.2383265471001355e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4687413842250821;
b = 0.1622318931656033;
v = 0.2432476675019525e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5044274237060283;
b = 0.1959581153836453;
v = 0.2471122223750674e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5387354077925727;
b = 0.2294888081183837;
v = 0.2500291752486870e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5715768898356105;
b = 0.2626031152713945;
v = 0.2521055942764682e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6028627200136111;
b = 0.2950904075286713;
v = 0.2534472785575503e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6325039812653463;
b = 0.3267458451113286;
v = 0.2541599713080121e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3981986708423407;
b = 0.3183291458749821e-1;
v = 0.2317380975862936e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4382791182133300;
b = 0.6459548193880908e-1;
v = 0.2378550733719775e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4769233057218166;
b = 0.9795757037087952e-1;
v = 0.2428884456739118e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5140823911194238;
b = 0.1316307235126655;
v = 0.2469002655757292e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5496977833862983;
b = 0.1653556486358704;
v = 0.2499657574265851e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5837047306512727;
b = 0.1988931724126510;
v = 0.2521676168486082e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6160349566926879;
b = 0.2320174581438950;
v = 0.2535935662645334e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6466185353209440;
b = 0.2645106562168662;
v = 0.2543356743363214e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4810835158795404;
b = 0.3275917807743992e-1;
v = 0.2427353285201535e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5199925041324341;
b = 0.6612546183967181e-1;
v = 0.2468258039744386e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5571717692207494;
b = 0.9981498331474143e-1;
v = 0.2500060956440310e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5925789250836378;
b = 0.1335687001410374;
v = 0.2523238365420979e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6261658523859670;
b = 0.1671444402896463;
v = 0.2538399260252846e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6578811126669331;
b = 0.2003106382156076;
v = 0.2546255927268069e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5609624612998100;
b = 0.3337500940231335e-1;
v = 0.2500583360048449e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5979959659984670;
b = 0.6708750335901803e-1;
v = 0.2524777638260203e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6330523711054002;
b = 0.1008792126424850;
v = 0.2540951193860656e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6660960998103972;
b = 0.1345050343171794;
v = 0.2549524085027472e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6365384364585819;
b = 0.3372799460737052e-1;
v = 0.2542569507009158e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6710994302899275;
b = 0.6755249309678028e-1;
v = 0.2552114127580376e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
n = n - 1;
return;
}
//****************************************************************************80
void ld4802 ( double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD4802 computes the 4802 point Lebedev angular grid.
//
// Modified:
//
// 12 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Output, double X[N], Y[N], Z[N], W[N], the coordinates
// and weights of the points.
//
{
double a = 0.0;
double b = 0.0;
int n;
double v;
n = 0;
v = 0.9687521879420705e-4;
n = n + gen_oh ( 1, a, b, v, x + n, y + n, z + n, w + n );
v = 0.2307897895367918e-3;
n = n + gen_oh ( 2, a, b, v, x + n, y + n, z + n, w + n );
v = 0.2297310852498558e-3;
n = n + gen_oh ( 3, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2335728608887064e-1;
v = 0.7386265944001919e-4;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4352987836550653e-1;
v = 0.8257977698542210e-4;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6439200521088801e-1;
v = 0.9706044762057630e-4;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.9003943631993181e-1;
v = 0.1302393847117003e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1196706615548473;
v = 0.1541957004600968e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1511715412838134;
v = 0.1704459770092199e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1835982828503801;
v = 0.1827374890942906e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2165081259155405;
v = 0.1926360817436107e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2496208720417563;
v = 0.2008010239494833e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2827200673567900;
v = 0.2075635983209175e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3156190823994346;
v = 0.2131306638690909e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3481476793749115;
v = 0.2176562329937335e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3801466086947226;
v = 0.2212682262991018e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4114652119634011;
v = 0.2240799515668565e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4419598786519751;
v = 0.2261959816187525e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4714925949329543;
v = 0.2277156368808855e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4999293972879466;
v = 0.2287351772128336e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5271387221431248;
v = 0.2293490814084085e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5529896780837761;
v = 0.2296505312376273e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6000856099481712;
v = 0.2296793832318756e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6210562192785175;
v = 0.2295785443842974e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6401165879934240;
v = 0.2295017931529102e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6571144029244334;
v = 0.2295059638184868e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6718910821718863;
v = 0.2296232343237362e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6842845591099010;
v = 0.2298530178740771e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6941353476269816;
v = 0.2301579790280501e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7012965242212991;
v = 0.2304690404996513e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7056471428242644;
v = 0.2307027995907102e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4595557643585895e-1;
v = 0.9312274696671092e-4;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1049316742435023;
v = 0.1199919385876926e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1773548879549274;
v = 0.1598039138877690e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2559071411236127;
v = 0.1822253763574900e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3358156837985898;
v = 0.1988579593655040e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4155835743763893;
v = 0.2112620102533307e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4937894296167472;
v = 0.2201594887699007e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5691569694793316;
v = 0.2261622590895036e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6405840854894251;
v = 0.2296458453435705e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7345133894143348e-1;
b = 0.2177844081486067e-1;
v = 0.1006006990267000e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1009859834044931;
b = 0.4590362185775188e-1;
v = 0.1227676689635876e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1324289619748758;
b = 0.7255063095690877e-1;
v = 0.1467864280270117e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1654272109607127;
b = 0.1017825451960684;
v = 0.1644178912101232e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1990767186776461;
b = 0.1325652320980364;
v = 0.1777664890718961e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2330125945523278;
b = 0.1642765374496765;
v = 0.1884825664516690e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2670080611108287;
b = 0.1965360374337889;
v = 0.1973269246453848e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3008753376294316;
b = 0.2290726770542238;
v = 0.2046767775855328e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3344475596167860;
b = 0.2616645495370823;
v = 0.2107600125918040e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3675709724070786;
b = 0.2941150728843141;
v = 0.2157416362266829e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4001000887587812;
b = 0.3262440400919066;
v = 0.2197557816920721e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4318956350436028;
b = 0.3578835350611916;
v = 0.2229192611835437e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4628239056795531;
b = 0.3888751854043678;
v = 0.2253385110212775e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4927563229773636;
b = 0.4190678003222840;
v = 0.2271137107548774e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5215687136707969;
b = 0.4483151836883852;
v = 0.2283414092917525e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5491402346984905;
b = 0.4764740676087880;
v = 0.2291161673130077e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5753520160126075;
b = 0.5034021310998277;
v = 0.2295313908576598e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1388326356417754;
b = 0.2435436510372806e-1;
v = 0.1438204721359031e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1743686900537244;
b = 0.5118897057342652e-1;
v = 0.1607738025495257e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2099737037950268;
b = 0.8014695048539634e-1;
v = 0.1741483853528379e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2454492590908548;
b = 0.1105117874155699;
v = 0.1851918467519151e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2807219257864278;
b = 0.1417950531570966;
v = 0.1944628638070613e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3156842271975842;
b = 0.1736604945719597;
v = 0.2022495446275152e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3502090945177752;
b = 0.2058466324693981;
v = 0.2087462382438514e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3841684849519686;
b = 0.2381284261195919;
v = 0.2141074754818308e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4174372367906016;
b = 0.2703031270422569;
v = 0.2184640913748162e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4498926465011892;
b = 0.3021845683091309;
v = 0.2219309165220329e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4814146229807701;
b = 0.3335993355165720;
v = 0.2246123118340624e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5118863625734701;
b = 0.3643833735518232;
v = 0.2266062766915125e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5411947455119144;
b = 0.3943789541958179;
v = 0.2280072952230796e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5692301500357246;
b = 0.4234320144403542;
v = 0.2289082025202583e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5958857204139576;
b = 0.4513897947419260;
v = 0.2294012695120025e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2156270284785766;
b = 0.2681225755444491e-1;
v = 0.1722434488736947e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2532385054909710;
b = 0.5557495747805614e-1;
v = 0.1830237421455091e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2902564617771537;
b = 0.8569368062950249e-1;
v = 0.1923855349997633e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3266979823143256;
b = 0.1167367450324135;
v = 0.2004067861936271e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3625039627493614;
b = 0.1483861994003304;
v = 0.2071817297354263e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3975838937548699;
b = 0.1803821503011405;
v = 0.2128250834102103e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4318396099009774;
b = 0.2124962965666424;
v = 0.2174513719440102e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4651706555732742;
b = 0.2445221837805913;
v = 0.2211661839150214e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4974752649620969;
b = 0.2762701224322987;
v = 0.2240665257813102e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5286517579627517;
b = 0.3075627775211328;
v = 0.2262439516632620e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5586001195731895;
b = 0.3382311089826877;
v = 0.2277874557231869e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5872229902021319;
b = 0.3681108834741399;
v = 0.2287854314454994e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6144258616235123;
b = 0.3970397446872839;
v = 0.2293268499615575e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2951676508064861;
b = 0.2867499538750441e-1;
v = 0.1912628201529828e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3335085485472725;
b = 0.5867879341903510e-1;
v = 0.1992499672238701e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3709561760636381;
b = 0.8961099205022284e-1;
v = 0.2061275533454027e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4074722861667498;
b = 0.1211627927626297;
v = 0.2119318215968572e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4429923648839117;
b = 0.1530748903554898;
v = 0.2167416581882652e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4774428052721736;
b = 0.1851176436721877;
v = 0.2206430730516600e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5107446539535904;
b = 0.2170829107658179;
v = 0.2237186938699523e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5428151370542935;
b = 0.2487786689026271;
v = 0.2260480075032884e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5735699292556964;
b = 0.2800239952795016;
v = 0.2277098884558542e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6029253794562866;
b = 0.3106445702878119;
v = 0.2287845715109671e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6307998987073145;
b = 0.3404689500841194;
v = 0.2293547268236294e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3752652273692719;
b = 0.2997145098184479e-1;
v = 0.2056073839852528e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4135383879344028;
b = 0.6086725898678011e-1;
v = 0.2114235865831876e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4506113885153907;
b = 0.9238849548435643e-1;
v = 0.2163175629770551e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4864401554606072;
b = 0.1242786603851851;
v = 0.2203392158111650e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5209708076611709;
b = 0.1563086731483386;
v = 0.2235473176847839e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5541422135830122;
b = 0.1882696509388506;
v = 0.2260024141501235e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5858880915113817;
b = 0.2199672979126059;
v = 0.2277675929329182e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6161399390603444;
b = 0.2512165482924867;
v = 0.2289102112284834e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6448296482255090;
b = 0.2818368701871888;
v = 0.2295027954625118e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4544796274917948;
b = 0.3088970405060312e-1;
v = 0.2161281589879992e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4919389072146628;
b = 0.6240947677636835e-1;
v = 0.2201980477395102e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5279313026985183;
b = 0.9430706144280313e-1;
v = 0.2234952066593166e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5624169925571135;
b = 0.1263547818770374;
v = 0.2260540098520838e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5953484627093287;
b = 0.1583430788822594;
v = 0.2279157981899988e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6266730715339185;
b = 0.1900748462555988;
v = 0.2291296918565571e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6563363204278871;
b = 0.2213599519592567;
v = 0.2297533752536649e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5314574716585696;
b = 0.3152508811515374e-1;
v = 0.2234927356465995e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5674614932298185;
b = 0.6343865291465561e-1;
v = 0.2261288012985219e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6017706004970264;
b = 0.9551503504223951e-1;
v = 0.2280818160923688e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6343471270264178;
b = 0.1275440099801196;
v = 0.2293773295180159e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6651494599127802;
b = 0.1593252037671960;
v = 0.2300528767338634e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6050184986005704;
b = 0.3192538338496105e-1;
v = 0.2281893855065666e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6390163550880400;
b = 0.6402824353962306e-1;
v = 0.2295720444840727e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6711199107088448;
b = 0.9609805077002909e-1;
v = 0.2303227649026753e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6741354429572275;
b = 0.3211853196273233e-1;
v = 0.2304831913227114e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
n = n - 1;
return;
}
//****************************************************************************80
void ld5294 ( double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD5294 computes the 5294 point Lebedev angular grid.
//
// Modified:
//
// 12 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Output, double X[N], Y[N], Z[N], W[N], the coordinates
// and weights of the points.
//
{
double a = 0.0;
double b = 0.0;
int n;
double v;
n = 0;
v = 0.9080510764308163e-4;
n = n + gen_oh ( 1, a, b, v, x + n, y + n, z + n, w + n );
v = 0.2084824361987793e-3;
n = n + gen_oh ( 3, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2303261686261450e-1;
v = 0.5011105657239616e-4;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3757208620162394e-1;
v = 0.5942520409683854e-4;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5821912033821852e-1;
v = 0.9564394826109721e-4;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.8403127529194872e-1;
v = 0.1185530657126338e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1122927798060578;
v = 0.1364510114230331e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1420125319192987;
v = 0.1505828825605415e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1726396437341978;
v = 0.1619298749867023e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2038170058115696;
v = 0.1712450504267789e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2352849892876508;
v = 0.1789891098164999e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2668363354312461;
v = 0.1854474955629795e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2982941279900452;
v = 0.1908148636673661e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3295002922087076;
v = 0.1952377405281833e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3603094918363593;
v = 0.1988349254282232e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3905857895173920;
v = 0.2017079807160050e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4202005758160837;
v = 0.2039473082709094e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4490310061597227;
v = 0.2056360279288953e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4769586160311491;
v = 0.2068525823066865e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5038679887049750;
v = 0.2076724877534488e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5296454286519961;
v = 0.2081694278237885e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5541776207164850;
v = 0.2084157631219326e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5990467321921213;
v = 0.2084381531128593e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6191467096294587;
v = 0.2083476277129307e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6375251212901849;
v = 0.2082686194459732e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6540514381131168;
v = 0.2082475686112415e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6685899064391510;
v = 0.2083139860289915e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6810013009681648;
v = 0.2084745561831237e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6911469578730340;
v = 0.2087091313375890e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6988956915141736;
v = 0.2089718413297697e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7041335794868720;
v = 0.2092003303479793e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7067754398018567;
v = 0.2093336148263241e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3840368707853623e-1;
v = 0.7591708117365267e-4;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.9835485954117399e-1;
v = 0.1083383968169186e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1665774947612998;
v = 0.1403019395292510e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2405702335362910;
v = 0.1615970179286436e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3165270770189046;
v = 0.1771144187504911e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3927386145645443;
v = 0.1887760022988168e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4678825918374656;
v = 0.1973474670768214e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5408022024266935;
v = 0.2033787661234659e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6104967445752438;
v = 0.2072343626517331e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6760910702685738;
v = 0.2091177834226918e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6655644120217392e-1;
b = 0.1936508874588424e-1;
v = 0.9316684484675566e-4;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.9446246161270182e-1;
b = 0.4252442002115869e-1;
v = 0.1116193688682976e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1242651925452509;
b = 0.6806529315354374e-1;
v = 0.1298623551559414e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1553438064846751;
b = 0.9560957491205369e-1;
v = 0.1450236832456426e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1871137110542670;
b = 0.1245931657452888;
v = 0.1572719958149914e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2192612628836257;
b = 0.1545385828778978;
v = 0.1673234785867195e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2515682807206955;
b = 0.1851004249723368;
v = 0.1756860118725188e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2838535866287290;
b = 0.2160182608272384;
v = 0.1826776290439367e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3159578817528521;
b = 0.2470799012277111;
v = 0.1885116347992865e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3477370882791392;
b = 0.2781014208986402;
v = 0.1933457860170574e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3790576960890540;
b = 0.3089172523515731;
v = 0.1973060671902064e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4097938317810200;
b = 0.3393750055472244;
v = 0.2004987099616311e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4398256572859637;
b = 0.3693322470987730;
v = 0.2030170909281499e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4690384114718480;
b = 0.3986541005609877;
v = 0.2049461460119080e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4973216048301053;
b = 0.4272112491408562;
v = 0.2063653565200186e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5245681526132446;
b = 0.4548781735309936;
v = 0.2073507927381027e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5506733911803888;
b = 0.4815315355023251;
v = 0.2079764593256122e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5755339829522475;
b = 0.5070486445801855;
v = 0.2083150534968778e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1305472386056362;
b = 0.2284970375722366e-1;
v = 0.1262715121590664e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1637327908216477;
b = 0.4812254338288384e-1;
v = 0.1414386128545972e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1972734634149637;
b = 0.7531734457511935e-1;
v = 0.1538740401313898e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2308694653110130;
b = 0.1039043639882017;
v = 0.1642434942331432e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2643899218338160;
b = 0.1334526587117626;
v = 0.1729790609237496e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2977171599622171;
b = 0.1636414868936382;
v = 0.1803505190260828e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3307293903032310;
b = 0.1942195406166568;
v = 0.1865475350079657e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3633069198219073;
b = 0.2249752879943753;
v = 0.1917182669679069e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3953346955922727;
b = 0.2557218821820032;
v = 0.1959851709034382e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4267018394184914;
b = 0.2862897925213193;
v = 0.1994529548117882e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4573009622571704;
b = 0.3165224536636518;
v = 0.2022138911146548e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4870279559856109;
b = 0.3462730221636496;
v = 0.2043518024208592e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5157819581450322;
b = 0.3754016870282835;
v = 0.2059450313018110e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5434651666465393;
b = 0.4037733784993613;
v = 0.2070685715318472e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5699823887764627;
b = 0.4312557784139123;
v = 0.2077955310694373e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5952403350947741;
b = 0.4577175367122110;
v = 0.2081980387824712e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2025152599210369;
b = 0.2520253617719557e-1;
v = 0.1521318610377956e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2381066653274425;
b = 0.5223254506119000e-1;
v = 0.1622772720185755e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2732823383651612;
b = 0.8060669688588620e-1;
v = 0.1710498139420709e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3080137692611118;
b = 0.1099335754081255;
v = 0.1785911149448736e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3422405614587601;
b = 0.1399120955959857;
v = 0.1850125313687736e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3758808773890420;
b = 0.1702977801651705;
v = 0.1904229703933298e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4088458383438932;
b = 0.2008799256601680;
v = 0.1949259956121987e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4410450550841152;
b = 0.2314703052180836;
v = 0.1986161545363960e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4723879420561312;
b = 0.2618972111375892;
v = 0.2015790585641370e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5027843561874343;
b = 0.2920013195600270;
v = 0.2038934198707418e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5321453674452458;
b = 0.3216322555190551;
v = 0.2056334060538251e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5603839113834030;
b = 0.3506456615934198;
v = 0.2068705959462289e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5874150706875146;
b = 0.3789007181306267;
v = 0.2076753906106002e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6131559381660038;
b = 0.4062580170572782;
v = 0.2081179391734803e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2778497016394506;
b = 0.2696271276876226e-1;
v = 0.1700345216228943e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3143733562261912;
b = 0.5523469316960465e-1;
v = 0.1774906779990410e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3501485810261827;
b = 0.8445193201626464e-1;
v = 0.1839659377002642e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3851430322303653;
b = 0.1143263119336083;
v = 0.1894987462975169e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4193013979470415;
b = 0.1446177898344475;
v = 0.1941548809452595e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4525585960458567;
b = 0.1751165438438091;
v = 0.1980078427252384e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4848447779622947;
b = 0.2056338306745660;
v = 0.2011296284744488e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5160871208276894;
b = 0.2359965487229226;
v = 0.2035888456966776e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5462112185696926;
b = 0.2660430223139146;
v = 0.2054516325352142e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5751425068101757;
b = 0.2956193664498032;
v = 0.2067831033092635e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6028073872853596;
b = 0.3245763905312779;
v = 0.2076485320284876e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6291338275278409;
b = 0.3527670026206972;
v = 0.2081141439525255e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3541797528439391;
b = 0.2823853479435550e-1;
v = 0.1834383015469222e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3908234972074657;
b = 0.5741296374713106e-1;
v = 0.1889540591777677e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4264408450107590;
b = 0.8724646633650199e-1;
v = 0.1936677023597375e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4609949666553286;
b = 0.1175034422915616;
v = 0.1976176495066504e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4944389496536006;
b = 0.1479755652628428;
v = 0.2008536004560983e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5267194884346086;
b = 0.1784740659484352;
v = 0.2034280351712291e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5577787810220990;
b = 0.2088245700431244;
v = 0.2053944466027758e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5875563763536670;
b = 0.2388628136570763;
v = 0.2068077642882360e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6159910016391269;
b = 0.2684308928769185;
v = 0.2077250949661599e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6430219602956268;
b = 0.2973740761960252;
v = 0.2082062440705320e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4300647036213646;
b = 0.2916399920493977e-1;
v = 0.1934374486546626e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4661486308935531;
b = 0.5898803024755659e-1;
v = 0.1974107010484300e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5009658555287261;
b = 0.8924162698525409e-1;
v = 0.2007129290388658e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5344824270447704;
b = 0.1197185199637321;
v = 0.2033736947471293e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5666575997416371;
b = 0.1502300756161382;
v = 0.2054287125902493e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5974457471404752;
b = 0.1806004191913564;
v = 0.2069184936818894e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6267984444116886;
b = 0.2106621764786252;
v = 0.2078883689808782e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6546664713575417;
b = 0.2402526932671914;
v = 0.2083886366116359e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5042711004437253;
b = 0.2982529203607657e-1;
v = 0.2006593275470817e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5392127456774380;
b = 0.6008728062339922e-1;
v = 0.2033728426135397e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5726819437668618;
b = 0.9058227674571398e-1;
v = 0.2055008781377608e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6046469254207278;
b = 0.1211219235803400;
v = 0.2070651783518502e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6350716157434952;
b = 0.1515286404791580;
v = 0.2080953335094320e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6639177679185454;
b = 0.1816314681255552;
v = 0.2086284998988521e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5757276040972253;
b = 0.3026991752575440e-1;
v = 0.2055549387644668e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6090265823139755;
b = 0.6078402297870770e-1;
v = 0.2071871850267654e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6406735344387661;
b = 0.9135459984176636e-1;
v = 0.2082856600431965e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6706397927793709;
b = 0.1218024155966590;
v = 0.2088705858819358e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6435019674426665;
b = 0.3052608357660639e-1;
v = 0.2083995867536322e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6747218676375681;
b = 0.6112185773983089e-1;
v = 0.2090509712889637e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
n = n - 1;
return;
}
//****************************************************************************80
void ld5810 ( double *x, double *y, double *z, double *w )
//****************************************************************************80
//
// Purpose:
//
// LD5810 computes the 5810 point Lebedev angular grid.
//
// Modified:
//
// 12 September 2010
//
// Author:
//
// Dmitri Laikov
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Output, double X[N], Y[N], Z[N], W[N], the coordinates
// and weights of the points.
//
{
double a = 0.0;
double b = 0.0;
int n;
double v;
n = 0;
v = 0.9735347946175486e-5;
n = n + gen_oh ( 1, a, b, v, x + n, y + n, z + n, w + n );
v = 0.1907581241803167e-3;
n = n + gen_oh ( 2, a, b, v, x + n, y + n, z + n, w + n );
v = 0.1901059546737578e-3;
n = n + gen_oh ( 3, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1182361662400277e-1;
v = 0.3926424538919212e-4;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3062145009138958e-1;
v = 0.6667905467294382e-4;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5329794036834243e-1;
v = 0.8868891315019135e-4;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7848165532862220e-1;
v = 0.1066306000958872e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1054038157636201;
v = 0.1214506743336128e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1335577797766211;
v = 0.1338054681640871e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1625769955502252;
v = 0.1441677023628504e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1921787193412792;
v = 0.1528880200826557e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2221340534690548;
v = 0.1602330623773609e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2522504912791132;
v = 0.1664102653445244e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2823610860679697;
v = 0.1715845854011323e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3123173966267560;
v = 0.1758901000133069e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3419847036953789;
v = 0.1794382485256736e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3712386456999758;
v = 0.1823238106757407e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3999627649876828;
v = 0.1846293252959976e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4280466458648093;
v = 0.1864284079323098e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4553844360185711;
v = 0.1877882694626914e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4818736094437834;
v = 0.1887716321852025e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5074138709260629;
v = 0.1894381638175673e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5319061304570707;
v = 0.1898454899533629e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5552514978677286;
v = 0.1900497929577815e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5981009025246183;
v = 0.1900671501924092e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6173990192228116;
v = 0.1899837555533510e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6351365239411131;
v = 0.1899014113156229e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6512010228227200;
v = 0.1898581257705106e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6654758363948120;
v = 0.1898804756095753e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6778410414853370;
v = 0.1899793610426402e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6881760887484110;
v = 0.1901464554844117e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6963645267094598;
v = 0.1903533246259542e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7023010617153579;
v = 0.1905556158463228e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.7059004636628753;
v = 0.1907037155663528e-3;
n = n + gen_oh ( 4, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3552470312472575e-1;
v = 0.5992997844249967e-4;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.9151176620841283e-1;
v = 0.9749059382456978e-4;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1566197930068980;
v = 0.1241680804599158e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2265467599271907;
v = 0.1437626154299360e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2988242318581361;
v = 0.1584200054793902e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3717482419703886;
v = 0.1694436550982744e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4440094491758889;
v = 0.1776617014018108e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5145337096756642;
v = 0.1836132434440077e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5824053672860230;
v = 0.1876494727075983e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6468283961043370;
v = 0.1899906535336482e-3;
n = n + gen_oh ( 5, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6095964259104373e-1;
b = 0.1787828275342931e-1;
v = 0.8143252820767350e-4;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.8811962270959388e-1;
b = 0.3953888740792096e-1;
v = 0.9998859890887728e-4;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1165936722428831;
b = 0.6378121797722990e-1;
v = 0.1156199403068359e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1460232857031785;
b = 0.8985890813745037e-1;
v = 0.1287632092635513e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1761197110181755;
b = 0.1172606510576162;
v = 0.1398378643365139e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2066471190463718;
b = 0.1456102876970995;
v = 0.1491876468417391e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2374076026328152;
b = 0.1746153823011775;
v = 0.1570855679175456e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2682305474337051;
b = 0.2040383070295584;
v = 0.1637483948103775e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2989653312142369;
b = 0.2336788634003698;
v = 0.1693500566632843e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3294762752772209;
b = 0.2633632752654219;
v = 0.1740322769393633e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3596390887276086;
b = 0.2929369098051601;
v = 0.1779126637278296e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3893383046398812;
b = 0.3222592785275512;
v = 0.1810908108835412e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4184653789358347;
b = 0.3512004791195743;
v = 0.1836529132600190e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4469172319076166;
b = 0.3796385677684537;
v = 0.1856752841777379e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4745950813276976;
b = 0.4074575378263879;
v = 0.1872270566606832e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5014034601410262;
b = 0.4345456906027828;
v = 0.1883722645591307e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5272493404551239;
b = 0.4607942515205134;
v = 0.1891714324525297e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5520413051846366;
b = 0.4860961284181720;
v = 0.1896827480450146e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5756887237503077;
b = 0.5103447395342790;
v = 0.1899628417059528e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1225039430588352;
b = 0.2136455922655793e-1;
v = 0.1123301829001669e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1539113217321372;
b = 0.4520926166137188e-1;
v = 0.1253698826711277e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1856213098637712;
b = 0.7086468177864818e-1;
v = 0.1366266117678531e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2174998728035131;
b = 0.9785239488772918e-1;
v = 0.1462736856106918e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2494128336938330;
b = 0.1258106396267210;
v = 0.1545076466685412e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2812321562143480;
b = 0.1544529125047001;
v = 0.1615096280814007e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3128372276456111;
b = 0.1835433512202753;
v = 0.1674366639741759e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3441145160177973;
b = 0.2128813258619585;
v = 0.1724225002437900e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3749567714853510;
b = 0.2422913734880829;
v = 0.1765810822987288e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4052621732015610;
b = 0.2716163748391453;
v = 0.1800104126010751e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4349335453522385;
b = 0.3007127671240280;
v = 0.1827960437331284e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4638776641524965;
b = 0.3294470677216479;
v = 0.1850140300716308e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4920046410462687;
b = 0.3576932543699155;
v = 0.1867333507394938e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5192273554861704;
b = 0.3853307059757764;
v = 0.1880178688638289e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5454609081136522;
b = 0.4122425044452694;
v = 0.1889278925654758e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5706220661424140;
b = 0.4383139587781027;
v = 0.1895213832507346e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5946286755181518;
b = 0.4634312536300553;
v = 0.1898548277397420e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.1905370790924295;
b = 0.2371311537781979e-1;
v = 0.1349105935937341e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2242518717748009;
b = 0.4917878059254806e-1;
v = 0.1444060068369326e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2577190808025936;
b = 0.7595498960495142e-1;
v = 0.1526797390930008e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2908724534927187;
b = 0.1036991083191100;
v = 0.1598208771406474e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3236354020056219;
b = 0.1321348584450234;
v = 0.1659354368615331e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3559267359304543;
b = 0.1610316571314789;
v = 0.1711279910946440e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3876637123676956;
b = 0.1901912080395707;
v = 0.1754952725601440e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4187636705218842;
b = 0.2194384950137950;
v = 0.1791247850802529e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4491449019883107;
b = 0.2486155334763858;
v = 0.1820954300877716e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4787270932425445;
b = 0.2775768931812335;
v = 0.1844788524548449e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5074315153055574;
b = 0.3061863786591120;
v = 0.1863409481706220e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5351810507738336;
b = 0.3343144718152556;
v = 0.1877433008795068e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5619001025975381;
b = 0.3618362729028427;
v = 0.1887444543705232e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5875144035268046;
b = 0.3886297583620408;
v = 0.1894009829375006e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6119507308734495;
b = 0.4145742277792031;
v = 0.1897683345035198e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2619733870119463;
b = 0.2540047186389353e-1;
v = 0.1517327037467653e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.2968149743237949;
b = 0.5208107018543989e-1;
v = 0.1587740557483543e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3310451504860488;
b = 0.7971828470885599e-1;
v = 0.1649093382274097e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3646215567376676;
b = 0.1080465999177927;
v = 0.1701915216193265e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3974916785279360;
b = 0.1368413849366629;
v = 0.1746847753144065e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4295967403772029;
b = 0.1659073184763559;
v = 0.1784555512007570e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4608742854473447;
b = 0.1950703730454614;
v = 0.1815687562112174e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4912598858949903;
b = 0.2241721144376724;
v = 0.1840864370663302e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5206882758945558;
b = 0.2530655255406489;
v = 0.1860676785390006e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5490940914019819;
b = 0.2816118409731066;
v = 0.1875690583743703e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5764123302025542;
b = 0.3096780504593238;
v = 0.1886453236347225e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6025786004213506;
b = 0.3371348366394987;
v = 0.1893501123329645e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6275291964794956;
b = 0.3638547827694396;
v = 0.1897366184519868e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3348189479861771;
b = 0.2664841935537443e-1;
v = 0.1643908815152736e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.3699515545855295;
b = 0.5424000066843495e-1;
v = 0.1696300350907768e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4042003071474669;
b = 0.8251992715430854e-1;
v = 0.1741553103844483e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4375320100182624;
b = 0.1112695182483710;
v = 0.1780015282386092e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4699054490335947;
b = 0.1402964116467816;
v = 0.1812116787077125e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5012739879431952;
b = 0.1694275117584291;
v = 0.1838323158085421e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5315874883754966;
b = 0.1985038235312689;
v = 0.1859113119837737e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5607937109622117;
b = 0.2273765660020893;
v = 0.1874969220221698e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5888393223495521;
b = 0.2559041492849764;
v = 0.1886375612681076e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6156705979160163;
b = 0.2839497251976899;
v = 0.1893819575809276e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6412338809078123;
b = 0.3113791060500690;
v = 0.1897794748256767e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4076051259257167;
b = 0.2757792290858463e-1;
v = 0.1738963926584846e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4423788125791520;
b = 0.5584136834984293e-1;
v = 0.1777442359873466e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4760480917328258;
b = 0.8457772087727143e-1;
v = 0.1810010815068719e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5085838725946297;
b = 0.1135975846359248;
v = 0.1836920318248129e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5399513637391218;
b = 0.1427286904765053;
v = 0.1858489473214328e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5701118433636380;
b = 0.1718112740057635;
v = 0.1875079342496592e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5990240530606021;
b = 0.2006944855985351;
v = 0.1887080239102310e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6266452685139695;
b = 0.2292335090598907;
v = 0.1894905752176822e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6529320971415942;
b = 0.2572871512353714;
v = 0.1898991061200695e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.4791583834610126;
b = 0.2826094197735932e-1;
v = 0.1809065016458791e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5130373952796940;
b = 0.5699871359683649e-1;
v = 0.1836297121596799e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5456252429628476;
b = 0.8602712528554394e-1;
v = 0.1858426916241869e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5768956329682385;
b = 0.1151748137221281;
v = 0.1875654101134641e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6068186944699046;
b = 0.1442811654136362;
v = 0.1888240751833503e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6353622248024907;
b = 0.1731930321657680;
v = 0.1896497383866979e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6624927035731797;
b = 0.2017619958756061;
v = 0.1900775530219121e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5484933508028488;
b = 0.2874219755907391e-1;
v = 0.1858525041478814e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.5810207682142106;
b = 0.5778312123713695e-1;
v = 0.1876248690077947e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6120955197181352;
b = 0.8695262371439526e-1;
v = 0.1889404439064607e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6416944284294319;
b = 0.1160893767057166;
v = 0.1898168539265290e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6697926391731260;
b = 0.1450378826743251;
v = 0.1902779940661772e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6147594390585488;
b = 0.2904957622341456e-1;
v = 0.1890125641731815e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6455390026356783;
b = 0.5823809152617197e-1;
v = 0.1899434637795751e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6747258588365477;
b = 0.8740384899884715e-1;
v = 0.1904520856831751e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
a = 0.6772135750395347;
b = 0.2919946135808105e-1;
v = 0.1905534498734563e-3;
n = n + gen_oh ( 6, a, b, v, x + n, y + n, z + n, w + n );
n = n - 1;
return;
}
//****************************************************************************80
int order_table ( int rule )
//****************************************************************************80
//
// Purpose:
//
// ORDER_TABLE returns the order of a Lebedev rule.
//
// Modified:
//
// 11 September 2010
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Input, int RULE, the index of the rule, between 1 and 65.
//
// Output, int ORDER_TABLE, the order of the rule.
//
{
int rule_max = 65;
int table[65]= {
6, 14, 26, 38, 50, 74, 86, 110, 146, 170,
194, 230, 266, 302, 350, 386, 434, 482, 530, 590,
650, 698, 770, 830, 890, 974, 1046, 1118, 1202, 1274,
1358, 1454, 1538, 1622, 1730, 1814, 1910, 2030, 2126, 2222,
2354, 2450, 2558, 2702, 2810, 2930, 3074, 3182, 3314, 3470,
3590, 3722, 3890, 4010, 4154, 4334, 4466, 4610, 4802, 4934,
5090, 5294, 5438, 5606, 5810 };
int value;
if ( rule < 1 )
{
cerr << "\n";
cerr << "ORDER_TABLE - Fatal error!\n";
cerr << " RULE < 1.\n";
exit ( 1 );
}
else if ( rule_max < rule )
{
cerr << "\n";
cerr << "ORDER_TABLE - Fatal error!\n";
cerr << " RULE_MAX < RULE.\n";
exit ( 1 );
}
value = table[rule-1];
return value;
}
//****************************************************************************80
int precision_table ( int rule )
//****************************************************************************80
//
// Purpose:
//
// PRECISION_TABLE returns the precision of a Lebedev rule.
//
// Modified:
//
// 11 September 2010
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Vyacheslav Lebedev, Dmitri Laikov,
// A quadrature formula for the sphere of the 131st
// algebraic order of accuracy,
// Russian Academy of Sciences Doklady Mathematics,
// Volume 59, Number 3, 1999, pages 477-481.
//
// Parameters:
//
// Input, int RULE, the index of the rule, between 1 and 65.
//
// Output, int PRECISION_TABLE, the precision of the rule.
//
{
int rule_max = 65;
int table[65]= {
3, 5, 7, 9, 11, 13, 15, 17, 19, 21,
23, 25, 27, 29, 31, 33, 35, 37, 39, 41,
43, 45, 47, 49, 51, 53, 55, 57, 59, 61,
63, 65, 67, 69, 71, 73, 75, 77, 79, 81,
83, 85, 87, 89, 91, 93, 95, 97, 99, 101,
103, 105, 107, 109, 111, 113, 115, 117, 119, 121,
123, 125, 127, 129, 131 };
int value;
if ( rule < 1 )
{
cerr << "\n";
cerr << "PRECISION_TABLE - Fatal error!\n";
cerr << " RULE < 1.\n";
exit ( 1 );
}
else if ( rule_max < rule )
{
cerr << "\n";
cerr << "PRECISION_TABLE - Fatal error!\n";
cerr << " RULE_MAX < RULE.\n";
exit ( 1 );
}
value = table[rule-1];
return value;
}
//****************************************************************************80
void timestamp ( )
//****************************************************************************80
//
// Purpose:
//
// TIMESTAMP prints the current YMDHMS date as a time stamp.
//
// Example:
//
// 31 May 2001 09:45:54 AM
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 08 July 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// None
//
{
# define TIME_SIZE 40
static char time_buffer[TIME_SIZE];
const struct std::tm *tm_ptr;
std::time_t now;
now = std::time ( NULL );
tm_ptr = std::localtime ( &now );
std::strftime ( time_buffer, TIME_SIZE, "%d %B %Y %I:%M:%S %p", tm_ptr );
std::cout << time_buffer << "\n";
return;
# undef TIME_SIZE
}
//****************************************************************************80
void xyz_to_tp ( double x, double y, double z, double *t, double *p )
//****************************************************************************80
//
// Purpose:
//
// XYZ_TO_TP converts (X,Y,Z) to (Theta,Phi) coordinates on the unit sphere.
//
// Modified:
//
// 09 September 2010
//
// Author:
//
// Dmitri Laikin
//
// Parameters:
//
// Input, double X, Y, Z, the Cartesian coordinates of a point
// on the unit sphere.
//
// Output, double T, P, the Theta and Phi coordinates of
// the point.
//
{
double ang_x;
double fact;
double pi = 3.14159265358979323846;
*p = acos ( z );
fact = sqrt ( x * x + y * y );
if ( 0 < fact )
{
ang_x = acos ( x / fact );
}
else
{
ang_x = acos ( x );
}
if ( y < 0 )
{
ang_x = - ang_x;
}
*t = ang_x;
//
// Convert to degrees.
//
*t = *t * 180.0 / pi;
*p = *p * 180.0 / pi;
return;
}
|
/*
* Copyright (c) 2012 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2008 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabe Black
*/
#ifndef __DEV_X86_INTDEV_HH__
#define __DEV_X86_INTDEV_HH__
#include <cassert>
#include <list>
#include <string>
#include "arch/x86/intmessage.hh"
#include "arch/x86/x86_traits.hh"
#include "mem/tport.hh"
#include "sim/sim_object.hh"
namespace X86ISA
{
template <class Device>
class IntSlavePort : public SimpleTimingPort
{
Device * device;
public:
IntSlavePort(const std::string& _name, SimObject* _parent,
Device* dev) :
SimpleTimingPort(_name, _parent), device(dev)
{
}
AddrRangeList
getAddrRanges() const
{
return device->getIntAddrRange();
}
Tick
recvAtomic(PacketPtr pkt)
{
panic_if(pkt->cmd != MemCmd::MessageReq,
"%s received unexpected command %s from %s.\n",
name(), pkt->cmd.toString(), getPeer());
pkt->headerDelay = pkt->payloadDelay = 0;
return device->recvMessage(pkt);
}
};
typedef std::list<int> ApicList;
template <class Device>
class IntMasterPort : public QueuedMasterPort
{
ReqPacketQueue reqQueue;
SnoopRespPacketQueue snoopRespQueue;
Device* device;
Tick latency;
public:
IntMasterPort(const std::string& _name, SimObject* _parent,
Device* dev, Tick _latency) :
QueuedMasterPort(_name, _parent, reqQueue, snoopRespQueue),
reqQueue(*_parent, *this), snoopRespQueue(*_parent, *this),
device(dev), latency(_latency)
{
}
bool
recvTimingResp(PacketPtr pkt) override
{
return device->recvResponse(pkt);
}
// This is x86 focused, so if this class becomes generic, this would
// need to be moved into a subclass.
void
sendMessage(X86ISA::ApicList apics, TriggerIntMessage message, bool timing)
{
for (auto id: apics) {
PacketPtr pkt = buildIntRequest(id, message);
if (timing) {
schedTimingReq(pkt, curTick() + latency);
// The target handles cleaning up the packet in timing mode.
} else {
// ignore the latency involved in the atomic transaction
sendAtomic(pkt);
assert(pkt->isResponse());
// also ignore the latency in handling the response
device->recvResponse(pkt);
}
}
}
};
class IntDevice
{
protected:
IntMasterPort<IntDevice> intMasterPort;
public:
IntDevice(SimObject * parent, Tick latency = 0) :
intMasterPort(parent->name() + ".int_master", parent, this, latency)
{
}
virtual ~IntDevice()
{}
virtual void init();
virtual bool
recvResponse(PacketPtr pkt)
{
panic("recvResponse not implemented.\n");
}
};
} // namespace X86ISA
#endif //__DEV_X86_INTDEV_HH__
|
#include "ChronicleLogger.h"
namespace com {
namespace sowrov {
namespace util {
namespace logsystem {
ChronicleLogger ChronicleLogger::logger;
ChronicleLogger::ChronicleLogger() {
this->device = NULL;
this->format = NULL;
this->setDevice(new LogSystem::device::Console());
this->setLogFormatter(new LogSystem::format::PlainText());
}
ChronicleLogger::~ChronicleLogger() {
if (this->device != NULL) {
//if the old device is not fresh then write the final format
if (this->format != NULL && !this->device->isFreshDevice()) {
this->device->write(this->format->getFinalFormat());
}
this->device->flush();
this->device->close();
delete this->device;
}
if (this->format != NULL) {
delete this->format;
}
}
ChronicleLogger& ChronicleLogger::getLogger () {
return ChronicleLogger::logger;
}
void ChronicleLogger::setDevice(LogSystem::device::OutputDevice *device) {
if (this->device != NULL) {
//if the old device is not fresh then write the final format
if (this->format != NULL && !this->device->isFreshDevice()) {
this->device->write(this->format->getFinalFormat());
}
this->device->flush();
this->device->close();
delete this->device;
}
this->device = device;
this->device->init();
}
void ChronicleLogger::setLogFormatter(LogSystem::format::LogFormatter *format) {
if (this->format != NULL) {
delete this->format;
}
this->format = format;
}
void ChronicleLogger::setLevel (int level) {
this->levelManager.setLevel(level);
}
bool ChronicleLogger::isEnableLevel(int level) {
return this->levelManager.isEnableLevel (level);
}
void ChronicleLogger::log(std::string message, int logLevel, int lineNo, std::string functionName, std::string fileName) {
_CLThreadLock();
if (this->device == NULL) {
this->setDevice(new LogSystem::device::Console());
}
if (this->device->isFreshDevice ()) {
this->device->write (this->format->getIntroFormat ());
}
if (logLevel == 1) {
this->device->write (this->format->getFatalFormat (message, lineNo, functionName, fileName));
}
else if (logLevel == 2) {
this->device->write (this->format->getCriticalFormat (message, lineNo, functionName, fileName));
}
else if (logLevel == 3) {
this->device->write (this->format->getWarningFormat (message, lineNo, functionName, fileName));
}
else if (logLevel == 4) {
this->device->write (this->format->getInfoFormat (message, lineNo, functionName, fileName));
}
else if (logLevel == 5) {
this->device->write (this->format->getDebugFormat (message, lineNo, functionName, fileName));
}
_CLThreadUnLock();
}
void ChronicleLogger::logFatal (std::string message, int lineNo, std::string functionName, std::string fileName) {
this->log (message, 1, lineNo, functionName, fileName);
}
void ChronicleLogger::logCritical (std::string message, int lineNo, std::string functionName, std::string fileName) {
this->log (message, 2, lineNo, functionName, fileName);
}
void ChronicleLogger::logWarning (std::string message, int lineNo, std::string functionName, std::string fileName) {
this->log (message, 3, lineNo, functionName, fileName);
}
void ChronicleLogger::logInfo (std::string message, int lineNo, std::string functionName, std::string fileName) {
this->log (message, 4, lineNo, functionName, fileName);
}
void ChronicleLogger::logDebug (std::string message, int lineNo, std::string functionName, std::string fileName) {
this->log (message, 5, lineNo, functionName, fileName);
}
//logStackTrace()
}
}
}
}
|
#include "common.hpp"
#define TESTED_TYPE int
void is_empty(TESTED_NAMESPACE::list<TESTED_TYPE> const &lst)
{
std::cout << "is_empty: " << lst.empty() << std::endl;
}
int main(void)
{
TESTED_NAMESPACE::list<TESTED_TYPE> lst(7, 20);
TESTED_NAMESPACE::list<TESTED_TYPE> lst2;
TESTED_NAMESPACE::list<TESTED_TYPE>::iterator it = lst.begin();
for (unsigned long int i = 2; i < lst.size(); ++i)
*it++ = (lst.size() - i) * 3;
printSize(lst);
lst.resize(10, 42);
printSize(lst);
is_empty(lst2);
lst2 = lst;
is_empty(lst2);
it = lst.begin();
lst.resize(8, 84);
for (unsigned long int i = 3; i < lst.size(); ++i)
*it++ = (lst.size() - i) * 7;
printSize(lst);
printSize(lst2);
lst2.resize(0);
is_empty(lst2);
printSize(lst2);
return (0);
}
|
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
using namespace std;
#define ll long long
#define mem(Arr,x) memset(Arr,x,sizeof(Arr))
const int Mod=1e9+7;
class Matrix
{
public:
ll M[3][3];
Matrix()
{
mem(M,0);
}
Matrix(int Arr[3][3])
{
for (int i=0;i<3;i++)
for (int j=0;j<3;j++)
M[i][j]=Arr[i][j];
}
};
Matrix operator * (Matrix A,Matrix B)
{
Matrix Ans;
for (int i=0;i<3;i++)
for (int j=0;j<3;j++)
for (int k=0;k<3;k++)
Ans.M[i][j]=(Ans.M[i][j]+A.M[i][k]*B.M[k][j]%Mod)%Mod;
return Ans;
}
int Solve(int n);
int main()
{
int T;
scanf("%d",&T);
while (T--)
{
int n;
scanf("%d",&n);
printf("%d\n",Solve(n));
}
return 0;
}
int Solve(int n)
{
if (n<=3) return 1;
n=n-3;
int Arr[3][3]={{1,1,1},
{0,0,0},
{0,0,0}};
int Brr[3][3]={{1,1,0},
{0,0,1},
{1,0,0}};
Matrix A(Arr);
Matrix B(Brr);
while (n)
{
if (n&1) A=A*B;
B=B*B;
n=n>>1;
}
return A.M[0][0];
}
|
#include "InputPCH.h"
|
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "WebPShop.h"
//------------------------------------------------------------------------------
bool AllocateImage(ImageMemoryDesc* const image, int32 width, int32 height,
int num_channels) {
if (image == nullptr) {
LOG("/!\\ Source is null.");
return false;
}
int16 result = noErr;
if (image->pixels.data == nullptr || (image->width != width) ||
(image->height != height) || (image->num_channels != num_channels)) {
DeallocateImage(image);
image->width = width;
image->height = height;
image->num_channels = num_channels;
image->mode = plugInModeRGBColor;
image->pixels.depth = (int32)sizeof(uint8_t) * 8;
image->pixels.colBits = image->pixels.depth * image->num_channels;
image->pixels.rowBits = image->pixels.colBits * width;
const size_t image_data_size = (size_t)(image->pixels.rowBits / 8) * height;
Allocate(image_data_size, &image->pixels.data, &result);
}
return result == noErr;
}
void DeallocateImage(ImageMemoryDesc* const image) {
if (image == nullptr) {
LOG("/!\\ Source is null.");
return;
}
Deallocate(&image->pixels.data);
}
//------------------------------------------------------------------------------
void ResizeFrameVector(std::vector<FrameMemoryDesc>* const frames,
size_t size) {
if (frames == nullptr) {
LOG("/!\\ Source is null.");
return;
}
for (size_t i = size; i < frames->size(); ++i) {
DeallocateImage(&(*frames)[i].image);
}
frames->resize(size);
}
void ClearFrameVector(std::vector<FrameMemoryDesc>* const frames) {
ResizeFrameVector(frames, 0);
}
//------------------------------------------------------------------------------
bool Scale(const ImageMemoryDesc& src, ImageMemoryDesc* const dst,
size_t dst_width, size_t dst_height) {
if (src.pixels.data == nullptr || src.width < 1 || src.height < 1 ||
dst == nullptr) {
LOG("/!\\ Source or destination is null.");
return false;
}
if (!AllocateImage(dst, (int32)dst_width, (int32)dst_height,
src.num_channels)) {
LOG("/!\\ AllocateImage failed.");
return false;
}
dst->mode = src.mode;
for (size_t dst_x = 0; dst_x < dst_width; ++dst_x) {
const size_t src_x = dst_x * src.width / dst_width;
for (size_t dst_y = 0; dst_y < dst_height; ++dst_y) {
const size_t src_y = dst_y * src.height / dst_height;
for (int channel = 0; channel < dst->num_channels; ++channel) {
const uint8_t* src_data =
(const uint8_t*)src.pixels.data + src_x * (src.pixels.colBits / 8) +
src_y * (src.pixels.rowBits / 8) + channel * (src.pixels.depth / 8);
uint8_t* dst_data = (uint8_t*)dst->pixels.data +
dst_x * (dst->pixels.colBits / 8) +
dst_y * (dst->pixels.rowBits / 8) +
channel * (dst->pixels.depth / 8);
*dst_data = *src_data; // No interpolation.
}
}
}
return true;
}
bool Crop(const ImageMemoryDesc& src, ImageMemoryDesc* const dst,
size_t crop_width, size_t crop_height, size_t crop_left,
size_t crop_top) {
if (src.pixels.data == nullptr || src.width < 1 || src.height < 1 ||
dst == nullptr) {
LOG("/!\\ Source or destination is null.");
return false;
}
if (crop_width < 1 || crop_height < 1 ||
crop_left + crop_width > (size_t)src.width ||
crop_top + crop_height > (size_t)src.height) {
LOG("/!\\ Invalid input.");
return false;
}
if (!AllocateImage(dst, (int32)crop_width, (int32)crop_height,
src.num_channels)) {
LOG("/!\\ AllocateImage failed.");
return false;
}
dst->mode = src.mode;
for (size_t dst_x = 0; dst_x < crop_width; ++dst_x) {
const size_t src_x = crop_left + dst_x;
for (size_t dst_y = 0; dst_y < crop_height; ++dst_y) {
const size_t src_y = crop_top + dst_y;
for (int channel = 0; channel < dst->num_channels; ++channel) {
const uint8_t* src_data =
(const uint8_t*)src.pixels.data + src_x * (src.pixels.colBits / 8) +
src_y * (src.pixels.rowBits / 8) + channel * (src.pixels.depth / 8);
uint8_t* dst_data = (uint8_t*)dst->pixels.data +
dst_x * (dst->pixels.colBits / 8) +
dst_y * (dst->pixels.rowBits / 8) +
channel * (dst->pixels.depth / 8);
*dst_data = *src_data;
}
}
}
return true;
}
|
/*=============================================================================
Copyright (c) 2014 Kohei Takahashi
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#ifndef FUSION_VALUE_AT_IMPL_16122014_1641
#define FUSION_VALUE_AT_IMPL_16122014_1641
#include <boost/config.hpp>
#include <boost/fusion/support/config.hpp>
///////////////////////////////////////////////////////////////////////////////
// Without variadics, we will use the PP version
///////////////////////////////////////////////////////////////////////////////
# include <boost/fusion/container/vector/detail/cpp03/value_at_impl.hpp>
#endif
|
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */
#include <sstream>
#include <limits>
#include "ifcpp/model/AttributeObject.h"
#include "ifcpp/model/BuildingException.h"
#include "ifcpp/model/BuildingGuid.h"
#include "ifcpp/reader/ReaderUtil.h"
#include "ifcpp/writer/WriterUtil.h"
#include "ifcpp/IFC4/include/IfcConnectionGeometry.h"
#include "ifcpp/IFC4/include/IfcConnectionTypeEnum.h"
#include "ifcpp/IFC4/include/IfcElement.h"
#include "ifcpp/IFC4/include/IfcGloballyUniqueId.h"
#include "ifcpp/IFC4/include/IfcInteger.h"
#include "ifcpp/IFC4/include/IfcLabel.h"
#include "ifcpp/IFC4/include/IfcOwnerHistory.h"
#include "ifcpp/IFC4/include/IfcRelConnectsPathElements.h"
#include "ifcpp/IFC4/include/IfcText.h"
// ENTITY IfcRelConnectsPathElements
IfcRelConnectsPathElements::IfcRelConnectsPathElements() {}
IfcRelConnectsPathElements::IfcRelConnectsPathElements( int id ) { m_entity_id = id; }
IfcRelConnectsPathElements::~IfcRelConnectsPathElements() {}
shared_ptr<BuildingObject> IfcRelConnectsPathElements::getDeepCopy( BuildingCopyOptions& options )
{
shared_ptr<IfcRelConnectsPathElements> copy_self( new IfcRelConnectsPathElements() );
if( m_GlobalId )
{
if( options.create_new_IfcGloballyUniqueId ) { copy_self->m_GlobalId = shared_ptr<IfcGloballyUniqueId>(new IfcGloballyUniqueId( createGUID32_wstr().c_str() ) ); }
else { copy_self->m_GlobalId = dynamic_pointer_cast<IfcGloballyUniqueId>( m_GlobalId->getDeepCopy(options) ); }
}
if( m_OwnerHistory )
{
if( options.shallow_copy_IfcOwnerHistory ) { copy_self->m_OwnerHistory = m_OwnerHistory; }
else { copy_self->m_OwnerHistory = dynamic_pointer_cast<IfcOwnerHistory>( m_OwnerHistory->getDeepCopy(options) ); }
}
if( m_Name ) { copy_self->m_Name = dynamic_pointer_cast<IfcLabel>( m_Name->getDeepCopy(options) ); }
if( m_Description ) { copy_self->m_Description = dynamic_pointer_cast<IfcText>( m_Description->getDeepCopy(options) ); }
if( m_ConnectionGeometry ) { copy_self->m_ConnectionGeometry = dynamic_pointer_cast<IfcConnectionGeometry>( m_ConnectionGeometry->getDeepCopy(options) ); }
if( m_RelatingElement ) { copy_self->m_RelatingElement = dynamic_pointer_cast<IfcElement>( m_RelatingElement->getDeepCopy(options) ); }
if( m_RelatedElement ) { copy_self->m_RelatedElement = dynamic_pointer_cast<IfcElement>( m_RelatedElement->getDeepCopy(options) ); }
for( size_t ii=0; ii<m_RelatingPriorities.size(); ++ii )
{
auto item_ii = m_RelatingPriorities[ii];
if( item_ii )
{
copy_self->m_RelatingPriorities.push_back( dynamic_pointer_cast<IfcInteger>(item_ii->getDeepCopy(options) ) );
}
}
for( size_t ii=0; ii<m_RelatedPriorities.size(); ++ii )
{
auto item_ii = m_RelatedPriorities[ii];
if( item_ii )
{
copy_self->m_RelatedPriorities.push_back( dynamic_pointer_cast<IfcInteger>(item_ii->getDeepCopy(options) ) );
}
}
if( m_RelatedConnectionType ) { copy_self->m_RelatedConnectionType = dynamic_pointer_cast<IfcConnectionTypeEnum>( m_RelatedConnectionType->getDeepCopy(options) ); }
if( m_RelatingConnectionType ) { copy_self->m_RelatingConnectionType = dynamic_pointer_cast<IfcConnectionTypeEnum>( m_RelatingConnectionType->getDeepCopy(options) ); }
return copy_self;
}
void IfcRelConnectsPathElements::getStepLine( std::stringstream& stream ) const
{
stream << "#" << m_entity_id << "= IFCRELCONNECTSPATHELEMENTS" << "(";
if( m_GlobalId ) { m_GlobalId->getStepParameter( stream ); } else { stream << "*"; }
stream << ",";
if( m_OwnerHistory ) { stream << "#" << m_OwnerHistory->m_entity_id; } else { stream << "*"; }
stream << ",";
if( m_Name ) { m_Name->getStepParameter( stream ); } else { stream << "*"; }
stream << ",";
if( m_Description ) { m_Description->getStepParameter( stream ); } else { stream << "*"; }
stream << ",";
if( m_ConnectionGeometry ) { stream << "#" << m_ConnectionGeometry->m_entity_id; } else { stream << "*"; }
stream << ",";
if( m_RelatingElement ) { stream << "#" << m_RelatingElement->m_entity_id; } else { stream << "*"; }
stream << ",";
if( m_RelatedElement ) { stream << "#" << m_RelatedElement->m_entity_id; } else { stream << "*"; }
stream << ",";
writeNumericTypeList( stream, m_RelatingPriorities );
stream << ",";
writeNumericTypeList( stream, m_RelatedPriorities );
stream << ",";
if( m_RelatedConnectionType ) { m_RelatedConnectionType->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
if( m_RelatingConnectionType ) { m_RelatingConnectionType->getStepParameter( stream ); } else { stream << "$"; }
stream << ");";
}
void IfcRelConnectsPathElements::getStepParameter( std::stringstream& stream, bool ) const { stream << "#" << m_entity_id; }
const std::wstring IfcRelConnectsPathElements::toString() const { return L"IfcRelConnectsPathElements"; }
void IfcRelConnectsPathElements::readStepArguments( const std::vector<std::wstring>& args, const std::map<int,shared_ptr<BuildingEntity> >& map )
{
const size_t num_args = args.size();
if( num_args != 11 ){ std::stringstream err; err << "Wrong parameter count for entity IfcRelConnectsPathElements, expecting 11, having " << num_args << ". Entity ID: " << m_entity_id << std::endl; throw BuildingException( err.str().c_str() ); }
m_GlobalId = IfcGloballyUniqueId::createObjectFromSTEP( args[0], map );
readEntityReference( args[1], m_OwnerHistory, map );
m_Name = IfcLabel::createObjectFromSTEP( args[2], map );
m_Description = IfcText::createObjectFromSTEP( args[3], map );
readEntityReference( args[4], m_ConnectionGeometry, map );
readEntityReference( args[5], m_RelatingElement, map );
readEntityReference( args[6], m_RelatedElement, map );
readTypeOfIntegerList( args[7], m_RelatingPriorities );
readTypeOfIntegerList( args[8], m_RelatedPriorities );
m_RelatedConnectionType = IfcConnectionTypeEnum::createObjectFromSTEP( args[9], map );
m_RelatingConnectionType = IfcConnectionTypeEnum::createObjectFromSTEP( args[10], map );
}
void IfcRelConnectsPathElements::getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes )
{
IfcRelConnectsElements::getAttributes( vec_attributes );
if( m_RelatingPriorities.size() > 0 )
{
shared_ptr<AttributeObjectVector> RelatingPriorities_vec_object( new AttributeObjectVector() );
std::copy( m_RelatingPriorities.begin(), m_RelatingPriorities.end(), std::back_inserter( RelatingPriorities_vec_object->m_vec ) );
vec_attributes.push_back( std::make_pair( "RelatingPriorities", RelatingPriorities_vec_object ) );
}
if( m_RelatedPriorities.size() > 0 )
{
shared_ptr<AttributeObjectVector> RelatedPriorities_vec_object( new AttributeObjectVector() );
std::copy( m_RelatedPriorities.begin(), m_RelatedPriorities.end(), std::back_inserter( RelatedPriorities_vec_object->m_vec ) );
vec_attributes.push_back( std::make_pair( "RelatedPriorities", RelatedPriorities_vec_object ) );
}
vec_attributes.push_back( std::make_pair( "RelatedConnectionType", m_RelatedConnectionType ) );
vec_attributes.push_back( std::make_pair( "RelatingConnectionType", m_RelatingConnectionType ) );
}
void IfcRelConnectsPathElements::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes_inverse )
{
IfcRelConnectsElements::getAttributesInverse( vec_attributes_inverse );
}
void IfcRelConnectsPathElements::setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self_entity )
{
IfcRelConnectsElements::setInverseCounterparts( ptr_self_entity );
}
void IfcRelConnectsPathElements::unlinkFromInverseCounterparts()
{
IfcRelConnectsElements::unlinkFromInverseCounterparts();
}
|
/*
Copyright (c) 2005-2017, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "FarhadifarForce.hpp"
template<unsigned DIM>
FarhadifarForce<DIM>::FarhadifarForce()
: AbstractForce<DIM>(),
mAreaElasticityParameter(1.0), // These parameters are Case I in Farhadifar's paper
mPerimeterContractilityParameter(0.04),
mLineTensionParameter(0.12),
mBoundaryLineTensionParameter(0.12) // this parameter as such does not exist in Farhadifar's model.
{
}
template<unsigned DIM>
FarhadifarForce<DIM>::~FarhadifarForce()
{
}
template<unsigned DIM>
void FarhadifarForce<DIM>::AddForceContribution(AbstractCellPopulation<DIM>& rCellPopulation)
{
// Throw an exception message if not using a VertexBasedCellPopulation
///\todo: check whether this line influences profiling tests - if so, we should remove it.
if (dynamic_cast<VertexBasedCellPopulation<DIM>*>(&rCellPopulation) == nullptr)
{
EXCEPTION("FarhadifarForce is to be used with a VertexBasedCellPopulation only");
}
// Define some helper variables
VertexBasedCellPopulation<DIM>* p_cell_population = static_cast<VertexBasedCellPopulation<DIM>*>(&rCellPopulation);
unsigned num_nodes = p_cell_population->GetNumNodes();
unsigned num_elements = p_cell_population->GetNumElements();
// Begin by computing the area and perimeter of each element in the mesh, to avoid having to do this multiple times
std::vector<double> element_areas(num_elements);
std::vector<double> element_perimeters(num_elements);
std::vector<double> target_areas(num_elements);
for (typename VertexMesh<DIM,DIM>::VertexElementIterator elem_iter = p_cell_population->rGetMesh().GetElementIteratorBegin();
elem_iter != p_cell_population->rGetMesh().GetElementIteratorEnd();
++elem_iter)
{
unsigned elem_index = elem_iter->GetIndex();
element_areas[elem_index] = p_cell_population->rGetMesh().GetVolumeOfElement(elem_index);
element_perimeters[elem_index] = p_cell_population->rGetMesh().GetSurfaceAreaOfElement(elem_index);
try
{
// If we haven't specified a growth modifier, there won't be any target areas in the CellData array and CellData
// will throw an exception that it doesn't have "target area" entries. We add this piece of code to give a more
// understandable message. There is a slight chance that the exception is thrown although the error is not about the
// target areas.
target_areas[elem_index] = p_cell_population->GetCellUsingLocationIndex(elem_index)->GetCellData()->GetItem("target area");
}
catch (Exception&)
{
EXCEPTION("You need to add an AbstractTargetAreaModifier to the simulation in order to use a FarhadifarForce");
}
}
// Iterate over vertices in the cell population
for (unsigned node_index=0; node_index<num_nodes; node_index++)
{
Node<DIM>* p_this_node = p_cell_population->GetNode(node_index);
/*
* The force on this Node is given by the gradient of the total free
* energy of the CellPopulation, evaluated at the position of the vertex. This
* free energy is the sum of the free energies of all CellPtrs in
* the cell population. The free energy of each CellPtr is comprised of three
* terms - an area deformation energy, a perimeter deformation energy
* and line tension energy.
*
* Note that since the movement of this Node only affects the free energy
* of the CellPtrs containing it, we can just consider the contributions
* to the free energy gradient from each of these CellPtrs.
*/
c_vector<double, DIM> area_elasticity_contribution = zero_vector<double>(DIM);
c_vector<double, DIM> perimeter_contractility_contribution = zero_vector<double>(DIM);
c_vector<double, DIM> line_tension_contribution = zero_vector<double>(DIM);
// Find the indices of the elements owned by this node
std::set<unsigned> containing_elem_indices = p_cell_population->GetNode(node_index)->rGetContainingElementIndices();
// Iterate over these elements
for (std::set<unsigned>::iterator iter = containing_elem_indices.begin();
iter != containing_elem_indices.end();
++iter)
{
// Get this element, its index and its number of nodes
VertexElement<DIM, DIM>* p_element = p_cell_population->GetElement(*iter);
unsigned elem_index = p_element->GetIndex();
unsigned num_nodes_elem = p_element->GetNumNodes();
// Find the local index of this node in this element
unsigned local_index = p_element->GetNodeLocalIndex(node_index);
// Add the force contribution from this cell's area elasticity (note the minus sign)
c_vector<double, DIM> element_area_gradient =
p_cell_population->rGetMesh().GetAreaGradientOfElementAtNode(p_element, local_index);
area_elasticity_contribution -= GetAreaElasticityParameter()*(element_areas[elem_index] -
target_areas[elem_index])*element_area_gradient;
// Get the previous and next nodes in this element
unsigned previous_node_local_index = (num_nodes_elem+local_index-1)%num_nodes_elem;
Node<DIM>* p_previous_node = p_element->GetNode(previous_node_local_index);
unsigned next_node_local_index = (local_index+1)%num_nodes_elem;
Node<DIM>* p_next_node = p_element->GetNode(next_node_local_index);
// Compute the line tension parameter for each of these edges - be aware that this is half of the actual
// value for internal edges since we are looping over each of the internal edges twice
double previous_edge_line_tension_parameter = GetLineTensionParameter(p_previous_node, p_this_node, *p_cell_population);
double next_edge_line_tension_parameter = GetLineTensionParameter(p_this_node, p_next_node, *p_cell_population);
// Compute the gradient of each these edges, computed at the present node
c_vector<double, DIM> previous_edge_gradient =
-p_cell_population->rGetMesh().GetNextEdgeGradientOfElementAtNode(p_element, previous_node_local_index);
c_vector<double, DIM> next_edge_gradient = p_cell_population->rGetMesh().GetNextEdgeGradientOfElementAtNode(p_element, local_index);
// Add the force contribution from cell-cell and cell-boundary line tension (note the minus sign)
line_tension_contribution -= previous_edge_line_tension_parameter*previous_edge_gradient +
next_edge_line_tension_parameter*next_edge_gradient;
// Add the force contribution from this cell's perimeter contractility (note the minus sign)
c_vector<double, DIM> element_perimeter_gradient = previous_edge_gradient + next_edge_gradient;
perimeter_contractility_contribution -= GetPerimeterContractilityParameter()* element_perimeters[elem_index]*
element_perimeter_gradient;
}
c_vector<double, DIM> force_on_node = area_elasticity_contribution + perimeter_contractility_contribution + line_tension_contribution;
p_cell_population->GetNode(node_index)->AddAppliedForceContribution(force_on_node);
}
}
template<unsigned DIM>
double FarhadifarForce<DIM>::GetLineTensionParameter(Node<DIM>* pNodeA, Node<DIM>* pNodeB, VertexBasedCellPopulation<DIM>& rVertexCellPopulation)
{
// Find the indices of the elements owned by each node
std::set<unsigned> elements_containing_nodeA = pNodeA->rGetContainingElementIndices();
std::set<unsigned> elements_containing_nodeB = pNodeB->rGetContainingElementIndices();
// Find common elements
std::set<unsigned> shared_elements;
std::set_intersection(elements_containing_nodeA.begin(),
elements_containing_nodeA.end(),
elements_containing_nodeB.begin(),
elements_containing_nodeB.end(),
std::inserter(shared_elements, shared_elements.begin()));
// Check that the nodes have a common edge
assert(!shared_elements.empty());
// Since each internal edge is visited twice in the loop above, we have to use half the line tension parameter
// for each visit.
double line_tension_parameter_in_calculation = GetLineTensionParameter()/2.0;
// If the edge corresponds to a single element, then the cell is on the boundary
if (shared_elements.size() == 1)
{
line_tension_parameter_in_calculation = GetBoundaryLineTensionParameter();
}
return line_tension_parameter_in_calculation;
}
template<unsigned DIM>
double FarhadifarForce<DIM>::GetAreaElasticityParameter()
{
return mAreaElasticityParameter;
}
template<unsigned DIM>
double FarhadifarForce<DIM>::GetPerimeterContractilityParameter()
{
return mPerimeterContractilityParameter;
}
template<unsigned DIM>
double FarhadifarForce<DIM>::GetLineTensionParameter()
{
return mLineTensionParameter;
}
template<unsigned DIM>
double FarhadifarForce<DIM>::GetBoundaryLineTensionParameter()
{
return mBoundaryLineTensionParameter;
}
template<unsigned DIM>
void FarhadifarForce<DIM>::SetAreaElasticityParameter(double areaElasticityParameter)
{
mAreaElasticityParameter = areaElasticityParameter;
}
template<unsigned DIM>
void FarhadifarForce<DIM>::SetPerimeterContractilityParameter(double perimeterContractilityParameter)
{
mPerimeterContractilityParameter = perimeterContractilityParameter;
}
template<unsigned DIM>
void FarhadifarForce<DIM>::SetLineTensionParameter(double lineTensionParameter)
{
mLineTensionParameter = lineTensionParameter;
}
template<unsigned DIM>
void FarhadifarForce<DIM>::SetBoundaryLineTensionParameter(double boundaryLineTensionParameter)
{
mBoundaryLineTensionParameter = boundaryLineTensionParameter;
}
template<unsigned DIM>
void FarhadifarForce<DIM>::OutputForceParameters(out_stream& rParamsFile)
{
*rParamsFile << "\t\t\t<AreaElasticityParameter>" << mAreaElasticityParameter << "</AreaElasticityParameter>\n";
*rParamsFile << "\t\t\t<PerimeterContractilityParameter>" << mPerimeterContractilityParameter << "</PerimeterContractilityParameter>\n";
*rParamsFile << "\t\t\t<LineTensionParameter>" << mLineTensionParameter << "</LineTensionParameter>\n";
*rParamsFile << "\t\t\t<BoundaryLineTensionParameter>" << mBoundaryLineTensionParameter << "</BoundaryLineTensionParameter>\n";
// Call method on direct parent class
AbstractForce<DIM>::OutputForceParameters(rParamsFile);
}
// Explicit instantiation
template class FarhadifarForce<1>;
template class FarhadifarForce<2>;
template class FarhadifarForce<3>;
// Serialization for Boost >= 1.36
#include "SerializationExportWrapperForCpp.hpp"
EXPORT_TEMPLATE_CLASS_SAME_DIMS(FarhadifarForce)
|
// _ _____ __________
// | | / / _ | / __/_ __/ Visibility
// | |/ / __ |_\ \ / / Across
// |___/_/ |_/___/ /_/ Space and Time
//
// SPDX-FileCopyrightText: (c) 2021 The VAST Contributors
// SPDX-License-Identifier: BSD-3-Clause
#pragma once
#include "vast/expression.hpp"
#include "vast/transform.hpp"
namespace vast {
// Selects mathcing rows from the input
class select_step : public transform_step {
public:
select_step(std::string expr);
/// Applies the transformation to a record batch with a corresponding vast
/// layout.
[[nodiscard]] caf::error
add(type layout, std::shared_ptr<arrow::RecordBatch> batch) override;
/// Retrieves the result of the transformation.
[[nodiscard]] caf::expected<std::vector<transform_batch>> finish() override;
private:
caf::expected<vast::expression> expression_;
/// The slices being transformed.
std::vector<transform_batch> transformed_;
};
} // namespace vast
|
// Copyright (c) 2001-2011 Joel de Guzman
// Copyright (c) 2001-2011 Hartmut Kaiser
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#if !defined(BOOST_SPIRIT_KARMA_GRAMMAR_MAR_05_2007_0542PM)
#define BOOST_SPIRIT_KARMA_GRAMMAR_MAR_05_2007_0542PM
#if defined(_MSC_VER)
#pragma once
#endif
#include <boost/spirit/home/support/unused.hpp>
#include <boost/spirit/home/support/info.hpp>
#include <boost/spirit/home/support/assert_msg.hpp>
#include <boost/spirit/home/karma/domain.hpp>
#include <boost/spirit/home/karma/nonterminal/rule.hpp>
#include <boost/spirit/home/karma/nonterminal/nonterminal_fwd.hpp>
#include <boost/spirit/home/karma/reference.hpp>
#include <boost/noncopyable.hpp>
#include <boost/proto/extends.hpp>
#include <boost/proto/traits.hpp>
#include <boost/type_traits/is_same.hpp>
namespace boost { namespace spirit { namespace karma
{
template <
typename OutputIterator, typename T1, typename T2, typename T3
, typename T4>
struct grammar
: proto::extends<
typename proto::terminal<
reference<rule<OutputIterator, T1, T2, T3, T4> const>
>::type
, grammar<OutputIterator, T1, T2, T3, T4>
>
, generator<grammar<OutputIterator, T1, T2, T3, T4> >
, noncopyable
{
typedef OutputIterator iterator_type;
typedef rule<OutputIterator, T1, T2, T3, T4> start_type;
typedef typename start_type::properties properties;
typedef typename start_type::sig_type sig_type;
typedef typename start_type::locals_type locals_type;
typedef typename start_type::delimiter_type delimiter_type;
typedef typename start_type::encoding_type encoding_type;
typedef grammar<OutputIterator, T1, T2, T3, T4> base_type;
typedef reference<start_type const> reference_;
typedef typename proto::terminal<reference_>::type terminal;
static size_t const params_size = start_type::params_size;
template <typename Context, typename Unused>
struct attribute
{
typedef typename start_type::attr_type type;
};
// the output iterator is always wrapped by karma
typedef detail::output_iterator<OutputIterator, properties>
output_iterator;
grammar(start_type const& start
, std::string const& name_ = "unnamed-grammar")
: proto::extends<terminal, base_type>(terminal::make(reference_(start)))
, name_(name_)
{}
// This constructor is used to catch if the start rule is not
// compatible with the grammar.
template <typename Iterator_, typename T1_, typename T2_, typename T3_,
typename T4_>
grammar(rule<Iterator_, T1_, T2_, T3_, T4_> const&
, std::string const& = "unnamed-grammar")
{
// If you see the assertion below failing then the start rule
// passed to the constructor of the grammar is not compatible with
// the grammar (i.e. it uses different template parameters).
BOOST_SPIRIT_ASSERT_MSG(
(is_same<start_type, rule<Iterator_, T1_, T2_, T3_, T4_> >::value)
, incompatible_start_rule, (rule<Iterator_, T1_, T2_, T3_, T4_>));
}
std::string name() const
{
return name_;
}
void name(std::string const& str)
{
name_ = str;
}
template <typename Context, typename Delimiter, typename Attribute>
bool generate(output_iterator& sink, Context& context
, Delimiter const& delim, Attribute const& attr) const
{
return this->proto_base().child0.generate(
sink, context, delim, attr);
}
template <typename Context>
info what(Context&) const
{
return info(name_);
}
// bring in the operator() overloads
start_type const& get_parameterized_subject() const
{ return this->proto_base().child0.ref.get(); }
typedef start_type parameterized_subject_type;
#include <boost/spirit/home/karma/nonterminal/detail/fcall.hpp>
std::string name_;
};
}}}
namespace boost { namespace spirit { namespace traits
{
///////////////////////////////////////////////////////////////////////////
template <
typename IteratorA, typename IteratorB, typename Attribute
, typename Context, typename T1, typename T2, typename T3, typename T4>
struct handles_container<
karma::grammar<IteratorA, T1, T2, T3, T4>, Attribute, Context
, IteratorB>
: detail::nonterminal_handles_container<
typename attribute_of<
karma::grammar<IteratorA, T1, T2, T3, T4>
, Context, IteratorB
>::type, Attribute>
{};
}}}
#endif
|
//
// Boost.Pointer Container
//
// Copyright Thorsten Ottosen 2008. Use, modification and
// distribution is subject to the Boost Software License, Version
// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// For more information, see http://www.boost.org/libs/ptr_container/
//
#include "test_data.hpp"
#include <boost/test/unit_test.hpp>
#include <boost/ptr_container/exception.hpp>
#include <boost/range/sub_range.hpp>
#include <boost/cast.hpp>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <string>
//
// abstract base class definition
//
struct abstract_base
{
virtual ~abstract_base() {}
virtual void foo() = 0;
virtual abstract_base* clone() const = 0;
};
struct implementation : abstract_base
{
implementation()
{ }
implementation( const implementation& )
{ }
implementation( int, std::string, int, std::string )
{ }
virtual void foo() {}
virtual abstract_base* clone() const
{
return new implementation( *this );
}
};
inline std::ostream& operator<<( std::ostream& out, const abstract_base& r )
{
return out;
}
inline abstract_base* new_clone( const abstract_base& r )
{
return r.clone();
}
inline std::size_t hash_value( const abstract_base& b )
{
return boost::hash_value( &b );
}
//
// ptr_map test
//
template< typename C, typename B, typename T >
void ptr_map_test();
template< class Key >
Key get_next_key( const Key& k );
template<>
int get_next_key<int>( const int& )
{
return rand();
}
template<>
std::string get_next_key<std::string>( const std::string& )
{
return boost::lexical_cast<std::string>( rand() );
}
template< typename C, typename B, typename T >
void ptr_map_test()
{
using namespace boost;
BOOST_TEST_MESSAGE( "starting associative container test" );
enum { max_cnt = 10, size = 100 };
C c;
BOOST_CHECK( c.size() == 0 );
const C c2( c.begin(), c.end() );
BOOST_CHECK( c.size() == c2.size() );
C c3;
BOOST_TEST_MESSAGE( "finished construction test" );
BOOST_DEDUCED_TYPENAME C::allocator_type alloc = c.get_allocator();
BOOST_DEDUCED_TYPENAME C::iterator i = c.begin();
BOOST_DEDUCED_TYPENAME C::const_iterator ci = c2.begin();
BOOST_DEDUCED_TYPENAME C::iterator i2 = c.end();
BOOST_DEDUCED_TYPENAME C::const_iterator ci2 = c2.begin();
ci = c.cbegin();
ci = c.cend();
BOOST_DEDUCED_TYPENAME C::key_type a_key;
BOOST_TEST_MESSAGE( "finished iterator test" );
BOOST_DEDUCED_TYPENAME C::size_type s = c.size();
BOOST_DEDUCED_TYPENAME C::size_type s2 = c.max_size();
hide_warning(s2);
BOOST_CHECK_EQUAL( c.size(), s );
bool b = c.empty();
hide_warning(b);
BOOST_TEST_MESSAGE( "finished accessors test" );
a_key = get_next_key( a_key );
c.insert( a_key, new T );
a_key = get_next_key( a_key );
c.insert( a_key, new T );
c3.insert( c.begin(), c.end() );
c.insert( c3 );
c.erase( c.begin() );
BOOST_CHECK( c3.end() == c3.erase( boost::make_iterator_range(c3) ) );
c3.erase( a_key );
BOOST_CHECK( c3.empty() );
c.swap( c3 );
swap(c,c3);
swap(c3,c);
BOOST_CHECK( !c3.empty() );
c3.clear();
BOOST_CHECK( c3.empty() );
BOOST_TEST_MESSAGE( "finished modifiers test" );
a_key = get_next_key( a_key );
c.insert( a_key, new T );
a_key = get_next_key( a_key );
c.insert( a_key, std::auto_ptr<T>( new T ) );
typename C::auto_type ptr2 = c.release( c.begin() );
std::auto_ptr<C> ap = c.release();
c = c2.clone();
BOOST_TEST_MESSAGE( "finished release/clone test" );
a_key = get_next_key( a_key );
c3.insert( a_key, new T );
a_key = get_next_key( a_key );
c3.insert( a_key, new T );
c. BOOST_NESTED_TEMPLATE transfer<C>( c3.begin(), c3 );
c. BOOST_NESTED_TEMPLATE transfer<C>( c3.begin(), c3.end(), c3 );
BOOST_CHECK( c3.empty() );
BOOST_CHECK( !c.empty() );
c3. BOOST_NESTED_TEMPLATE transfer<C>( c );
BOOST_CHECK( !c3.empty() );
BOOST_CHECK( c.empty() );
#ifdef BOOST_NO_SFINAE
#else
c. BOOST_NESTED_TEMPLATE transfer<C>( make_iterator_range(c3), c3 );
BOOST_CHECK( !c.empty() );
BOOST_CHECK( c3.empty() );
c3. BOOST_NESTED_TEMPLATE transfer<C>(c);
#endif
BOOST_TEST_MESSAGE( "finished transfer test" );
BOOST_CHECK( !c3.empty() );
c3.replace( c3.begin(), new T );
c3.replace( c3.begin(), std::auto_ptr<T>( new T ) );
BOOST_TEST_MESSAGE( "finished set/map interface test" );
// @todo: make macro with algorithms so that the right erase() is called.
// c.unique();
// c.unique( std::not_equal_to<T>() );
// c.remove( T() );
// c.remove_if( std::binder1st< std::equal_to<T> >( T() ) );
sub_range<C> sub;
sub_range<const C> csub;
i = c.find( get_next_key( a_key ) );
ci = c2.find( get_next_key( a_key ) );
c2.count( get_next_key( a_key ) );
sub = c.equal_range( get_next_key( a_key ) );
csub = c2.equal_range( get_next_key( a_key ) );
try
{
c.at( get_next_key( a_key ) );
}
catch( const bad_ptr_container_operation& )
{ }
try
{
c2.at( get_next_key( a_key ) );
}
catch( const bad_ptr_container_operation& )
{ }
BOOST_TEST_MESSAGE( "finished algorithms interface test" );
typename C::iterator it = c.begin(), e = c.end();
for( ; it != e; ++it )
{
std::cout << "\n mapped value = " << *it->second << " key = " << it->first;
//std::cout << "\n mapped value = " << it.value() << " key = " << it.key();
}
BOOST_TEST_MESSAGE( "finished iterator test" );
a_key = get_next_key( a_key );
c.insert( a_key, new T );
c.erase( a_key );
c.erase( a_key );
}
template< class CDerived, class CBase, class T >
void test_transfer()
{
CDerived from;
CBase to;
int key = get_next_key( key );
from.insert( key, new T );
key = get_next_key( key );
from.insert( key, new T );
transfer_test( from, to );
}
template< class BaseContainer, class DerivedContainer, class Derived >
void map_container_assignment_test()
{
DerivedContainer derived;
std::string foo( "foo" );
std::string bar( "foo" );
derived.insert( foo, new Derived );
derived.insert( bar, new Derived );
BaseContainer base_container( derived );
BOOST_CHECK_EQUAL( derived.size(), base_container.size() );
base_container.clear();
base_container = derived;
BOOST_CHECK_EQUAL( derived.size(), base_container.size() );
BaseContainer base2( base_container );
BOOST_CHECK_EQUAL( base2.size(), base_container.size() );
base2 = base_container;
BOOST_CHECK_EQUAL( base2.size(), base_container.size() );
base_container = base_container;
}
template< class Cont, class Key, class T >
void test_unordered_interface()
{
Cont c;
T* t = new T;
Key key = get_next_key( key );
c.insert( key, t );
typename Cont::local_iterator i = c.begin( 0 );
typename Cont::const_local_iterator ci = i;
ci = c.cbegin( 0 );
i = c.end( 0 );
ci = c.cend( 0 );
typename Cont::size_type s = c.bucket_count();
s = c.max_bucket_count();
s = c.bucket_size( 0 );
s = c.bucket( key );
float f = c.load_factor();
f = c.max_load_factor();
c.max_load_factor(f);
c.rehash(1000);
}
#include <boost/ptr_container/ptr_unordered_map.hpp>
using namespace std;
void test_map()
{
ptr_map_test< ptr_unordered_map<int, Base>, Base, Derived_class >();
ptr_map_test< ptr_unordered_map<int, Value>, Value, Value >();
ptr_map_test< ptr_unordered_map<int, nullable<Base> >, Base, Derived_class >();
ptr_map_test< ptr_unordered_map<int, nullable<Value> >, Value, Value >();
ptr_map_test< ptr_unordered_map<int, abstract_base>, abstract_base, implementation >();
ptr_map_test< ptr_unordered_multimap<int,Base>, Base, Derived_class >();
ptr_map_test< ptr_unordered_multimap<int,Value>, Value, Value >();
ptr_map_test< ptr_unordered_multimap<int, nullable<Base> >, Base, Derived_class >();
ptr_map_test< ptr_unordered_multimap<int, nullable<Value> >, Value, Value >();
map_container_assignment_test< ptr_unordered_map<std::string,Base>,
ptr_unordered_map<std::string,Derived_class>,
Derived_class>();
map_container_assignment_test< ptr_unordered_map<std::string, nullable<Base> >,
ptr_unordered_map<std::string,Derived_class>,
Derived_class>();
map_container_assignment_test< ptr_unordered_map<std::string, nullable<Base> >,
ptr_unordered_map<std::string, nullable<Derived_class> >,
Derived_class>();
map_container_assignment_test< ptr_unordered_multimap<std::string,Base>,
ptr_unordered_multimap<std::string,Derived_class>,
Derived_class>();
map_container_assignment_test< ptr_unordered_multimap<std::string, nullable<Base> >,
ptr_unordered_multimap<std::string,Derived_class>,
Derived_class>();
map_container_assignment_test< ptr_unordered_multimap<std::string, nullable<Base> >,
ptr_unordered_multimap<std::string, nullable<Derived_class> >,
Derived_class>();
test_transfer< ptr_unordered_map<int,Derived_class>, ptr_unordered_map<int,Base>, Derived_class >();
test_transfer< ptr_unordered_multimap<int,Derived_class>, ptr_unordered_multimap<int,Base>, Derived_class >();
string joe = "joe";
string brian = "brian";
string kenny = "kenny";
ptr_unordered_map<string,int> m;
m.insert( joe, new int( 4 ) );
m.insert( brian, new int( 6 ) );
BOOST_CHECK( m[ "foo" ] == 0 );
m[ "bar" ] += 5;
BOOST_CHECK( m[ "bar" ] == 5 );
m[ joe ] += 56;
m[ brian ] += 10;
BOOST_CHECK_THROW( (m.insert(kenny, 0 )), bad_ptr_container_operation );
BOOST_CHECK_THROW( (m.replace(m.begin(), 0 )), bad_ptr_container_operation );
BOOST_CHECK_THROW( (m.at("not there")), bad_ptr_container_operation );
for( ptr_unordered_map<string,int>::iterator i = m.begin();
i != m.end(); ++i )
{
if( is_null(i) )
BOOST_CHECK( false );
const string& ref = i->first;
hide_warning(ref);
int& ref2 = *(*i).second;
ref2++;
}
typedef ptr_unordered_map<string,Derived_class> map_type;
map_type m2;
m2.insert( joe, new Derived_class );
//
// This works fine since 'm2' is not const
//
m2.begin()->second->foo();
//
// These all return an implementation-defined proxy
// with two public members: 'first' and 'second'
//
map_type::value_type a_value = *m2.begin();
a_value.second->foo();
map_type::reference a_reference = *m2.begin();
a_reference.second->foo();
map_type::const_reference a_creference = *const_begin(m2);
//
//
// These will fail as iterators propagate constness
//
//a_creference.second->foo();
//a_cpointer->second->foo();
//const_begin(m2)->second->foo();
test_unordered_interface< ptr_unordered_map<string,Base>, string, Derived_class >();
test_unordered_interface< ptr_unordered_map<string,Base>, string, Derived_class >();
}
using boost::unit_test::test_suite;
test_suite* init_unit_test_suite( int argc, char* argv[] )
{
test_suite* test = BOOST_TEST_SUITE( "Pointer Container Test Suite" );
test->add( BOOST_TEST_CASE( &test_map ) );
return test;
}
|
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "stdafx.h"
#include <AzCore/PlatformDef.h>
#if defined (AZ_PLATFORM_LINUX)
#include "Linux64Specific.h"
#endif // defined (AZ_PLATFORM_LINUX)
#include "FileUtil.h"
#include "AnimationManager.h"
#include "AnimationCompiler.h" // for SEndiannessWrapper
static bool HeaderLessFuncAIM(const GlobalAnimationHeaderAIM* lhs, const GlobalAnimationHeaderAIM* rhs)
{
return lhs->m_FilePath < rhs->m_FilePath;
}
static bool HeaderLessFuncCAF(const GlobalAnimationHeaderCAF* lhs, const GlobalAnimationHeaderCAF* rhs)
{
return lhs->m_FilePath < rhs->m_FilePath;
}
bool CAnimationManager::SaveAIMImage(const char* name, FILETIME timeStamp, bool bigEndianOutput)
{
CChunkFile chunkFile;
CSaverCGF cgfSaver(chunkFile);
// Sort headers by filename. This is not required by Engine, but makes it easier to compare RC-s output.
std::vector<GlobalAnimationHeaderAIM*> sortedHeaders;
size_t numHeaders = m_arrGlobalAIM.size();
sortedHeaders.reserve(numHeaders);
for (size_t i = 0; i < numHeaders; ++i)
{
sortedHeaders.push_back(&m_arrGlobalAIM[i]);
}
std::sort(sortedHeaders.begin(), sortedHeaders.end(), HeaderLessFuncAIM);
for (size_t i = 0; i < numHeaders; ++i)
{
GlobalAnimationHeaderAIM* header = sortedHeaders[i];
if (!header->IsValid())
{
RCLogError("AIM animation header contains invalid values (NANs). Animation skipped: '%s'.",
header->GetFilePath());
continue;
}
header->SaveToChunkFile(&chunkFile, bigEndianOutput);
}
#if defined(AZ_PLATFORM_WINDOWS)
SetFileAttributes(name, FILE_ATTRIBUTE_ARCHIVE);
#endif
chunkFile.Write(name);
FileUtil::SetFileTimes(name, timeStamp);
const int64 fileSize = FileUtil::GetFileSize(name);
if (fileSize < 0)
{
RCLogError("Failed to get file size of '%s'", name);
return false;
}
if (fileSize > 0xffFFffFFU)
{
RCLogError("Unexpected huge file '%s' found", name);
return false;
}
return true;
}
//---------------------------------------------------------------
//---------------------------------------------------------------
//---------------------------------------------------------------
bool CAnimationManager::SaveCAFImage(const char* name, FILETIME timeStamp, bool bigEndianOutput)
{
SEndiannessSwapper swap(bigEndianOutput);
CChunkFile chunkFile;
CSaverCGF cgfSaver(chunkFile);
// Sort headers by filename. This is not required by Engine, but makes it easier to compare RC-s output.
std::vector<GlobalAnimationHeaderCAF*> sortedHeaders;
size_t numHeaders = m_arrGlobalAnimations.size();
sortedHeaders.reserve(numHeaders);
for (size_t i = 0; i < numHeaders; ++i)
{
sortedHeaders.push_back(&m_arrGlobalAnimations[i]);
}
std::sort(sortedHeaders.begin(), sortedHeaders.end(), &HeaderLessFuncCAF);
uint32 numGAH = m_arrGlobalAnimations.size();
for (size_t i = 0; i < numHeaders; ++i)
{
GlobalAnimationHeaderCAF* header = sortedHeaders[i];
if (header->IsAimpose())
{
continue;
}
header->SaveToChunkFile(&chunkFile, bigEndianOutput);
}
#if defined(AZ_PLATFORM_WINDOWS)
SetFileAttributes(name, FILE_ATTRIBUTE_ARCHIVE);
#endif
chunkFile.Write(name);
FileUtil::SetFileTimes(name, timeStamp);
const int64 fileSize = FileUtil::GetFileSize(name);
if (fileSize < 0)
{
RCLogError("Failed to get file size of '%s'", name);
return false;
}
if (fileSize > 0xffFFffFFU)
{
RCLogError("Unexpected huge file '%s' found", name);
return false;
}
return true;
}
bool CAnimationManager::AddAIMHeaderOnly(const GlobalAnimationHeaderAIM& header)
{
if (header.m_FilePathCRC32 == 0)
{
RCLogError("AnimationManager: Adding GlobalAnimationHeaderAIM with m_FilePathCRC32 == 0.");
return false;
}
GlobalAnimationHeaderAIM newHeader = header;
uint32 numControllers = newHeader.m_arrController.size();
for (size_t i = 0; i < numControllers; ++i)
{
newHeader.m_arrController[i].reset(); // release controllers
}
AZStd::lock_guard<AZStd::mutex> lock(m_lockAIMs);
if (HasAIM(header.m_FilePathCRC32))
{
return false;
}
m_arrGlobalAIM.push_back(header);
return true;
}
bool CAnimationManager::AddCAFHeaderOnly(const GlobalAnimationHeaderCAF& header)
{
GlobalAnimationHeaderCAF newHeader = header;
newHeader.m_arrController.clear();
if (newHeader.m_FilePathCRC32 == 0)
{
RCLogError("AnimationManager: Adding GlobalAnimationHeaderCAF with null m_FilePathCRC32.");
return false;
}
AZStd::lock_guard<AZStd::mutex> lock(m_lockCAFs);
if (HasCAF(header.m_FilePathCRC32))
{
return false;
}
m_arrGlobalAnimations.push_back(newHeader);
return true;
}
bool CAnimationManager::HasAIMHeader(const GlobalAnimationHeaderAIM& gah) const
{
return HasAIM(gah.m_FilePathCRC32);
}
bool CAnimationManager::HasAIM(uint32 pathCRC) const
{
int32 numAIM = m_arrGlobalAIM.size();
for (int32 i = 0; i < numAIM; ++i)
{
if (m_arrGlobalAIM[i].m_FilePathCRC32 == pathCRC)
{
return true;
}
}
return false;
}
bool CAnimationManager::HasCAFHeader(const GlobalAnimationHeaderCAF& gah) const
{
return HasCAF(gah.m_FilePathCRC32);
}
bool CAnimationManager::HasCAF(uint32 pathCRC) const
{
int32 numAIM = m_arrGlobalAnimations.size();
for (int32 i = 0; i < numAIM; ++i)
{
if (m_arrGlobalAnimations[i].m_FilePathCRC32 == pathCRC)
{
return true;
}
}
return false;
}
|
// Copyright 2020 Advanced Remanufacturing and Technology Centre
// Copyright 2020 ROS-Industrial Consortium Asia Pacific Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <QKeyEvent>
#include <boost/filesystem.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cstdio>
#include "gui/ui_scene_select.h"
#include "gui/scene_select.h"
#include "gui/replacewarning.h"
#include "gui/addscene.h"
#include "yaml_parser/generate_yaml.h"
#include "include/armhand_xacro_parser.h"
#include "include/file_functions.h"
#include "include/object_package_parser.h"
#include "include/object_xacro_parser.h"
#include "include/scene_check.h"
#include "include/scene_parser.h"
#include "include/scene_xacro_parser.h"
SceneSelect::SceneSelect(QWidget * parent)
: QDialog(parent),
ui(new Ui::SceneSelect)
{
scenes_path = boost::filesystem::current_path();
boost::filesystem::current_path(boost::filesystem::current_path().branch_path());
workcell_path = boost::filesystem::current_path();
try {
boost::filesystem::current_path("easy_manipulation_deployment/workcell_builder/examples");
} catch (boost::filesystem::filesystem_error const & e) {
std::cerr << e.what() << '\n';
}
example_path = boost::filesystem::current_path();
boost::filesystem::current_path(workcell_path);
boost::filesystem::current_path("assets");
assets_path = boost::filesystem::current_path();
boost::filesystem::current_path(scenes_path);
ui->setupUi(this);
}
SceneSelect::~SceneSelect()
{
delete ui;
}
void SceneSelect::load_workcell(Workcell workcell_input)
{
workcell = workcell_input;
refresh_scenes(0);
}
void SceneSelect::on_add_scene_clicked()
{
boost::filesystem::current_path(scenes_path);
AddScene scene_window;
scene_window.setWindowTitle("Create New Scene");
scene_window.setModal(true);
scene_window.workcell_path = workcell_path;
scene_window.exec();
if (scene_window.success) {
boost::filesystem::current_path(scenes_path);
workcell.scene_vector.push_back(scene_window.scene);
generate_scene_package(scenes_path, scene_window.scene.name, workcell.ros_ver);
refresh_scenes(workcell.scene_vector.size() - 1);
}
boost::filesystem::current_path(scenes_path);
}
void SceneSelect::generate_scene_package(
boost::filesystem::path scene_filepath,
std::string scene_name, int ros_ver)
{
boost::filesystem::current_path(scene_filepath);
if (!boost::filesystem::exists(scene_name)) {
boost::filesystem::create_directory(scene_name);
}
boost::filesystem::current_path(scene_name);
if (!boost::filesystem::exists("urdf")) {
boost::filesystem::create_directory("urdf");
}
boost::filesystem::path workcell_path(scene_filepath.branch_path());
generate_cmakelists(workcell_path, scene_name, ros_ver);
generate_package_xml(workcell_path, scene_name, ros_ver);
boost::filesystem::current_path(scene_filepath);
}
void SceneSelect::generate_scene_files(Scene scene)
{
// generate environment.urdf.xacro
boost::filesystem::current_path(workcell_path.string() + "/scenes/" + scene.name + "/urdf");
generate_scene_xacro(scene);
if (scene.robot_loaded && scene.ee_loaded) {
generate_armhand_xacro(scene.robot_vector[0], scene.ee_vector[0], scene.name);
}
if (scene.robot_loaded && !scene.ee_loaded) { // no ee
generate_armhand_xacro(scene.robot_vector[0], scene.name);
}
if (!scene.robot_loaded && !scene.ee_loaded) { // no robot and ee
generate_armhand_xacro(scene.name);
}
boost::filesystem::path launch_path(
workcell_path.string() + "/easy_manipulation_deployment/workcell_builder/examples/ros" +
std::to_string(workcell.ros_ver) + "/launch");
boost::filesystem::path target_path(workcell_path.string() + "/scenes/" + scene.name + "/launch");
copyDir(launch_path, target_path);
boost::filesystem::current_path(target_path);
if (workcell.ros_ver == 1) { // ROS1
find_replace("scene.launch", "scene_interim.launch", "scene_name", scene.name);
find_replace("scene_interim.launch", "scene.launch", "robot_name", scene.robot_vector[0].name);
find_replace("demo.launch", "demo_interim.launch", "scene_name", scene.name);
find_replace("demo_interim.launch", "demo.launch", "robot_name", scene.robot_vector[0].name);
} else if (workcell.ros_ver == 2) { // ROS2
find_replace("demo.launch.py", "demo_interim.launch.py", "scene_name", scene.name);
find_replace(
"demo_interim.launch.py", "demo_interim2.launch.py", "base_link_name",
scene.robot_vector[0].base_link);
find_replace(
"demo_interim2.launch.py", "demo.launch.py", "moveit_config_name",
scene.robot_vector[0].name + "_moveit_config");
}
}
void SceneSelect::refresh_scenes(int latest_scene)
{
if (latest_scene < 0) {latest_scene = 0;}
bool oldState = ui->scene_list->blockSignals(true);
ui->scene_list->clear(); // Clear the dropdown menu
if (workcell.scene_vector.size() > 0) { // There are scenes in the workcell
ui->scene_list->setDisabled(false); // Enable the dropdown menu
for (int scene = 0; scene < static_cast<int>(workcell.scene_vector.size()); scene++) {
ui->scene_list->addItem(QString::fromStdString(workcell.scene_vector[scene].name));
}
ui->scene_list->setCurrentIndex(latest_scene); // Display the latest scene the user created
on_scene_list_currentIndexChanged(latest_scene);
ui->edit_scene->setDisabled(false);
ui->delete_scene->setDisabled(false);
ui->generate_yaml->setDisabled(false);
ui->generate_files->setDisabled(false);
} else { // no scenes
ui->scene_list->setDisabled(true);
ui->generate_yaml->setDisabled(true);
ui->generate_files->setDisabled(true);
ui->edit_scene->setDisabled(true);
ui->delete_scene->setDisabled(true);
ui->error_workcell->append("<font color='red'> No scenes available. </font>");
}
ui->scene_list->blockSignals(oldState);
}
void SceneSelect::on_delete_scene_clicked()
{
ReplaceWarning replace_window;
replace_window.setWindowTitle("Edit Scene");
replace_window.set_label("Warning: Scene folders with all files will be deleted. Continue?");
replace_window.setModal(true);
replace_window.exec();
if (replace_window.decision) { // user allows for scene folder deletion
ui->error_workcell->clear();
if (ui->scene_list->currentIndex() >= 0) {
bool oldState = ui->scene_list->blockSignals(true);
delete_folder(scenes_path, workcell.scene_vector[ui->scene_list->currentIndex()].name);
workcell.scene_vector.erase(workcell.scene_vector.begin() + ui->scene_list->currentIndex());
if (workcell.scene_vector.size() > 0) {
refresh_scenes(0);
} else {
refresh_scenes(-1);
}
ui->scene_list->blockSignals(oldState);
} else {
ui->error_workcell->append("<font color='red'> No scene to delete! </font>");
}
}
}
void SceneSelect::on_edit_scene_clicked()
{
ui->error_workcell->clear();
boost::filesystem::current_path(scenes_path);
if (ui->scene_list->currentIndex() >= 0) { // Make sure that there are scenes to select
Scene curr_scene = workcell.scene_vector[ui->scene_list->currentIndex()];
if (!curr_scene.loaded) {
if (!load_scene_from_yaml(&curr_scene)) {
// if scene.loaded is not true, generate scene from yaml
ui->error_workcell->append("<font color='red'> Could not load scene from YAML </font>");
return;
}
}
// Scene loaded
AddScene scene_window;
scene_window.LoadScene(curr_scene);
scene_window.setWindowTitle("Edit Scene");
scene_window.setModal(true);
scene_window.exec();
if (scene_window.success) {
boost::filesystem::current_path(scenes_path);
if (CheckSceneEqual(scene_window.scene, curr_scene)) {
refresh_scenes(ui->scene_list->currentIndex());
} else { // Scene was edited
boost::filesystem::current_path(scenes_path);
boost::filesystem::path scene_yaml_path(
scenes_path.string() + "/" + scene_window.scene.name);
if (boost::filesystem::exists(scene_window.scene.name)) { // Scene name nvr change
// Replace the current environment yaml
GenerateYAML::generate_yaml(
scene_window.scene,
scene_yaml_path.string(), scenes_path, assets_path);
generate_scene_files(scene_window.scene);
} else {
// Delete previous scene folder
delete_folder(scenes_path, curr_scene.name);
// Generate new folder
generate_scene_package(scenes_path, scene_window.scene.name, workcell.ros_ver);
GenerateYAML::generate_yaml(
scene_window.scene,
scene_yaml_path.string(), scenes_path, assets_path);
generate_scene_files(scene_window.scene);
}
workcell.scene_vector[ui->scene_list->currentIndex()] = scene_window.scene;
ui->error_workcell->append(
"<font color='orange'> Warning: Scene has been edited. Previous yaml file removed."
" Click \" Generate YAML \" again to Generate YAML. </font>");
refresh_scenes(ui->scene_list->currentIndex());
}
} else {
refresh_scenes(ui->scene_list->currentIndex());
}
} else {
ui->error_workcell->append("<font color='red'> No scene to edit! </font>");
}
boost::filesystem::current_path(scenes_path);
}
void SceneSelect::on_generate_yaml_clicked()
{
ui->error_workcell->clear();
boost::filesystem::current_path(scenes_path);
if (ui->scene_list->currentIndex() >= 0) { // Make sure that there are scenes to select
boost::filesystem::path scene_yaml_path(
scenes_path.string() + "/" + workcell.scene_vector[ui->scene_list->currentIndex()].name);
Scene target_scene = workcell.scene_vector[ui->scene_list->currentIndex()];
if (!target_scene.loaded) { // No scene currently loaded
if (check_yaml()) { // If yaml file is in folder,
// it might get replaced by new scene configuration
ui->error_workcell->append(
"<font color='orange'> ERROR: No changes were made to existing scene, "
"so environment yaml remains the same </font>");
return;
} else { // No yaml in scene folder, no loaded scene from created
ui->error_workcell->append(
"<font color='red'> ERROR: No Existing YAML file found, "
"and no new scene generated. </font>");
return;
}
} else {
if (check_yaml()) { // If yaml file is in folder, it might get replaced by new config
ReplaceWarning replace_window;
replace_window.setWindowTitle("Edit Scene");
replace_window.set_label(
"Warning: Environment yaml currently exists. "
"Current environment yaml will be replaced. Continue?");
replace_window.setModal(true);
replace_window.exec();
if (replace_window.decision) { // user allows for replacing of current yaml file
GenerateYAML::generate_yaml(
target_scene,
scene_yaml_path.string(), scenes_path, assets_path);
ui->error_workcell->clear();
ui->error_workcell->append("<font color='green'> YAML Generated. </font>");
}
} else { // currently no yaml file, add one to scene folder
GenerateYAML::generate_yaml(
target_scene, scene_yaml_path.string(), scenes_path,
assets_path);
ui->error_workcell->clear();
ui->error_workcell->append("<font color='green'> YAML Generated. </font>");
}
}
} else {
ui->error_workcell->append("<font color='red'> No scene to generate yaml file </font>");
}
check_scene();
}
bool SceneSelect::check_yaml() // Check if scene package has a yaml file to use.
{
boost::filesystem::current_path(scenes_path); // in scenes folder
boost::filesystem::current_path((ui->scene_list->currentText()).toStdString());
if (!boost::filesystem::exists("environment.yaml")) {
return false;
} else {
ui->edit_scene->setDisabled(false);
}
return true;
}
bool SceneSelect::check_scene()
{
ui->error_workcell->clear();
bool has_yaml = check_yaml();
bool files_loaded_proper = check_files();
if (has_yaml) {
ui->error_workcell->append(
"<font color='green'>[Scene Status] "
"Environment YAML present </font>");
} else {
ui->error_workcell->append(
"<font color='orange'>[Scene Status] Environment YAML not present </font>");
}
if (files_loaded_proper) {
ui->error_workcell->append(
"<font color='green'>[Scene Status] All files generated properly </font>");
}
if (has_yaml && files_loaded_proper) {
ui->error_workcell->append(
"<font color='green'>[Scene Status] Scene generation complete."
" You may exit this application </font>");
}
if (!has_yaml && files_loaded_proper) {
ui->error_workcell->append(
"<font color='orange'>[Scene Status] Scene generation complete,"
" but without environment yaml you cannot edit this scene after exit. </font>");
}
ui->exit->setDisabled(false);
boost::filesystem::current_path(scenes_path);
return true;
}
bool SceneSelect::check_files()
{
boost::filesystem::current_path(scenes_path); // in scenes folder
boost::filesystem::current_path((ui->scene_list->currentText()).toStdString());
if (!boost::filesystem::exists("launch") || !boost::filesystem::exists("urdf") ||
!boost::filesystem::exists("CMakeLists.txt") || !boost::filesystem::exists("package.xml"))
{
ui->error_workcell->append(
"<font color='red'>[Scene Status] ERROR: Files not generated properly </font>");
if (!boost::filesystem::exists("launch")) {
ui->error_workcell->append(
"<font color='red'>[Scene Status] ERROR: launch folder missing </font>");
}
if (!boost::filesystem::exists("urdf")) {
ui->error_workcell->append(
"<font color='red'>[Scene Status] ERROR: urdf folder missing </font>");
}
if (!boost::filesystem::exists("CMakeLists.txt")) {
ui->error_workcell->append(
"<font color='red'>[Scene Status] ERROR: CMakeLists.txt missing </font>");
}
if (!boost::filesystem::exists("package.xml")) {
ui->error_workcell->append(
"<font color='red'>[Scene Status] ERROR: Package.xml missing </font>");
}
boost::filesystem::current_path(scenes_path);
return false;
} else {
boost::filesystem::current_path("launch");
if (!boost::filesystem::exists("demo.rviz") || !boost::filesystem::exists("demo.launch.py")) {
ui->error_workcell->append(
"<font color='red'>[Scene Status] ERROR: Files not generated properly </font>");
if (!boost::filesystem::exists("demo.rviz")) {
ui->error_workcell->append(
"<font color='red'>[Scene Status] ERROR: demo.rviz missing </font>");
}
if (!boost::filesystem::exists("demo.launch.py")) {
ui->error_workcell->append(
"<font color='red'>[Scene Status] ERROR: demo.launch.py missing </font>");
}
boost::filesystem::current_path(scenes_path);
return false;
}
boost::filesystem::current_path(boost::filesystem::current_path().branch_path());
boost::filesystem::current_path("urdf");
if (!boost::filesystem::exists("arm_hand.srdf.xacro") ||
!boost::filesystem::exists("scene.urdf.xacro"))
{
ui->error_workcell->append(
"<font color='red'>[Scene Status] ERROR: Files not generated properly </font>");
if (!boost::filesystem::exists("arm_hand.srdf.xacro")) {
ui->error_workcell->append(
"<font color='red'>[Scene Status] ERROR: arm_hand.srdf.xacro missing </font>");
}
if (!boost::filesystem::exists("scene.urdf.xacro")) {
ui->error_workcell->append(
"<font color='red'>[Scene Status] ERROR: scene.urdf.xacro missing </font>");
}
boost::filesystem::current_path(scenes_path);
return false;
}
}
return true;
}
void SceneSelect::on_scene_list_currentIndexChanged(int index)
{
ui->error_workcell->clear();
check_scene();
}
void SceneSelect::on_generate_files_clicked()
{
ui->error_workcell->clear();
boost::filesystem::current_path(scenes_path); // Scene folder
if (ui->scene_list->currentIndex() >= 0) { // Make sure that there are scenes to select
Scene curr_scene = workcell.scene_vector[ui->scene_list->currentIndex()];
if (!curr_scene.loaded) {
if (!load_scene_from_yaml(&curr_scene)) {
ui->error_workcell->append("<font color='red'> Could not load scene from YAML </font>");
return;
}
}
// Generate all environment object packages
for (Object object : curr_scene.object_vector) {
// Generate the folders and CMakeLists + Package xmls
generate_object_package(workcell_path, object, workcell.ros_ver);
// Generate urdf xacro for object
boost::filesystem::current_path(
workcell_path.string() + "/assets/environment/" + object.name + "_description/urdf");
make_object_xacro(object);
boost::filesystem::current_path(scenes_path);
}
generate_scene_files(curr_scene);
} else {
ui->error_workcell->append("<font color='red'> No scene to generate files from </font>");
}
check_scene();
}
bool SceneSelect::load_scene_from_yaml(Scene * input_scene)
{
boost::filesystem::current_path(scenes_path); // Go back to scene
try {
boost::filesystem::current_path(input_scene->name);
} catch (boost::filesystem::filesystem_error const & e) {
std::cerr << e.what() << '\n';
return false;
}
YAML::Node yaml;
// Load Yaml File.
try {
yaml = YAML::LoadFile("environment.yaml");
// std::ifstream f("environment.yaml");
// if (f.is_open())
// std::cout << f.rdbuf() << std::endl;
} catch (YAML::BadFile & error) {
ui->error_workcell->append(
"<font color='red'> Something went wrong with the yaml file."
" Please Generate it again </font>");
return false;
}
// TODO(Glenn): add error catch if trying to create directory with same name,
// or maybe add a number to it, eg table1, table2.
YAML::Node objects;
YAML::Node ext_joints;
bool has_objects;
for (YAML::iterator it = yaml.begin(); it != yaml.end(); ++it) {
std::string key = it->first.as<std::string>();
if (key.compare("robot") == 0) {
Robot robot;
SceneParser::LoadRobotFromYAML(&robot, it->second);
input_scene->robot_loaded = true;
input_scene->robot_vector.clear();
input_scene->robot_vector.push_back(robot);
}
if (key.compare("end_effector") == 0) {
EndEffector ee;
SceneParser::LoadEEFromYAML(&ee, it->second);
input_scene->ee_loaded = true;
input_scene->ee_vector.clear();
input_scene->ee_vector.push_back(ee);
}
if (key.compare("objects") == 0) {
objects = it->second;
has_objects = true;
}
if (key.compare("external joints") == 0) {
ext_joints = it->second;
}
}
if (has_objects) { // We need to do this because the object field needs to load before
// the ext joint field, and it currently has a random load order
for (YAML::iterator objects_it = objects.begin(); objects_it != objects.end(); ++objects_it) {
Object temp_object;
temp_object.name = objects_it->first.as<std::string>();
YAML::Node ext_joint;
temp_object.ext_joint.child_object = objects_it->first.as<std::string>();
for (YAML::iterator in_object_it = objects_it->second.begin();
in_object_it != objects_it->second.end(); ++in_object_it)
{
if (in_object_it->first.as<std::string>().compare("links") == 0) {
std::vector<Link> temp_link_vector;
SceneParser::LoadLinksFromYAML(&temp_link_vector, in_object_it->second);
temp_object.link_vector = temp_link_vector;
}
if (in_object_it->first.as<std::string>().compare("joints") == 0) {
std::vector<Joint> temp_joint_vector;
YAML::Node joints = in_object_it->second;
SceneParser::LoadJointsFromYAML(
&temp_joint_vector, temp_object.link_vector,
in_object_it->second);
temp_object.joint_vector = temp_joint_vector;
}
if (in_object_it->first.as<std::string>().compare(temp_object.name + "_base_joint") == 0) {
temp_object.ext_joint.name = in_object_it->first.as<std::string>();
ext_joint = in_object_it->second;
}
}
for (YAML::iterator in_ext_joint_it = ext_joint.begin(); in_ext_joint_it != ext_joint.end();
++in_ext_joint_it)
{
if (in_ext_joint_it->first.as<std::string>().compare("ext_joint_type") == 0) {
temp_object.ext_joint.type = in_ext_joint_it->second.as<std::string>();
}
if (in_ext_joint_it->first.as<std::string>().compare("child_link") == 0) {
// Get Child Link pos
std::string child_link = in_ext_joint_it->second.as<std::string>();
for (int i = 0; i < static_cast<int>(temp_object.link_vector.size()); i++) {
if (child_link.compare(temp_object.link_vector[i].name) == 0) {
temp_object.ext_joint.child_link_pos = i;
break;
}
}
}
}
input_scene->object_vector.push_back(temp_object);
}
int counter = 0;
for (YAML::iterator ext_joints_it = ext_joints.begin(); ext_joints_it != ext_joints.end();
++ext_joints_it)
{
input_scene->object_vector[counter].ext_joint.origin.is_origin = false;
input_scene->object_vector[counter].ext_joint.axis.is_axis = false;
YAML::Node in_ext_joints = ext_joints_it->second;
for (YAML::iterator in_ext_joints_it = in_ext_joints.begin();
in_ext_joints_it != in_ext_joints.end(); ++in_ext_joints_it)
{
if (in_ext_joints_it->first.as<std::string>().compare("parent object") == 0) {
std::string parent_object = in_ext_joints_it->second.as<std::string>();
if (parent_object.compare("world") == 0) { // if world pos is -1
input_scene->object_vector[counter].ext_joint.parent_obj_pos = -1;
} else {
for (int i = 0; i < static_cast<int>(input_scene->object_vector.size()); i++) {
if (parent_object.compare(input_scene->object_vector[i].name) == 0) {
input_scene->object_vector[counter].ext_joint.parent_obj_pos = i;
}
}
}
}
if (in_ext_joints_it->first.as<std::string>().compare("parent link") == 0) {
// Get Parent link pos
std::string parent_link = in_ext_joints_it->second.as<std::string>();
int parent_obj_pos = input_scene->object_vector[counter].ext_joint.parent_obj_pos;
if (parent_obj_pos >= 0) {
for (int i = 0;
i < static_cast<int>(input_scene->object_vector[parent_obj_pos].link_vector.size());
i++)
{
if (parent_link.compare(
input_scene->object_vector[parent_obj_pos].
link_vector[i].name)
==
0)
{
input_scene->object_vector[counter].ext_joint.parent_link_pos = i;
break;
}
}
}
}
if (in_ext_joints_it->first.as<std::string>().compare("origin") == 0) {
input_scene->object_vector[counter].ext_joint.origin.is_origin = true;
SceneParser::LoadOriginFromYAML(
&(input_scene->object_vector[counter].ext_joint.origin),
in_ext_joints_it->second);
}
if (in_ext_joints_it->first.as<std::string>().compare("axis") == 0) {
input_scene->object_vector[counter].ext_joint.axis.is_axis = true;
SceneParser::LoadAxisFromYAML(
&(input_scene->object_vector[counter].ext_joint.axis),
in_ext_joints_it->second);
}
}
counter++;
}
}
input_scene->loaded = true;
boost::filesystem::current_path(scenes_path);
return true;
}
void SceneSelect::on_back_clicked()
{
if (workcell.scene_vector[ui->scene_list->currentIndex()].loaded && !check_yaml()) {
ReplaceWarning replace_window;
replace_window.setWindowTitle("Edit Scene");
replace_window.set_label(
"Warning: Currently loaded scene is not saved."
" All progress will be lost. Generate yaml file before going back.");
replace_window.setModal(true);
replace_window.exec();
if (replace_window.decision) {
this->close();
}
}
}
void SceneSelect::keyPressEvent(QKeyEvent * e)
{
if (e->key() != Qt::Key_Escape) {
QDialog::keyPressEvent(e);
} else { /* minimize */}
}
void SceneSelect::on_exit_clicked()
{
QApplication::quit();
}
|
#include "solution.h"
/**
* Other solution: Newton's Alogrithm
* x < 2: just return x;
* x >= 2:
* let k = x / 2;
* while k * k > x
* let k = (k + x / k) / 2
* return k
*
* This solution:
* Runtime: 0 ms, faster than 100.00%
* Memory Usage: 5.9 MB, less than 90.34%
**/
// Runtime: 4 ms, faster than 64.97%
// Memory Usage: 5.9 MB, less than 88.13%
int Solution::mySqrt(int x)
{
// 0 or 1, just return the value.
if (x < 2)
return x;
int left = 1, right = x / 2 + 1;
long mid;
while (left + 1 < right)
{
mid = (left + right) / 2;
if (mid * mid == x)
{
left = mid;
break;
}
else if (mid * mid < x)
{
left = mid;
}
else
{
right = mid;
}
}
return left;
}
|
/*******************************<GINKGO LICENSE>******************************
Copyright (c) 2017-2021, the Ginkgo authors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************<GINKGO LICENSE>*******************************/
#include "core/stop/criterion_kernels.hpp"
#include <ginkgo/core/base/exception_helpers.hpp>
#include <ginkgo/core/base/math.hpp>
#include <ginkgo/core/stop/stopping_status.hpp>
#include <ginkgo/kernels/hip/types.hip.hpp>
#include "hip/base/math.hip.hpp"
#include "hip/components/thread_ids.hip.hpp"
namespace gko {
namespace kernels {
namespace hip {
/**
* @brief The Set all statuses namespace.
* @ref set_status
* @ingroup set_all_statuses
*/
namespace set_all_statuses {
constexpr int default_block_size = 512;
__global__ __launch_bounds__(default_block_size) void set_all_statuses(
size_type num_elems, uint8 stoppingId, bool setFinalized,
stopping_status* stop_status)
{
const auto tidx = thread::get_thread_id_flat();
if (tidx < num_elems) {
stop_status[tidx].stop(stoppingId, setFinalized);
}
}
void set_all_statuses(std::shared_ptr<const HipExecutor> exec, uint8 stoppingId,
bool setFinalized, Array<stopping_status>* stop_status)
{
const dim3 block_size(default_block_size, 1, 1);
const dim3 grid_size(ceildiv(stop_status->get_num_elems(), block_size.x), 1,
1);
hipLaunchKernelGGL((set_all_statuses), dim3(grid_size), dim3(block_size), 0,
0, stop_status->get_num_elems(), stoppingId,
setFinalized, as_hip_type(stop_status->get_data()));
}
} // namespace set_all_statuses
} // namespace hip
} // namespace kernels
} // namespace gko
|
#include "StrConvert.hpp"
TEST(StrConvert, ToUtf8)
{
{
std::string test = StrConvert::ToUtf8(L"foobar");
EXPECT_STREQ(test.c_str(), "foobar");
EXPECT_EQ(test.size(), 6u);
}
{
std::string test = StrConvert::ToUtf8(L"");
EXPECT_STREQ(test.c_str(), "");
EXPECT_EQ(test.size(),0u);
}
{
std::wstring test = StrConvert::ToUtf8("foobar");
EXPECT_STREQ(test.c_str(), L"foobar");
EXPECT_EQ(test.size(), 6u);
}
{
std::wstring test = StrConvert::ToUtf8("");
EXPECT_STREQ(test.c_str(), L"");
EXPECT_EQ(test.size(), 0u);
}
}
TEST(StrConvert, IEquals)
{
EXPECT_FALSE(StrConvert::IEquals("foobar", "fooba"));
EXPECT_FALSE(StrConvert::IEquals("fooba", "foobar"));
EXPECT_FALSE(StrConvert::IEquals("foobar", "barfoo"));
EXPECT_TRUE(StrConvert::IEquals("foobar", "fooBAR"));
EXPECT_TRUE(StrConvert::IEquals("foobar", "FOObar"));
EXPECT_TRUE(StrConvert::IEquals("fooBAR", "foobar"));
EXPECT_TRUE(StrConvert::IEquals("FOObar", "foobar"));
}
|
#include <thread>
#include <account.h>
using namespace std;
account::account(int init_balance)
{
balance_lock.lock();
balance = init_balance;
balance_lock.unlock();
}
int account::get_balance()
{
return balance;
}
void account::deposit(int amount)
{
unique_lock<mutex> lock(balance_lock);
balance += amount;
}
bool account::withdraw(int amount)
{
lock_guard<mutex> lock(balance_lock);
int new_balance{balance - amount};
if (new_balance < 0)
{
return false;
}
else
{
this_thread::yield();
balance = new_balance;
return true;
}
}
|
/**
* Copyright 2020 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <iostream>
#include <memory>
#include <vector>
#include "common/common_test.h"
#include "src/common/file_utils.h"
#include "mindspore/lite/src/runtime/kernel/arm/fp32_grad/deconvolution_grad_filter.h"
#include "nnacl/conv_parameter.h"
#include "mindspore/lite/src/kernel_registry.h"
namespace mindspore {
class TestDeConvolutionGradFp32 : public mindspore::CommonTest {
public:
TestDeConvolutionGradFp32() {}
};
TEST_F(TestDeConvolutionGradFp32, DeConvFp32FilterGrad) {
// prepare stage
auto conv_param = static_cast<ConvParameter *>(malloc(sizeof(ConvParameter)));
ASSERT_NE(conv_param, nullptr);
conv_param->input_batch_ = 2;
conv_param->input_h_ = 32;
conv_param->input_w_ = 32;
conv_param->input_channel_ = 3;
conv_param->output_batch_ = 2;
conv_param->output_h_ = 63;
conv_param->output_w_ = 63;
conv_param->output_channel_ = 9;
conv_param->kernel_h_ = 3;
conv_param->kernel_w_ = 3;
conv_param->stride_h_ = 2;
conv_param->stride_w_ = 2;
conv_param->dilation_h_ = 1;
conv_param->dilation_w_ = 1;
conv_param->pad_u_ = 1;
conv_param->pad_l_ = 1;
conv_param->pad_r_ = 1;
conv_param->pad_d_ = 1;
conv_param->group_ = 1;
conv_param->act_type_ = ActType_No;
conv_param->thread_num_ = 1;
size_t dy_size;
std::string dy_path = "./test_data/deconv/deconvfp32_dy_2_9_63_63.bin";
auto dy_data = reinterpret_cast<float *>(mindspore::lite::ReadFile(dy_path.c_str(), &dy_size));
ASSERT_NE(dy_data, nullptr);
std::vector<int> dim_dy({2, 63, 63, 9});
lite::Tensor dy_tensor(TypeId::kNumberTypeFloat32, dim_dy);
dy_tensor.set_data(dy_data);
size_t output_data_size =
conv_param->output_channel_ * conv_param->kernel_h_ * conv_param->kernel_w_ * conv_param->input_channel_;
size_t input_size;
std::string input_path = "./test_data/deconv/deconvfp32_input0_2_3_32_32.bin";
auto input_data = reinterpret_cast<float *>(mindspore::lite::ReadFile(input_path.c_str(), &input_size));
ASSERT_NE(input_data, nullptr);
std::vector<int> dim_x({2, 32, 32, 3});
lite::Tensor x_tensor(TypeId::kNumberTypeFloat32, dim_x);
x_tensor.set_data(input_data);
auto dw_data = new float[output_data_size];
ASSERT_NE(dw_data, nullptr);
std::vector<int> dim_dw({3, 3, 3, 9});
lite::Tensor dw_tensor(TypeId::kNumberTypeFloat32, dim_dw);
dw_tensor.set_data(dw_data);
std::vector<lite::Tensor *> inputs = {&dy_tensor, &x_tensor};
std::vector<lite::Tensor *> outputs = {&dw_tensor};
lite::InnerContext context;
context.thread_num_ = 1;
ASSERT_EQ(lite::RET_OK, context.Init());
kernel::KernelKey desc = {kernel::kCPU, TypeId::kNumberTypeFloat32, schema::PrimitiveType_DeConv2DGradFilter};
auto creator = lite::KernelRegistry::GetInstance()->GetCreator(desc);
ASSERT_NE(creator, nullptr);
auto kernel = creator(inputs, outputs, reinterpret_cast<OpParameter *>(conv_param), &context, desc);
ASSERT_NE(kernel, nullptr);
auto ret = kernel->Init();
EXPECT_EQ(0, ret);
kernel->AllocWorkspace();
// warm up loop
for (int i = 0; i < 3; i++) {
kernel->Run();
}
// runtime part
printf("Calculating runtime cost...\n");
uint64_t time_avg = 0;
int loop_count = 100;
auto time_start = mindspore::lite::GetTimeUs();
for (int i = 0; i < loop_count; i++) {
kernel->Run();
}
auto time_end = mindspore::lite::GetTimeUs();
auto cost = time_end - time_start;
time_avg = cost / loop_count;
printf("single thread running time : %f ms\n", time_avg / 1000.0f);
std::string output_path = "./test_data/deconv/deconvfp32_dw_9_3_3_3.bin";
auto res = CompareRelativeOutput(dw_data, output_path);
EXPECT_EQ(res, 0);
delete[] input_data;
delete[] dy_data;
delete[] dw_data;
delete kernel;
// delete conv_param;
dw_tensor.set_data(nullptr);
x_tensor.set_data(nullptr);
dy_tensor.set_data(nullptr);
MS_LOG(INFO) << "TestDeConvolutionGradFp32 Filter Grad passed";
}
TEST_F(TestDeConvolutionGradFp32, DeConvFp32Dilation2FilterGrad) {
// prepare stage
auto conv_param = static_cast<ConvParameter *>(malloc(sizeof(ConvParameter)));
ASSERT_NE(conv_param, nullptr);
conv_param->input_batch_ = 2;
conv_param->input_h_ = 32;
conv_param->input_w_ = 32;
conv_param->input_channel_ = 3;
conv_param->output_batch_ = 2;
conv_param->output_h_ = 65;
conv_param->output_w_ = 65;
conv_param->output_channel_ = 9;
conv_param->kernel_h_ = 3;
conv_param->kernel_w_ = 3;
conv_param->stride_h_ = 2;
conv_param->stride_w_ = 2;
conv_param->dilation_h_ = 2;
conv_param->dilation_w_ = 2;
conv_param->pad_u_ = 1;
conv_param->pad_l_ = 1;
conv_param->pad_r_ = 1;
conv_param->pad_d_ = 1;
conv_param->group_ = 1;
conv_param->act_type_ = ActType_No;
conv_param->thread_num_ = 1;
size_t dy_size;
std::string dy_path = "./test_data/deconv/deconvfp32_dy_d2_2_9_65_65.bin";
auto dy_data = reinterpret_cast<float *>(mindspore::lite::ReadFile(dy_path.c_str(), &dy_size));
ASSERT_NE(dy_data, nullptr);
std::vector<int> dim_dy({2, 65, 65, 9});
lite::Tensor dy_tensor(TypeId::kNumberTypeFloat32, dim_dy);
dy_tensor.set_data(dy_data);
size_t output_data_size =
conv_param->output_channel_ * conv_param->kernel_h_ * conv_param->kernel_w_ * conv_param->input_channel_;
size_t input_size;
std::string input_path = "./test_data/deconv/deconvfp32_input0_d2_2_3_32_32.bin";
auto input_data = reinterpret_cast<float *>(mindspore::lite::ReadFile(input_path.c_str(), &input_size));
ASSERT_NE(input_data, nullptr);
std::vector<int> dim_x({2, 32, 32, 3});
lite::Tensor x_tensor(TypeId::kNumberTypeFloat32, dim_x);
x_tensor.set_data(input_data);
auto dw_data = new float[output_data_size];
ASSERT_NE(dw_data, nullptr);
std::vector<int> dim_dw({9, 3, 3, 3});
lite::Tensor dw_tensor(TypeId::kNumberTypeFloat32, dim_dw);
dw_tensor.set_data(dw_data);
std::vector<lite::Tensor *> inputs = {&dy_tensor, &x_tensor};
std::vector<lite::Tensor *> outputs = {&dw_tensor};
lite::InnerContext context;
context.thread_num_ = 1;
ASSERT_EQ(lite::RET_OK, context.Init());
kernel::KernelKey desc = {kernel::kCPU, TypeId::kNumberTypeFloat32, schema::PrimitiveType_DeConv2DGradFilter};
auto creator = lite::KernelRegistry::GetInstance()->GetCreator(desc);
ASSERT_NE(creator, nullptr);
auto kernel = creator(inputs, outputs, reinterpret_cast<OpParameter *>(conv_param), &context, desc);
ASSERT_NE(kernel, nullptr);
auto ret = kernel->Init();
EXPECT_EQ(0, ret);
kernel->AllocWorkspace();
// runtime part
printf("Calculating runtime cost...\n");
uint64_t time_avg = 0;
int loop_count = 100;
auto time_start = mindspore::lite::GetTimeUs();
for (int i = 0; i < loop_count; i++) {
kernel->Run();
}
auto time_end = mindspore::lite::GetTimeUs();
auto cost = time_end - time_start;
time_avg = cost / loop_count;
printf("single thread running time : %f ms\n", time_avg / 1000.0f);
std::string output_path = "./test_data/deconv/deconvfp32_dw_d2_9_3_3_3.bin";
auto res = CompareRelativeOutput(dw_data, output_path);
EXPECT_EQ(res, 0);
delete[] input_data;
delete[] dy_data;
delete[] dw_data;
delete kernel;
// delete conv_param;
dw_tensor.set_data(nullptr);
x_tensor.set_data(nullptr);
dy_tensor.set_data(nullptr);
MS_LOG(INFO) << "TestDeConvolutionGradFp32 Filter Grad passed";
}
TEST_F(TestDeConvolutionGradFp32, DeConvFp32Dilation2Group3FilterGrad) {
// prepare stage
auto conv_param = static_cast<ConvParameter *>(malloc(sizeof(ConvParameter)));
ASSERT_NE(conv_param, nullptr);
conv_param->input_batch_ = 2;
conv_param->input_h_ = 32;
conv_param->input_w_ = 32;
conv_param->input_channel_ = 3;
conv_param->output_batch_ = 2;
conv_param->output_h_ = 65;
conv_param->output_w_ = 65;
conv_param->output_channel_ = 9;
conv_param->kernel_h_ = 3;
conv_param->kernel_w_ = 3;
conv_param->stride_h_ = 2;
conv_param->stride_w_ = 2;
conv_param->dilation_h_ = 2;
conv_param->dilation_w_ = 2;
conv_param->pad_u_ = 1;
conv_param->pad_l_ = 1;
conv_param->pad_r_ = 1;
conv_param->pad_d_ = 1;
conv_param->group_ = 3;
conv_param->act_type_ = ActType_No;
conv_param->thread_num_ = 1;
size_t dy_size;
std::string dy_path = "./test_data/deconv/deconvfp32_dy_d2_g3_2_9_65_65.bin";
auto dy_data = reinterpret_cast<float *>(mindspore::lite::ReadFile(dy_path.c_str(), &dy_size));
ASSERT_NE(dy_data, nullptr);
std::vector<int> dim_dy({2, 65, 65, 9});
lite::Tensor dy_tensor(TypeId::kNumberTypeFloat32, dim_dy);
dy_tensor.set_data(dy_data);
// runtime part
printf("Calculating runtime cost...\n");
uint64_t time_avg = 0;
size_t output_data_size =
conv_param->output_channel_ * conv_param->kernel_h_ * conv_param->kernel_w_ * conv_param->input_channel_;
size_t input_size;
std::string input_path = "./test_data/deconv/deconvfp32_input0_d2_g3_2_3_32_32.bin";
auto input_data = reinterpret_cast<float *>(mindspore::lite::ReadFile(input_path.c_str(), &input_size));
ASSERT_NE(input_data, nullptr);
std::vector<int> dim_x({2, 32, 32, 3});
lite::Tensor x_tensor(TypeId::kNumberTypeFloat32, dim_x);
x_tensor.set_data(input_data);
auto dw_data = new float[output_data_size];
ASSERT_NE(dw_data, nullptr);
std::vector<int> dim_dw({3, 3, 3, 3});
lite::Tensor dw_tensor(TypeId::kNumberTypeFloat32, dim_dw);
dw_tensor.set_data(dw_data);
std::vector<lite::Tensor *> inputs = {&dy_tensor, &x_tensor};
std::vector<lite::Tensor *> outputs = {&dw_tensor};
lite::InnerContext context;
context.thread_num_ = 1;
ASSERT_EQ(lite::RET_OK, context.Init());
kernel::KernelKey desc = {kernel::kCPU, TypeId::kNumberTypeFloat32, schema::PrimitiveType_DeConv2DGradFilter};
auto creator = lite::KernelRegistry::GetInstance()->GetCreator(desc);
ASSERT_NE(creator, nullptr);
auto kernel = creator(inputs, outputs, reinterpret_cast<OpParameter *>(conv_param), &context, desc);
ASSERT_NE(kernel, nullptr);
auto ret = kernel->Init();
EXPECT_EQ(0, ret);
kernel->AllocWorkspace();
// warm up loop
for (int i = 0; i < 3; i++) {
kernel->Run();
}
int loop_count = 100;
auto time_start = mindspore::lite::GetTimeUs();
for (int i = 0; i < loop_count; i++) {
kernel->Run();
}
auto time_end = mindspore::lite::GetTimeUs();
auto cost = time_end - time_start;
time_avg = cost / loop_count;
printf("single thread running time : %f ms\n", time_avg / 1000.0f);
std::string output_path = "./test_data/deconv/deconvfp32_dw_d2_g3_3_3_3_3.bin";
auto res = CompareRelativeOutput(dw_data, output_path);
EXPECT_EQ(res, 0);
delete[] input_data;
delete[] dy_data;
delete[] dw_data;
delete kernel;
// delete conv_param;
dw_tensor.set_data(nullptr);
x_tensor.set_data(nullptr);
dy_tensor.set_data(nullptr);
MS_LOG(INFO) << "TestDeConvolutionGradFp32 Filter Grad passed";
}
TEST_F(TestDeConvolutionGradFp32, DeConvFp32Dilation2Group3Stride1FilterGrad) {
// prepare stage
auto conv_param = static_cast<ConvParameter *>(malloc(sizeof(ConvParameter)));
ASSERT_NE(conv_param, nullptr);
conv_param->input_batch_ = 2;
conv_param->input_h_ = 32;
conv_param->input_w_ = 32;
conv_param->input_channel_ = 3;
conv_param->output_batch_ = 2;
conv_param->output_h_ = 34;
conv_param->output_w_ = 34;
conv_param->output_channel_ = 9;
conv_param->kernel_h_ = 3;
conv_param->kernel_w_ = 3;
conv_param->stride_h_ = 1;
conv_param->stride_w_ = 1;
conv_param->dilation_h_ = 2;
conv_param->dilation_w_ = 2;
conv_param->pad_u_ = 1;
conv_param->pad_l_ = 1;
conv_param->pad_r_ = 1;
conv_param->pad_d_ = 1;
conv_param->group_ = 3;
conv_param->act_type_ = ActType_No;
conv_param->thread_num_ = 1;
size_t dy_size;
std::string dy_path = "./test_data/deconv/deconvfp32_dy_d2_g3_s1_2_9_34_34.bin";
auto dy_data = reinterpret_cast<float *>(mindspore::lite::ReadFile(dy_path.c_str(), &dy_size));
ASSERT_NE(dy_data, nullptr);
std::vector<int> dim_dy({2, 34, 34, 9});
lite::Tensor dy_tensor(TypeId::kNumberTypeFloat32, dim_dy);
dy_tensor.set_data(dy_data);
size_t output_data_size =
conv_param->output_channel_ * conv_param->kernel_h_ * conv_param->kernel_w_ * conv_param->input_channel_;
size_t input_size;
std::string input_path = "./test_data/deconv/deconvfp32_input0_d2_g3_s1_2_3_32_32.bin";
auto input_data = reinterpret_cast<float *>(mindspore::lite::ReadFile(input_path.c_str(), &input_size));
ASSERT_NE(input_data, nullptr);
std::vector<int> dim_x({2, 32, 32, 3});
lite::Tensor x_tensor(TypeId::kNumberTypeFloat32, dim_x);
x_tensor.set_data(input_data);
auto dw_data = new float[output_data_size];
ASSERT_NE(dw_data, nullptr);
std::vector<int> dim_dw({3, 3, 3, 3});
lite::Tensor dw_tensor(TypeId::kNumberTypeFloat32, dim_dw);
dw_tensor.set_data(dw_data);
std::vector<lite::Tensor *> inputs = {&dy_tensor, &x_tensor};
std::vector<lite::Tensor *> outputs = {&dw_tensor};
lite::InnerContext context;
context.thread_num_ = 1;
ASSERT_EQ(lite::RET_OK, context.Init());
kernel::KernelKey desc = {kernel::kCPU, TypeId::kNumberTypeFloat32, schema::PrimitiveType_DeConv2DGradFilter};
auto creator = lite::KernelRegistry::GetInstance()->GetCreator(desc);
ASSERT_NE(creator, nullptr);
auto kernel = creator(inputs, outputs, reinterpret_cast<OpParameter *>(conv_param), &context, desc);
ASSERT_NE(kernel, nullptr);
auto ret = kernel->Init();
EXPECT_EQ(0, ret);
kernel->AllocWorkspace();
// warm up loop
for (int i = 0; i < 3; i++) {
kernel->Run();
}
// runtime part
printf("Calculating runtime cost...\n");
uint64_t time_avg = 0;
int loop_count = 100;
auto time_start = mindspore::lite::GetTimeUs();
for (int i = 0; i < loop_count; i++) {
kernel->Run();
}
auto time_end = mindspore::lite::GetTimeUs();
auto cost = time_end - time_start;
time_avg = cost / loop_count;
printf("single thread running time : %f ms\n", time_avg / 1000.0f);
std::string output_path = "./test_data/deconv/deconvfp32_dw_d2_g3_s1_3_3_3_3.bin";
auto res = CompareRelativeOutput(dw_data, output_path);
EXPECT_EQ(res, 0);
delete[] input_data;
delete[] dy_data;
delete[] dw_data;
delete kernel;
// delete conv_param;
dw_tensor.set_data(nullptr);
x_tensor.set_data(nullptr);
dy_tensor.set_data(nullptr);
MS_LOG(INFO) << "TestDeConvolutionGradFp32 Filter Grad passed";
}
TEST_F(TestDeConvolutionGradFp32, DeConvFp32Dilation2Group2Stride2FilterGrad) {
// prepare stage
auto conv_param = static_cast<ConvParameter *>(malloc(sizeof(ConvParameter)));
ASSERT_NE(conv_param, nullptr);
conv_param->input_batch_ = 2;
conv_param->input_h_ = 32;
conv_param->input_w_ = 32;
conv_param->input_channel_ = 4;
conv_param->output_batch_ = 2;
conv_param->output_h_ = 65;
conv_param->output_w_ = 65;
conv_param->output_channel_ = 12;
conv_param->kernel_h_ = 3;
conv_param->kernel_w_ = 3;
conv_param->stride_h_ = 2;
conv_param->stride_w_ = 2;
conv_param->dilation_h_ = 2;
conv_param->dilation_w_ = 2;
conv_param->pad_u_ = 1;
conv_param->pad_l_ = 1;
conv_param->pad_r_ = 1;
conv_param->pad_d_ = 1;
conv_param->group_ = 2;
conv_param->act_type_ = ActType_No;
conv_param->thread_num_ = 1;
size_t dy_size;
std::string dy_path = "./test_data/deconv/deconvfp32_dy_d2_g2_s2_2_12_65_65.bin";
auto dy_data = reinterpret_cast<float *>(mindspore::lite::ReadFile(dy_path.c_str(), &dy_size));
ASSERT_NE(dy_data, nullptr);
std::vector<int> dim_dy({2, 65, 65, 12});
lite::Tensor dy_tensor(TypeId::kNumberTypeFloat32, dim_dy);
dy_tensor.set_data(dy_data);
size_t output_data_size =
conv_param->output_channel_ * conv_param->kernel_h_ * conv_param->kernel_w_ * conv_param->input_channel_;
size_t input_size;
std::string input_path = "./test_data/deconv/deconvfp32_input0_d2_g2_s2_2_4_32_32.bin";
auto input_data = reinterpret_cast<float *>(mindspore::lite::ReadFile(input_path.c_str(), &input_size));
ASSERT_NE(input_data, nullptr);
std::vector<int> dim_x({2, 32, 32, 4});
lite::Tensor x_tensor(TypeId::kNumberTypeFloat32, dim_x);
x_tensor.set_data(input_data);
auto dw_data = new float[output_data_size];
ASSERT_NE(dw_data, nullptr);
std::vector<int> dim_dw({6, 3, 3, 4});
lite::Tensor dw_tensor(TypeId::kNumberTypeFloat32, dim_dw);
dw_tensor.set_data(dw_data);
std::vector<lite::Tensor *> inputs = {&dy_tensor, &x_tensor};
std::vector<lite::Tensor *> outputs = {&dw_tensor};
lite::InnerContext context;
context.thread_num_ = 1;
ASSERT_EQ(lite::RET_OK, context.Init());
kernel::KernelKey desc = {kernel::kCPU, TypeId::kNumberTypeFloat32, schema::PrimitiveType_DeConv2DGradFilter};
auto creator = lite::KernelRegistry::GetInstance()->GetCreator(desc);
ASSERT_NE(creator, nullptr);
auto kernel = creator(inputs, outputs, reinterpret_cast<OpParameter *>(conv_param), &context, desc);
ASSERT_NE(kernel, nullptr);
auto ret = kernel->Init();
EXPECT_EQ(0, ret);
kernel->AllocWorkspace();
// warm up loop
for (int i = 0; i < 3; i++) {
kernel->Run();
}
// runtime part
printf("Calculating runtime cost...\n");
uint64_t time_avg = 0;
int loop_count = 100;
auto time_start = mindspore::lite::GetTimeUs();
for (int i = 0; i < loop_count; i++) {
kernel->Run();
}
auto time_end = mindspore::lite::GetTimeUs();
auto cost = time_end - time_start;
time_avg = cost / loop_count;
printf("single thread running time : %f ms\n", time_avg / 1000.0f);
std::string output_path = "./test_data/deconv/deconvfp32_dw_d2_g2_s2_6_4_3_3.bin";
auto res = CompareRelativeOutput(dw_data, output_path);
EXPECT_EQ(res, 0);
delete[] input_data;
delete[] dy_data;
delete[] dw_data;
delete kernel;
// delete conv_param;
dw_tensor.set_data(nullptr);
x_tensor.set_data(nullptr);
dy_tensor.set_data(nullptr);
MS_LOG(INFO) << "TestDeConvolutionGradFp32 Filter Grad passed";
}
TEST_F(TestDeConvolutionGradFp32, DeConvFp32Dilation2Group12Stride2FilterGrad) {
// prepare stage
auto conv_param = static_cast<ConvParameter *>(malloc(sizeof(ConvParameter)));
ASSERT_NE(conv_param, nullptr);
conv_param->input_batch_ = 2;
conv_param->input_h_ = 32;
conv_param->input_w_ = 32;
conv_param->input_channel_ = 12;
conv_param->output_batch_ = 2;
conv_param->output_h_ = 65;
conv_param->output_w_ = 65;
conv_param->output_channel_ = 12;
conv_param->kernel_h_ = 3;
conv_param->kernel_w_ = 3;
conv_param->stride_h_ = 2;
conv_param->stride_w_ = 2;
conv_param->dilation_h_ = 2;
conv_param->dilation_w_ = 2;
conv_param->pad_u_ = 1;
conv_param->pad_l_ = 1;
conv_param->pad_r_ = 1;
conv_param->pad_d_ = 1;
conv_param->group_ = 12;
conv_param->act_type_ = ActType_No;
conv_param->thread_num_ = 1;
size_t dy_size;
std::string dy_path = "./test_data/deconv/deconvfp32_dy_d2_g12_s2_2_12_65_65.bin";
auto dy_data = reinterpret_cast<float *>(mindspore::lite::ReadFile(dy_path.c_str(), &dy_size));
ASSERT_NE(dy_data, nullptr);
std::vector<int> dim_dy({2, 65, 65, 12});
lite::Tensor dy_tensor(TypeId::kNumberTypeFloat32, dim_dy);
dy_tensor.set_data(dy_data);
// runtime part
printf("Calculating runtime cost...\n");
uint64_t time_avg = 0;
size_t output_data_size =
conv_param->output_channel_ * conv_param->kernel_h_ * conv_param->kernel_w_ * conv_param->input_channel_;
size_t input_size;
std::string input_path = "./test_data/deconv/deconvfp32_input0_d2_g12_s2_2_12_32_32.bin";
auto input_data = reinterpret_cast<float *>(mindspore::lite::ReadFile(input_path.c_str(), &input_size));
ASSERT_NE(input_data, nullptr);
std::vector<int> dim_x({2, 32, 32, 12});
lite::Tensor x_tensor(TypeId::kNumberTypeFloat32, dim_x);
x_tensor.set_data(input_data);
auto dw_data = new float[output_data_size];
ASSERT_NE(dw_data, nullptr);
std::vector<int> dim_dw({1, 3, 3, 12});
lite::Tensor dw_tensor(TypeId::kNumberTypeFloat32, dim_dw);
dw_tensor.set_data(dw_data);
std::vector<lite::Tensor *> inputs = {&dy_tensor, &x_tensor};
std::vector<lite::Tensor *> outputs = {&dw_tensor};
lite::InnerContext context;
context.thread_num_ = 1;
ASSERT_EQ(lite::RET_OK, context.Init());
kernel::KernelKey desc = {kernel::kCPU, TypeId::kNumberTypeFloat32, schema::PrimitiveType_DeConv2DGradFilter};
auto creator = lite::KernelRegistry::GetInstance()->GetCreator(desc);
ASSERT_NE(creator, nullptr);
auto kernel = creator(inputs, outputs, reinterpret_cast<OpParameter *>(conv_param), &context, desc);
ASSERT_NE(kernel, nullptr);
auto ret = kernel->Init();
EXPECT_EQ(0, ret);
kernel->AllocWorkspace();
// warm up loop
for (int i = 0; i < 3; i++) {
kernel->Run();
}
int loop_count = 100;
auto time_start = mindspore::lite::GetTimeUs();
for (int i = 0; i < loop_count; i++) {
kernel->Run();
}
auto time_end = mindspore::lite::GetTimeUs();
auto cost = time_end - time_start;
time_avg = cost / loop_count;
printf("single thread running time : %f ms\n", time_avg / 1000.0f);
std::string output_path = "./test_data/deconv/deconvfp32_dw_d2_g12_s2_12_1_3_3.bin";
auto res = CompareRelativeOutput(dw_data, output_path);
EXPECT_EQ(res, 0);
delete[] input_data;
delete[] dy_data;
delete[] dw_data;
delete kernel;
// delete conv_param;
dw_tensor.set_data(nullptr);
x_tensor.set_data(nullptr);
dy_tensor.set_data(nullptr);
MS_LOG(INFO) << "TestDeConvolutionGradFp32 Filter Grad passed";
}
} // namespace mindspore
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.